1 /////////////////////////////////////////////////////////////////////////////
4 // Author: Guilhem Lavaux
5 // Modified by: Vadim Zeitlin (modifications partly inspired by omnithreads
6 // package from Olivetti & Oracle Research Laboratory)
9 // Copyright: (c) Guilhem Lavaux
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
16 // ----------------------------------------------------------------------------
18 // ----------------------------------------------------------------------------
20 // get the value of wxUSE_THREADS configuration flag
25 // only for wxUSE_THREADS - otherwise we'd get undefined symbols
26 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
27 #pragma interface "thread.h"
30 // Windows headers define it
36 #include "wx/msw/wrapwin.h"
39 // ----------------------------------------------------------------------------
41 // ----------------------------------------------------------------------------
45 wxMUTEX_NO_ERROR
= 0, // operation completed successfully
46 wxMUTEX_INVALID
, // mutex hasn't been initialized
47 wxMUTEX_DEAD_LOCK
, // mutex is already locked by the calling thread
48 wxMUTEX_BUSY
, // mutex is already locked by another thread
49 wxMUTEX_UNLOCKED
, // attempt to unlock a mutex which is not locked
50 wxMUTEX_MISC_ERROR
// any other error
57 wxCOND_TIMEOUT
, // WaitTimeout() has timed out
64 wxSEMA_INVALID
, // semaphore hasn't been initialized successfully
65 wxSEMA_BUSY
, // returned by TryWait() if Wait() would block
66 wxSEMA_TIMEOUT
, // returned by WaitTimeout()
67 wxSEMA_OVERFLOW
, // Post() would increase counter past the max
73 wxTHREAD_NO_ERROR
= 0, // No error
74 wxTHREAD_NO_RESOURCE
, // No resource left to create a new thread
75 wxTHREAD_RUNNING
, // The thread is already running
76 wxTHREAD_NOT_RUNNING
, // The thread isn't running
77 wxTHREAD_KILLED
, // Thread we waited for had to be killed
78 wxTHREAD_MISC_ERROR
// Some other error
87 // defines the interval of priority
90 WXTHREAD_MIN_PRIORITY
= 0u,
91 WXTHREAD_DEFAULT_PRIORITY
= 50u,
92 WXTHREAD_MAX_PRIORITY
= 100u
95 // There are 2 types of mutexes: normal mutexes and recursive ones. The attempt
96 // to lock a normal mutex by a thread which already owns it results in
97 // undefined behaviour (it always works under Windows, it will almost always
98 // result in a deadlock under Unix). Locking a recursive mutex in such
99 // situation always succeeds and it must be unlocked as many times as it has
102 // However recursive mutexes have several important drawbacks: first, in the
103 // POSIX implementation, they're less efficient. Second, and more importantly,
104 // they CAN NOT BE USED WITH CONDITION VARIABLES under Unix! Using them with
105 // wxCondition will work under Windows and some Unices (notably Linux) but will
106 // deadlock under other Unix versions (e.g. Solaris). As it might be difficult
107 // to ensure that a recursive mutex is not used with wxCondition, it is a good
108 // idea to avoid using recursive mutexes at all. Also, the last problem with
109 // them is that some (older) Unix versions don't support this at all -- which
110 // results in a configure warning when building and a deadlock when using them.
113 // normal mutex: try to always use this one
116 // recursive mutex: don't use these ones with wxCondition
120 // forward declarations
121 class WXDLLIMPEXP_BASE wxThreadHelper
;
122 class WXDLLIMPEXP_BASE wxConditionInternal
;
123 class WXDLLIMPEXP_BASE wxMutexInternal
;
124 class WXDLLIMPEXP_BASE wxSemaphoreInternal
;
125 class WXDLLIMPEXP_BASE wxThreadInternal
;
127 // ----------------------------------------------------------------------------
128 // A mutex object is a synchronization object whose state is set to signaled
129 // when it is not owned by any thread, and nonsignaled when it is owned. Its
130 // name comes from its usefulness in coordinating mutually-exclusive access to
131 // a shared resource. Only one thread at a time can own a mutex object.
132 // ----------------------------------------------------------------------------
134 // you should consider wxMutexLocker whenever possible instead of directly
135 // working with wxMutex class - it is safer
136 class WXDLLIMPEXP_BASE wxMutex
139 // constructor & destructor
140 // ------------------------
142 // create either default (always safe) or recursive mutex
143 wxMutex(wxMutexType mutexType
= wxMUTEX_DEFAULT
);
145 // destroys the mutex kernel object
148 // test if the mutex has been created successfully
154 // Lock the mutex, blocking on it until it is unlocked by the other thread.
155 // The result of locking a mutex already locked by the current thread
156 // depend on the mutex type.
158 // The caller must call Unlock() later if Lock() returned wxMUTEX_NO_ERROR.
161 // Try to lock the mutex: if it is currently locked, return immediately
162 // with an error. Otherwise the caller must call Unlock().
163 wxMutexError
TryLock();
165 // Unlock the mutex. It is an error to unlock an already unlocked mutex
166 wxMutexError
Unlock();
169 wxMutexInternal
*m_internal
;
171 friend class wxConditionInternal
;
173 DECLARE_NO_COPY_CLASS(wxMutex
)
176 // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
177 // this ensures that mutex is always unlocked, even if the function returns or
178 // throws an exception before it reaches the end
179 class WXDLLIMPEXP_BASE wxMutexLocker
182 // lock the mutex in the ctor
183 wxMutexLocker(wxMutex
& mutex
)
184 : m_isOk(false), m_mutex(mutex
)
185 { m_isOk
= ( m_mutex
.Lock() == wxMUTEX_NO_ERROR
); }
187 // returns true if mutex was successfully locked in ctor
191 // unlock the mutex in dtor
193 { if ( IsOk() ) m_mutex
.Unlock(); }
196 // no assignment operator nor copy ctor
197 wxMutexLocker(const wxMutexLocker
&);
198 wxMutexLocker
& operator=(const wxMutexLocker
&);
204 // ----------------------------------------------------------------------------
205 // Critical section: this is the same as mutex but is only visible to the
206 // threads of the same process. For the platforms which don't have native
207 // support for critical sections, they're implemented entirely in terms of
210 // NB: wxCriticalSection object does not allocate any memory in its ctor
211 // which makes it possible to have static globals of this class
212 // ----------------------------------------------------------------------------
214 // in order to avoid any overhead under platforms where critical sections are
215 // just mutexes make all wxCriticalSection class functions inline
216 #if !defined(__WXMSW__) && !defined(__WXMAC__)
217 #define wxCRITSECT_IS_MUTEX 1
219 #define wxCRITSECT_INLINE inline
221 #define wxCRITSECT_IS_MUTEX 0
223 #define wxCRITSECT_INLINE
226 // you should consider wxCriticalSectionLocker whenever possible instead of
227 // directly working with wxCriticalSection class - it is safer
228 class WXDLLIMPEXP_BASE wxCriticalSection
232 wxCRITSECT_INLINE
wxCriticalSection();
233 wxCRITSECT_INLINE
~wxCriticalSection();
235 // enter the section (the same as locking a mutex)
236 wxCRITSECT_INLINE
void Enter();
238 // leave the critical section (same as unlocking a mutex)
239 wxCRITSECT_INLINE
void Leave();
242 #if wxCRITSECT_IS_MUTEX
244 #elif defined(__WXMSW__)
245 // we can't allocate any memory in the ctor, so use placement new -
246 // unfortunately, we have to hardcode the sizeof() here because we can't
247 // include windows.h from this public header and we also have to use the
248 // union to force the correct (i.e. maximal) alignment
250 // if CRITICAL_SECTION size changes in Windows, you'll get an assert below
252 // finally, we need this typedef instead of declaring m_buffer directly
253 // because otherwise the assert mentioned above wouldn't compile with some
254 // compilers (notably CodeWarrior 8)
256 typedef char wxCritSectBuffer
[40];
258 typedef char wxCritSectBuffer
[24];
261 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
262 wxCriticalSectionBufferTooSmall
);
266 unsigned long m_dummy1
;
269 wxCritSectBuffer m_buffer
;
271 #elif defined(__WXMAC__)
273 #endif // Unix&OS2/Win32
275 DECLARE_NO_COPY_CLASS(wxCriticalSection
)
278 #if wxCRITSECT_IS_MUTEX
279 // implement wxCriticalSection using mutexes
280 inline wxCriticalSection::wxCriticalSection() { }
281 inline wxCriticalSection::~wxCriticalSection() { }
283 inline void wxCriticalSection::Enter() { (void)m_mutex
.Lock(); }
284 inline void wxCriticalSection::Leave() { (void)m_mutex
.Unlock(); }
285 #endif // wxCRITSECT_IS_MUTEX
287 #undef wxCRITSECT_INLINE
288 #undef wxCRITSECT_IS_MUTEX
290 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
292 class WXDLLIMPEXP_BASE wxCriticalSectionLocker
295 wxCriticalSectionLocker(wxCriticalSection
& cs
)
301 ~wxCriticalSectionLocker()
307 wxCriticalSection
& m_critsect
;
309 DECLARE_NO_COPY_CLASS(wxCriticalSectionLocker
)
312 // ----------------------------------------------------------------------------
313 // wxCondition models a POSIX condition variable which allows one (or more)
314 // thread(s) to wait until some condition is fulfilled
315 // ----------------------------------------------------------------------------
317 class WXDLLIMPEXP_BASE wxCondition
320 // Each wxCondition object is associated with a (single) wxMutex object.
321 // The mutex object MUST be locked before calling Wait()
322 wxCondition(wxMutex
& mutex
);
324 // dtor is not virtual, don't use this class polymorphically
327 // return true if the condition has been created successfully
330 // NB: the associated mutex MUST be locked beforehand by the calling thread
332 // it atomically releases the lock on the associated mutex
333 // and starts waiting to be woken up by a Signal()/Broadcast()
334 // once its signaled, then it will wait until it can reacquire
335 // the lock on the associated mutex object, before returning.
338 // exactly as Wait() except that it may also return if the specified
339 // timeout ellapses even if the condition hasn't been signalled: in this
340 // case, the return value is false, otherwise (i.e. in case of a normal
341 // return) it is true
343 // the timeeout parameter specifies a interval that needs to be waited in
345 wxCondError
WaitTimeout(unsigned long milliseconds
);
347 // NB: the associated mutex may or may not be locked by the calling thread
349 // this method unblocks one thread if any are blocking on the condition.
350 // if no thread is blocking in Wait(), then the signal is NOT remembered
351 // The thread which was blocking on Wait(), will then reacquire the lock
352 // on the associated mutex object before returning
353 wxCondError
Signal();
355 // NB: the associated mutex may or may not be locked by the calling thread
357 // this method unblocks all threads if any are blocking on the condition.
358 // if no thread is blocking in Wait(), then the signal is NOT remembered
359 // The threads which were blocking on Wait(), will then reacquire the lock
360 // on the associated mutex object before returning.
361 wxCondError
Broadcast();
364 // deprecated version, don't use
365 bool Wait(unsigned long milliseconds
)
366 { return WaitTimeout(milliseconds
) == wxCOND_NO_ERROR
; }
369 wxConditionInternal
*m_internal
;
371 DECLARE_NO_COPY_CLASS(wxCondition
)
374 // ----------------------------------------------------------------------------
375 // wxSemaphore: a counter limiting the number of threads concurrently accessing
377 // ----------------------------------------------------------------------------
379 class WXDLLIMPEXP_BASE wxSemaphore
382 // specifying a maxcount of 0 actually makes wxSemaphore behave as if there
383 // is no upper limit, if maxcount is 1 the semaphore behaves as a mutex
384 wxSemaphore( int initialcount
= 0, int maxcount
= 0 );
386 // dtor is not virtual, don't use this class polymorphically
389 // return true if the semaphore has been created successfully
392 // wait indefinitely, until the semaphore count goes beyond 0
393 // and then decrement it and return (this method might have been called
397 // same as Wait(), but does not block, returns wxSEMA_NO_ERROR if
398 // successful and wxSEMA_BUSY if the count is currently zero
399 wxSemaError
TryWait();
401 // same as Wait(), but as a timeout limit, returns wxSEMA_NO_ERROR if the
402 // semaphore was acquired and wxSEMA_TIMEOUT if the timeout has ellapsed
403 wxSemaError
WaitTimeout(unsigned long milliseconds
);
405 // increments the semaphore count and signals one of the waiting threads
409 wxSemaphoreInternal
*m_internal
;
411 DECLARE_NO_COPY_CLASS(wxSemaphore
)
414 // ----------------------------------------------------------------------------
415 // wxThread: class encapsulating a thread of execution
416 // ----------------------------------------------------------------------------
418 // there are two different kinds of threads: joinable and detached (default)
419 // ones. Only joinable threads can return a return code and only detached
420 // threads auto-delete themselves - the user should delete the joinable
423 // NB: in the function descriptions the words "this thread" mean the thread
424 // created by the wxThread object while "main thread" is the thread created
425 // during the process initialization (a.k.a. the GUI thread)
427 // On VMS thread pointers are 64 bits (also needed for other systems???
429 typedef unsigned long long wxThreadIdType
;
431 typedef unsigned long wxThreadIdType
;
434 class WXDLLIMPEXP_BASE wxThread
437 // the return type for the thread function
438 typedef void *ExitCode
;
441 // Returns the wxThread object for the calling thread. NULL is returned
442 // if the caller is the main thread (but it's recommended to use
443 // IsMain() and only call This() for threads other than the main one
444 // because NULL is also returned on error). If the thread wasn't
445 // created with wxThread class, the returned value is undefined.
446 static wxThread
*This();
448 // Returns true if current thread is the main thread.
449 static bool IsMain();
451 // Release the rest of our time slice leting the other threads run
454 // Sleep during the specified period of time in milliseconds
456 // NB: at least under MSW worker threads can not call ::wxSleep()!
457 static void Sleep(unsigned long milliseconds
);
459 // get the number of system CPUs - useful with SetConcurrency()
460 // (the "best" value for it is usually number of CPUs + 1)
462 // Returns -1 if unknown, number of CPUs otherwise
463 static int GetCPUCount();
465 // Get the platform specific thread ID and return as a long. This
466 // can be used to uniquely identify threads, even if they are not
467 // wxThreads. This is used by wxPython.
468 static wxThreadIdType
GetCurrentId();
470 // sets the concurrency level: this is, roughly, the number of threads
471 // the system tries to schedule to run in parallel. 0 means the
472 // default value (usually acceptable, but may not yield the best
473 // performance for this process)
475 // Returns true on success, false otherwise (if not implemented, for
477 static bool SetConcurrency(size_t level
);
479 // constructor only creates the C++ thread object and doesn't create (or
480 // start) the real thread
481 wxThread(wxThreadKind kind
= wxTHREAD_DETACHED
);
483 // functions that change the thread state: all these can only be called
484 // from _another_ thread (typically the thread that created this one, e.g.
485 // the main thread), not from the thread itself
487 // create a new thread and optionally set the stack size on
488 // platforms that support that - call Run() to start it
489 // (special cased for watcom which won't accept 0 default)
491 wxThreadError
Create(unsigned int stackSize
= 0);
493 // starts execution of the thread - from the moment Run() is called
494 // the execution of wxThread::Entry() may start at any moment, caller
495 // shouldn't suppose that it starts after (or before) Run() returns.
498 // stops the thread if it's running and deletes the wxThread object if
499 // this is a detached thread freeing its memory - otherwise (for
500 // joinable threads) you still need to delete wxThread object
503 // this function only works if the thread calls TestDestroy()
504 // periodically - the thread will only be deleted the next time it
507 // will fill the rc pointer with the thread exit code if it's !NULL
508 wxThreadError
Delete(ExitCode
*rc
= (ExitCode
*)NULL
);
510 // waits for a joinable thread to finish and returns its exit code
512 // Returns (ExitCode)-1 on error (for example, if the thread is not
516 // kills the thread without giving it any chance to clean up - should
517 // not be used in normal circumstances, use Delete() instead. It is a
518 // dangerous function that should only be used in the most extreme
521 // The wxThread object is deleted by Kill() if the thread is
522 // detachable, but you still have to delete it manually for joinable
524 wxThreadError
Kill();
526 // pause a running thread: as Delete(), this only works if the thread
527 // calls TestDestroy() regularly
528 wxThreadError
Pause();
530 // resume a paused thread
531 wxThreadError
Resume();
534 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
536 // NB: the priority can only be set before the thread is created
537 void SetPriority(unsigned int prio
);
539 // Get the current priority.
540 unsigned int GetPriority() const;
542 // thread status inquiries
543 // Returns true if the thread is alive: i.e. running or suspended
544 bool IsAlive() const;
545 // Returns true if the thread is running (not paused, not killed).
546 bool IsRunning() const;
547 // Returns true if the thread is suspended
548 bool IsPaused() const;
550 // is the thread of detached kind?
551 bool IsDetached() const { return m_isDetached
; }
553 // Get the thread ID - a platform dependent number which uniquely
554 // identifies a thread inside a process
555 wxThreadIdType
GetId() const;
557 // called when the thread exits - in the context of this thread
559 // NB: this function will not be called if the thread is Kill()ed
560 virtual void OnExit() { }
562 // Returns true if the thread was asked to terminate: this function should
563 // be called by the thread from time to time, otherwise the main thread
564 // will be left forever in Delete()!
565 virtual bool TestDestroy();
567 // dtor is public, but the detached threads should never be deleted - use
568 // Delete() instead (or leave the thread terminate by itself)
572 // exits from the current thread - can be called only from this thread
573 void Exit(ExitCode exitcode
= 0);
575 // entry point for the thread - called by Run() and executes in the context
577 virtual void *Entry() = 0;
580 // no copy ctor/assignment operator
581 wxThread(const wxThread
&);
582 wxThread
& operator=(const wxThread
&);
584 friend class wxThreadInternal
;
586 // the (platform-dependent) thread class implementation
587 wxThreadInternal
*m_internal
;
589 // protects access to any methods of wxThreadInternal object
590 wxCriticalSection m_critsect
;
592 // true if the thread is detached, false if it is joinable
596 // wxThreadHelperThread class
597 // --------------------------
599 class WXDLLIMPEXP_BASE wxThreadHelperThread
: public wxThread
602 // constructor only creates the C++ thread object and doesn't create (or
603 // start) the real thread
604 wxThreadHelperThread(wxThreadHelper
& owner
)
605 : wxThread(wxTHREAD_JOINABLE
), m_owner(owner
)
609 // entry point for the thread -- calls Entry() in owner.
610 virtual void *Entry();
613 // the owner of the thread
614 wxThreadHelper
& m_owner
;
616 // no copy ctor/assignment operator
617 wxThreadHelperThread(const wxThreadHelperThread
&);
618 wxThreadHelperThread
& operator=(const wxThreadHelperThread
&);
621 // ----------------------------------------------------------------------------
622 // wxThreadHelper: this class implements the threading logic to run a
623 // background task in another object (such as a window). It is a mix-in: just
624 // derive from it to implement a threading background task in your class.
625 // ----------------------------------------------------------------------------
627 class WXDLLIMPEXP_BASE wxThreadHelper
640 // constructor only initializes m_thread to NULL
641 wxThreadHelper() : m_thread(NULL
) { }
643 // destructor deletes m_thread
644 virtual ~wxThreadHelper() { KillThread(); }
646 // create a new thread (and optionally set the stack size on platforms that
647 // support/need that), call Run() to start it
648 wxThreadError
Create(unsigned int stackSize
= 0)
652 m_thread
= new wxThreadHelperThread(*this);
654 return m_thread
->Create(stackSize
);
657 // entry point for the thread - called by Run() and executes in the context
659 virtual void *Entry() = 0;
661 // returns a pointer to the thread which can be used to call Run()
662 wxThread
*GetThread() const { return m_thread
; }
668 // call Entry() in owner, put it down here to avoid circular declarations
669 inline void *wxThreadHelperThread::Entry()
671 return m_owner
.Entry();
674 // ----------------------------------------------------------------------------
675 // Automatic initialization
676 // ----------------------------------------------------------------------------
678 // GUI mutex handling.
679 void WXDLLIMPEXP_BASE
wxMutexGuiEnter();
680 void WXDLLIMPEXP_BASE
wxMutexGuiLeave();
682 // macros for entering/leaving critical sections which may be used without
683 // having to take them inside "#if wxUSE_THREADS"
684 #define wxENTER_CRIT_SECT(cs) (cs).Enter()
685 #define wxLEAVE_CRIT_SECT(cs) (cs).Leave()
686 #define wxCRIT_SECT_DECLARE(cs) static wxCriticalSection cs
687 #define wxCRIT_SECT_DECLARE_MEMBER(cs) wxCriticalSection cs
688 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(cs)
690 // function for checking if we're in the main thread which may be used whether
691 // wxUSE_THREADS is 0 or 1
692 inline bool wxIsMainThread() { return wxThread::IsMain(); }
694 #else // !wxUSE_THREADS
697 inline void WXDLLIMPEXP_BASE
wxMutexGuiEnter() { }
698 inline void WXDLLIMPEXP_BASE
wxMutexGuiLeave() { }
700 // macros for entering/leaving critical sections which may be used without
701 // having to take them inside "#if wxUSE_THREADS"
702 #define wxENTER_CRIT_SECT(cs)
703 #define wxLEAVE_CRIT_SECT(cs)
704 #define wxCRIT_SECT_DECLARE(cs)
705 #define wxCRIT_SECT_DECLARE_MEMBER(cs)
706 #define wxCRIT_SECT_LOCKER(name, cs)
708 // if there is only one thread, it is always the main one
709 inline bool wxIsMainThread() { return true; }
711 #endif // wxUSE_THREADS/!wxUSE_THREADS
713 // mark part of code as being a critical section: this macro declares a
714 // critical section with the given name and enters it immediately and leaves
715 // it at the end of the current scope
721 // static int s_counter = 0;
723 // wxCRITICAL_SECTION(counter);
725 // return ++s_counter;
728 // this function is MT-safe in presence of the threads but there is no
729 // overhead when the library is compiled without threads
730 #define wxCRITICAL_SECTION(name) \
731 wxCRIT_SECT_DECLARE(s_cs##name); \
732 wxCRIT_SECT_LOCKER(cs##name##Locker, s_cs##name)
734 // automatically lock GUI mutex in ctor and unlock it in dtor
735 class WXDLLIMPEXP_BASE wxMutexGuiLocker
738 wxMutexGuiLocker() { wxMutexGuiEnter(); }
739 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
742 // -----------------------------------------------------------------------------
743 // implementation only until the end of file
744 // -----------------------------------------------------------------------------
748 #if defined(__WXMSW__) || defined(__WXMAC__) || defined(__WXPM__) || defined(__EMX__)
749 // unlock GUI if there are threads waiting for and lock it back when
750 // there are no more of them - should be called periodically by the main
752 extern void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter();
754 // returns true if the main thread has GUI lock
755 extern bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread();
758 // wakes up the main thread if it's sleeping inside ::GetMessage()
759 extern void WXDLLIMPEXP_BASE
wxWakeUpMainThread();
762 // return true if the main thread is waiting for some other to terminate:
763 // wxApp then should block all "dangerous" messages
764 extern bool WXDLLIMPEXP_BASE
wxIsWaitingForThread();
765 #endif // MSW, Mac, OS/2
767 #endif // wxUSE_THREADS
769 #endif // _WX_THREAD_H_