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
27 #pragma interface "thread.h"
30 // Windows headers define it
35 #include "wx/module.h"
37 // ----------------------------------------------------------------------------
39 // ----------------------------------------------------------------------------
44 wxMUTEX_DEAD_LOCK
, // Mutex has been already locked by THE CALLING thread
45 wxMUTEX_BUSY
, // Mutex has been already locked by ONE thread
52 wxTHREAD_NO_ERROR
= 0, // No error
53 wxTHREAD_NO_RESOURCE
, // No resource left to create a new thread
54 wxTHREAD_RUNNING
, // The thread is already running
55 wxTHREAD_NOT_RUNNING
, // The thread isn't running
56 wxTHREAD_KILLED
, // Thread we waited for had to be killed
57 wxTHREAD_MISC_ERROR
// Some other error
66 // defines the interval of priority
69 WXTHREAD_MIN_PRIORITY
= 0u,
70 WXTHREAD_DEFAULT_PRIORITY
= 50u,
71 WXTHREAD_MAX_PRIORITY
= 100u
74 // ----------------------------------------------------------------------------
75 // A mutex object is a synchronization object whose state is set to signaled
76 // when it is not owned by any thread, and nonsignaled when it is owned. Its
77 // name comes from its usefulness in coordinating mutually-exclusive access to
78 // a shared resource. Only one thread at a time can own a mutex object.
79 // ----------------------------------------------------------------------------
81 // you should consider wxMutexLocker whenever possible instead of directly
82 // working with wxMutex class - it is safer
83 class WXDLLEXPORT wxMutexInternal
;
84 class WXDLLEXPORT wxMutex
87 // constructor & destructor
93 // Try to lock the mutex: if it can't, returns immediately with an error.
94 wxMutexError
TryLock();
96 wxMutexError
Unlock();
98 // Returns true if the mutex is locked.
99 bool IsLocked() const { return (m_locked
> 0); }
102 friend class wxCondition
;
104 // no assignment operator nor copy ctor
105 wxMutex(const wxMutex
&);
106 wxMutex
& operator=(const wxMutex
&);
109 wxMutexInternal
*p_internal
;
112 // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
113 // this ensures that mutex is always unlocked, even if the function returns or
114 // throws an exception before it reaches the end
115 class WXDLLEXPORT wxMutexLocker
118 // lock the mutex in the ctor
119 wxMutexLocker(wxMutex
& mutex
) : m_mutex(mutex
)
120 { m_isOk
= m_mutex
.Lock() == wxMUTEX_NO_ERROR
; }
122 // returns TRUE if mutex was successfully locked in ctor
126 // unlock the mutex in dtor
128 { if ( IsOk() ) m_mutex
.Unlock(); }
131 // no assignment operator nor copy ctor
132 wxMutexLocker(const wxMutexLocker
&);
133 wxMutexLocker
& operator=(const wxMutexLocker
&);
139 // ----------------------------------------------------------------------------
140 // Critical section: this is the same as mutex but is only visible to the
141 // threads of the same process. For the platforms which don't have native
142 // support for critical sections, they're implemented entirely in terms of
145 // NB: wxCriticalSection object does not allocate any memory in its ctor
146 // which makes it possible to have static globals of this class
147 // ----------------------------------------------------------------------------
149 class WXDLLEXPORT wxCriticalSectionInternal
;
151 // in order to avoid any overhead under platforms where critical sections are
152 // just mutexes make all wxCriticalSection class functions inline
153 #if !defined(__WXMSW__) && !defined(__WXPM__) && !defined(__WXMAC__)
154 #define WXCRITICAL_INLINE inline
156 #define wxCRITSECT_IS_MUTEX 1
157 #else // MSW || Mac || OS2
158 #define WXCRITICAL_INLINE
160 #define wxCRITSECT_IS_MUTEX 0
163 // you should consider wxCriticalSectionLocker whenever possible instead of
164 // directly working with wxCriticalSection class - it is safer
165 class WXDLLEXPORT wxCriticalSection
169 WXCRITICAL_INLINE
wxCriticalSection();
170 WXCRITICAL_INLINE
~wxCriticalSection();
172 // enter the section (the same as locking a mutex)
173 WXCRITICAL_INLINE
void Enter();
174 // leave the critical section (same as unlocking a mutex)
175 WXCRITICAL_INLINE
void Leave();
178 // no assignment operator nor copy ctor
179 wxCriticalSection(const wxCriticalSection
&);
180 wxCriticalSection
& operator=(const wxCriticalSection
&);
182 #if wxCRITSECT_IS_MUTEX
184 #elif defined(__WXMSW__)
185 // we can't allocate any memory in the ctor, so use placement new -
186 // unfortunately, we have to hardcode the sizeof() here because we can't
187 // include windows.h from this public header
189 #elif !defined(__WXPM__)
190 wxCriticalSectionInternal
*m_critsect
;
196 // keep your preprocessor name space clean
197 #undef WXCRITICAL_INLINE
199 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
201 class WXDLLEXPORT wxCriticalSectionLocker
204 inline wxCriticalSectionLocker(wxCriticalSection
& critsect
);
205 inline ~wxCriticalSectionLocker();
208 // no assignment operator nor copy ctor
209 wxCriticalSectionLocker(const wxCriticalSectionLocker
&);
210 wxCriticalSectionLocker
& operator=(const wxCriticalSectionLocker
&);
212 wxCriticalSection
& m_critsect
;
215 // ----------------------------------------------------------------------------
216 // Condition handler.
217 // ----------------------------------------------------------------------------
219 class wxConditionInternal
;
220 class WXDLLEXPORT wxCondition
223 // constructor & destructor
227 // Waits indefinitely.
228 void Wait(wxMutex
& mutex
);
229 // Waits until a signal is raised or the timeout is elapsed.
230 bool Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
);
231 // Raises a signal: only one "Waiter" is released.
233 // Broadcasts to all "Waiters".
237 wxConditionInternal
*p_internal
;
240 // ----------------------------------------------------------------------------
242 // ----------------------------------------------------------------------------
244 // there are two different kinds of threads: joinable and detached (default)
245 // ones. Only joinable threads can return a return code and only detached
246 // threads auto-delete themselves - the user should delete the joinable
249 // NB: in the function descriptions the words "this thread" mean the thread
250 // created by the wxThread object while "main thread" is the thread created
251 // during the process initialization (a.k.a. the GUI thread)
253 class wxThreadInternal
;
254 class WXDLLEXPORT wxThread
257 // the return type for the thread function
258 typedef void *ExitCode
;
261 // Returns the wxThread object for the calling thread. NULL is returned
262 // if the caller is the main thread (but it's recommended to use
263 // IsMain() and only call This() for threads other than the main one
264 // because NULL is also returned on error). If the thread wasn't
265 // created with wxThread class, the returned value is undefined.
266 static wxThread
*This();
268 // Returns true if current thread is the main thread.
269 static bool IsMain();
271 // Release the rest of our time slice leting the other threads run
274 // Sleep during the specified period of time in milliseconds
276 // NB: at least under MSW worker threads can not call ::wxSleep()!
277 static void Sleep(unsigned long milliseconds
);
279 // constructor only creates the C++ thread object and doesn't create (or
280 // start) the real thread
281 wxThread(wxThreadKind kind
= wxTHREAD_DETACHED
);
283 // functions that change the thread state: all these can only be called
284 // from _another_ thread (typically the thread that created this one, e.g.
285 // the main thread), not from the thread itself
287 // create a new thread - call Run() to start it
288 wxThreadError
Create();
290 // starts execution of the thread - from the moment Run() is called
291 // the execution of wxThread::Entry() may start at any moment, caller
292 // shouldn't suppose that it starts after (or before) Run() returns.
295 // stops the thread if it's running and deletes the wxThread object if
296 // this is a detached thread freeing its memory - otherwise (for
297 // joinable threads) you still need to delete wxThread object
300 // this function only works if the thread calls TestDestroy()
301 // periodically - the thread will only be deleted the next time it
304 // will fill the rc pointer with the thread exit code if it's !NULL
305 wxThreadError
Delete(ExitCode
*rc
= (ExitCode
*)NULL
);
307 // waits for a joinable thread to finish and returns its exit code
309 // Returns (ExitCode)-1 on error (for example, if the thread is not
313 // kills the thread without giving it any chance to clean up - should
314 // not be used in normal circumstances, use Delete() instead. It is a
315 // dangerous function that should only be used in the most extreme
318 // The wxThread object is deleted by Kill() if the thread is
319 // detachable, but you still have to delete it manually for joinable
321 wxThreadError
Kill();
323 // pause a running thread: as Delete(), this only works if the thread
324 // calls TestDestroy() regularly
325 wxThreadError
Pause();
327 // resume a paused thread
328 wxThreadError
Resume();
331 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
333 // NB: the priority can only be set before the thread is created
334 void SetPriority(unsigned int prio
);
336 // Get the current priority.
337 unsigned int GetPriority() const;
339 // thread status inquiries
340 // Returns true if the thread is alive: i.e. running or suspended
341 bool IsAlive() const;
342 // Returns true if the thread is running (not paused, not killed).
343 bool IsRunning() const;
344 // Returns true if the thread is suspended
345 bool IsPaused() const;
347 // is the thread of detached kind?
348 bool IsDetached() const { return m_isDetached
; }
350 // Get the thread ID - a platform dependent number which uniquely
351 // identifies a thread inside a process
352 unsigned long GetId() const;
354 // called when the thread exits - in the context of this thread
356 // NB: this function will not be called if the thread is Kill()ed
357 virtual void OnExit() { }
359 // dtor is public, but the detached threads should never be deleted - use
360 // Delete() instead (or leave the thread terminate by itself)
364 // Returns TRUE if the thread was asked to terminate: this function should
365 // be called by the thread from time to time, otherwise the main thread
366 // will be left forever in Delete()!
369 // exits from the current thread - can be called only from this thread
370 void Exit(ExitCode exitcode
= 0);
372 // entry point for the thread - called by Run() and executes in the context
374 virtual void *Entry() = 0;
377 // no copy ctor/assignment operator
378 wxThread(const wxThread
&);
379 wxThread
& operator=(const wxThread
&);
381 friend class wxThreadInternal
;
383 // the (platform-dependent) thread class implementation
384 wxThreadInternal
*p_internal
;
386 // protects access to any methods of wxThreadInternal object
387 wxCriticalSection m_critsect
;
389 // true if the thread is detached, false if it is joinable
393 // ----------------------------------------------------------------------------
394 // Automatic initialization
395 // ----------------------------------------------------------------------------
397 // GUI mutex handling.
398 void WXDLLEXPORT
wxMutexGuiEnter();
399 void WXDLLEXPORT
wxMutexGuiLeave();
401 // macros for entering/leaving critical sections which may be used without
402 // having to take them inside "#if wxUSE_THREADS"
403 #define wxENTER_CRIT_SECT(cs) (cs).Enter()
404 #define wxLEAVE_CRIT_SECT(cs) (cs).Leave()
405 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(cs)
407 #else // !wxUSE_THREADS
409 #include "wx/defs.h" // for WXDLLEXPORT
412 inline void WXDLLEXPORT
wxMutexGuiEnter() { }
413 inline void WXDLLEXPORT
wxMutexGuiLeave() { }
415 // macros for entering/leaving critical sections which may be used without
416 // having to take them inside "#if wxUSE_THREADS"
417 #define wxENTER_CRIT_SECT(cs)
418 #define wxLEAVE_CRIT_SECT(cs)
419 #define wxCRIT_SECT_LOCKER(name, cs)
421 #endif // wxUSE_THREADS
423 // automatically unlock GUI mutex in dtor
424 class WXDLLEXPORT wxMutexGuiLocker
427 wxMutexGuiLocker() { wxMutexGuiEnter(); }
428 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
431 // -----------------------------------------------------------------------------
432 // implementation only until the end of file
433 // -----------------------------------------------------------------------------
437 #if defined(__WXMSW__)
438 // unlock GUI if there are threads waiting for and lock it back when
439 // there are no more of them - should be called periodically by the main
441 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
443 // returns TRUE if the main thread has GUI lock
444 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
446 // wakes up the main thread if it's sleeping inside ::GetMessage()
447 extern void WXDLLEXPORT
wxWakeUpMainThread();
449 // return TRUE if the main thread is waiting for some other to terminate:
450 // wxApp then should block all "dangerous" messages
451 extern bool WXDLLEXPORT
wxIsWaitingForThread();
452 #elif defined(__WXMAC__)
453 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
455 // returns TRUE if the main thread has GUI lock
456 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
458 // wakes up the main thread if it's sleeping inside ::GetMessage()
459 extern void WXDLLEXPORT
wxWakeUpMainThread();
461 // return TRUE if the main thread is waiting for some other to terminate:
462 // wxApp then should block all "dangerous" messages
463 extern bool WXDLLEXPORT
wxIsWaitingForThread();
464 #elif defined(__WXPM__)
465 // unlock GUI if there are threads waiting for and lock it back when
466 // there are no more of them - should be called periodically by the main
468 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
470 // returns TRUE if the main thread has GUI lock
471 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
473 // return TRUE if the main thread is waiting for some other to terminate:
474 // wxApp then should block all "dangerous" messages
475 extern bool WXDLLEXPORT
wxIsWaitingForThread();
478 // implement wxCriticalSection using mutexes
479 inline wxCriticalSection::wxCriticalSection() { }
480 inline wxCriticalSection::~wxCriticalSection() { }
482 inline void wxCriticalSection::Enter() { (void)m_mutex
.Lock(); }
483 inline void wxCriticalSection::Leave() { (void)m_mutex
.Unlock(); }
486 // we can define these inline functions now (they should be defined after
487 // wxCriticalSection::Enter/Leave)
489 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection
& cs
)
490 : m_critsect(cs
) { m_critsect
.Enter(); }
492 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect
.Leave(); }
493 #endif // wxUSE_THREADS
495 #endif // __THREADH__