]>
git.saurik.com Git - apple/security.git/blob - OSX/libsecurity_utilities/lib/threading.h
2 * Copyright (c) 2000-2004,2011,2014 Apple Inc. All Rights Reserved.
4 * @APPLE_LICENSE_HEADER_START@
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. Please obtain a copy of the License at
10 * http://www.opensource.apple.com/apsl/ and read it before using this
13 * The Original Code and all software distributed under the License are
14 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
15 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
16 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
17 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
18 * Please see the License for the specific language governing rights and
19 * limitations under the License.
21 * @APPLE_LICENSE_HEADER_END@
26 // threading - multi-threading support
28 // Once upon a time, this file provided a system-independent abstraction layer
29 // for various thread models. These times are long gone, and we might as well
30 // admit that we're sitting on top of pthreads (plus certain other system facilities).
35 #include <security_utilities/utilities.h>
36 #include <security_utilities/errors.h>
37 #include <security_utilities/debugging.h>
40 #include <security_utilities/threading_internal.h>
47 // Potentially, debug-logging all Mutex activity can really ruin your
48 // performance day. We take some measures to reduce the impact, but if
49 // you really can't stomach any overhead, define THREAD_NDEBUG to turn
50 // (only) thread debug-logging off. NDEBUG will turn this on automatically.
51 // On the other hand, throwing out all debug code will change the ABI of
52 // Mutexi in incompatible ways. Thus, we still generate the debug-style out-of-line
53 // code even with THREAD_NDEBUG, so that debug-style code will work with us.
54 // If you want to ditch it completely, #define THREAD_CLEAN_NDEBUG.
56 #if defined(NDEBUG) || defined(THREAD_CLEAN_NDEBUG)
57 # if !defined(THREAD_NDEBUG)
58 # define THREAD_NDEBUG
64 // An abstraction of a per-thread untyped storage slot of pointer size.
65 // Do not use this in ordinary code; this is for implementing other primitives only.
66 // Use a PerThreadPointer or ThreadNexus.
68 class ThreadStoreSlot
{
70 typedef void Destructor(void *);
71 ThreadStoreSlot(Destructor
*destructor
= NULL
);
74 void *get() const { return pthread_getspecific(mKey
); }
75 operator void * () const { return get(); }
76 void operator = (void *value
) const
78 if (int err
= pthread_setspecific(mKey
, value
))
79 UnixError::throwMe(err
);
88 // Per-thread pointers are implemented using the pthread TLS (thread local storage)
90 // Let's be clear on what gets destroyed when, here. Following the pthread lead,
91 // when a thread dies its PerThreadPointer object(s) are properly destroyed.
92 // However, if a PerThreadPointer itself is destroyed, NOTHING HAPPENS. Yes, there are
93 // reasons for this. This is not (on its face) a bug, so don't yell. But be aware...
96 class PerThreadPointer
: public ThreadStoreSlot
{
98 PerThreadPointer(bool cleanup
= true) : ThreadStoreSlot(cleanup
? destructor
: NULL
) { }
99 operator bool() const { return get() != NULL
; }
100 operator T
* () const { return reinterpret_cast<T
*>(get()); }
101 T
*operator -> () const { return static_cast<T
*>(*this); }
102 T
&operator * () const { return *static_cast<T
*>(get()); }
103 void operator = (T
*t
) { ThreadStoreSlot::operator = (t
); }
106 static void destructor(void *element
)
107 { delete reinterpret_cast<T
*>(element
); }
112 // Pthread Synchronization primitives.
113 // These have a common header, strictly for our convenience.
115 class LockingPrimitive
{
117 LockingPrimitive() { }
119 void check(int err
) { if (err
) UnixError::throwMe(err
); }
126 class Mutex
: public LockingPrimitive
{
128 friend class Condition
;
137 Mutex(Type type
); // recursive
138 ~Mutex(); // destroy (must be unlocked)
139 void lock(); // lock and wait
140 bool tryLock(); // instantaneous lock (return false if busy)
141 void unlock(); // unlock (must be locked)
148 class RecursiveMutex
: public Mutex
151 RecursiveMutex() : Mutex(recursive
) {}
156 // Condition variables
158 class Condition
: public LockingPrimitive
{
162 Condition(Mutex
&mutex
); // create with specific Mutex
164 void wait(); // wait for signal
165 void signal(); // signal one
166 void broadcast(); // signal all
168 Mutex
&mutex
; // associated Mutex
176 // A CountingMutex adds a counter to a Mutex.
177 // NOTE: This is not officially a semaphore - it's an automatically managed
178 // counter married to a Mutex.
180 class CountingMutex
: public Mutex
{
182 CountingMutex() : mCount(0) { }
183 ~CountingMutex() { assert(mCount
== 0); }
185 void enter(); // lock, add one, unlock
186 bool tryEnter(); // enter or return false
187 void exit(); // lock, subtract one, unlock
189 // these methods do not lock - use only while you hold the lock
190 unsigned int count() const { return mCount
; }
191 bool isIdle() const { return mCount
== 0; }
193 // convert Mutex lock to CountingMutex enter/exit. Expert use only
194 void finishEnter(); // all but the initial lock
195 void finishExit(); // all but the initial lock
198 unsigned int mCount
; // counter level
202 // A ReadWriteLock is a wrapper around a pthread_rwlock
204 class ReadWriteLock
: public Mutex
{
207 ~ReadWriteLock() { check(pthread_rwlock_destroy(&mLock
)); }
209 // Takes the read lock
218 pthread_rwlock_t mLock
;
223 // A guaranteed-unlocker stack-based class.
224 // By default, this will use lock/unlock methods, but you can provide your own
225 // alternates (to, e.g., use enter/exit, or some more specialized pair of operations).
227 // NOTE: StLock itself is not thread-safe. It is intended for use (usually on the stack)
228 // by a single thread.
230 template <class Lock
,
231 void (Lock::*_lock
)() = &Lock::lock
,
232 void (Lock::*_unlock
)() = &Lock::unlock
>
235 StLock(Lock
&lck
) : me(lck
) { (me
.*_lock
)(); mActive
= true; }
236 StLock(Lock
&lck
, bool option
) : me(lck
), mActive(option
) { }
237 ~StLock() { if (mActive
) (me
.*_unlock
)(); }
239 bool isActive() const { return mActive
; }
240 void lock() { if(!mActive
) { (me
.*_lock
)(); mActive
= true; }}
241 void unlock() { if(mActive
) { (me
.*_unlock
)(); mActive
= false; }}
242 void release() { assert(mActive
); mActive
= false; }
244 operator const Lock
&() const { return me
; }
252 // This class behaves exactly as StLock above, but accepts a pointer to a mutex instead of a reference.
253 // If the pointer is NULL, this class does nothing. Otherwise, it behaves as StLock.
254 // Try not to use this.
256 template <class Lock
,
257 void (Lock::*_lock
)() = &Lock::lock
,
258 void (Lock::*_unlock
)() = &Lock::unlock
>
261 StMaybeLock(Lock
*lck
) : me(lck
), mActive(false)
262 { if(me
) { (me
->*_lock
)(); mActive
= true; } }
263 StMaybeLock(Lock
*lck
, bool option
) : me(lck
), mActive(option
) { }
264 ~StMaybeLock() { if (me
) { if(mActive
) (me
->*_unlock
)(); } else {mActive
= false;} }
266 bool isActive() const { return mActive
; }
267 void lock() { if(me
) { if(!mActive
) { (me
->*_lock
)(); mActive
= true; }}}
268 void unlock() { if(me
) { if(mActive
) { (me
->*_unlock
)(); mActive
= false; }}}
269 void release() { if(me
) { assert(mActive
); mActive
= false; } }
271 operator const Lock
&() const { return me
; }
278 // Note: if you use the TryRead or TryWrite modes, you must check if you
279 // actually have the lock before proceeding
280 class StReadWriteLock
{
288 StReadWriteLock(ReadWriteLock
&lck
, Type type
) : mType(type
), mIsLocked(false), mRWLock(lck
)
290 ~StReadWriteLock() { if(mIsLocked
) unlock(); }
299 ReadWriteLock
& mRWLock
;
303 template <class TakeLock
, class ReleaseLock
,
304 void (TakeLock::*_lock
)() = &TakeLock::lock
,
305 void (TakeLock::*_unlock
)() = &TakeLock::unlock
,
306 void (ReleaseLock::*_rlock
)() = &ReleaseLock::lock
,
307 void (ReleaseLock::*_runlock
)() = &ReleaseLock::unlock
>
310 StSyncLock(TakeLock
&tlck
, ReleaseLock
&rlck
) : taken(tlck
), released(rlck
) {
311 (released
.*_unlock
)();
315 StSyncLock(TakeLock
&tlck
, ReleaseLock
&rlck
, bool option
) : taken(tlck
), released(rlck
), mActive(option
) { }
316 ~StSyncLock() { if (mActive
) { (taken
.*_unlock
)(); (released
.*_rlock
)(); }}
318 bool isActive() const { return mActive
; }
319 void lock() { if(!mActive
) { (released
.*_runlock
)(); (taken
.*_lock
)(); mActive
= true; }}
320 void unlock() { if(mActive
) { (taken
.*_unlock
)(); (released
.*_rlock
)(); mActive
= false; }}
321 void release() { assert(mActive
); mActive
= false; }
325 ReleaseLock
&released
;
331 // Atomic increment/decrement operations.
332 // The default implementation uses a Mutex. However, many architectures can do
333 // much better than that.
334 // Be very clear on the nature of AtomicCounter. It implies no memory barriers of
335 // any kind. This means that (1) you cannot protect any other memory region with it
336 // (use a Mutex for that), and (2) it may not enforce cross-processor ordering, which
337 // means that you have no guarantee that you'll see modifications by other processors
338 // made earlier (unless another mechanism provides the memory barrier).
339 // On the other hand, if your compiler has brains, this is blindingly fast...
341 template <class Integer
= uint32_t>
342 class StaticAtomicCounter
{
347 operator Integer() const { return mValue
; }
349 // infix versions (primary)
350 Integer
operator ++ () { return Atomic
<Integer
>::increment(mValue
); }
351 Integer
operator -- () { return Atomic
<Integer
>::decrement(mValue
); }
354 Integer
operator ++ (int) { return Atomic
<Integer
>::increment(mValue
) - 1; }
355 Integer
operator -- (int) { return Atomic
<Integer
>::decrement(mValue
) + 1; }
358 Integer
operator += (int delta
) { return Atomic
<Integer
>::add(delta
, mValue
); }
362 template <class Integer
= int>
363 class AtomicCounter
: public StaticAtomicCounter
<Integer
> {
365 AtomicCounter(Integer init
= 0) { StaticAtomicCounter
<Integer
>::mValue
= init
; }
370 // A class implementing a separate thread of execution.
371 // Do not expect many high-level semantics to be portable. If you can,
372 // restrict yourself to expect parallel execution and little else.
380 Identity(pthread_t id
) : mIdent(id
) { }
384 static Identity
current() { return pthread_self(); }
386 bool operator == (const Identity
&other
) const
387 { return pthread_equal(mIdent
, other
.mIdent
); }
389 bool operator != (const Identity
&other
) const
390 { return !(*this == other
); }
397 Thread() { } // constructor
398 virtual ~Thread(); // virtual destructor
399 void run(); // begin running the thread
402 static void yield(); // unstructured short-term processor yield
405 virtual void action() = 0; // the action to be performed
408 Identity self
; // my own identity (instance constant)
410 static void *runner(void *); // argument to pthread_create
415 // A "just run this function in a thread" variant of Thread
417 class ThreadRunner
: public Thread
{
418 typedef void Action();
420 ThreadRunner(Action
*todo
);
428 } // end namespace Security
430 #endif //_H_THREADING