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_MISC_ERROR
// Some other error
59 // defines the interval of priority
62 WXTHREAD_MIN_PRIORITY
= 0u,
63 WXTHREAD_DEFAULT_PRIORITY
= 50u,
64 WXTHREAD_MAX_PRIORITY
= 100u
67 // ----------------------------------------------------------------------------
68 // A mutex object is a synchronization object whose state is set to signaled
69 // when it is not owned by any thread, and nonsignaled when it is owned. Its
70 // name comes from its usefulness in coordinating mutually-exclusive access to
71 // a shared resource. Only one thread at a time can own a mutex object.
72 // ----------------------------------------------------------------------------
74 // you should consider wxMutexLocker whenever possible instead of directly
75 // working with wxMutex class - it is safer
76 class WXDLLEXPORT wxMutexInternal
;
77 class WXDLLEXPORT wxMutex
80 // constructor & destructor
86 // Try to lock the mutex: if it can't, returns immediately with an error.
87 wxMutexError
TryLock();
89 wxMutexError
Unlock();
91 // Returns true if the mutex is locked.
92 bool IsLocked() const { return (m_locked
> 0); }
95 friend class wxCondition
;
97 // no assignment operator nor copy ctor
98 wxMutex(const wxMutex
&);
99 wxMutex
& operator=(const wxMutex
&);
102 wxMutexInternal
*p_internal
;
105 // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
106 // this ensures that mutex is always unlocked, even if the function returns or
107 // throws an exception before it reaches the end
108 class WXDLLEXPORT wxMutexLocker
111 // lock the mutex in the ctor
112 wxMutexLocker(wxMutex
& mutex
) : m_mutex(mutex
)
113 { m_isOk
= m_mutex
.Lock() == wxMUTEX_NO_ERROR
; }
115 // returns TRUE if mutex was successfully locked in ctor
119 // unlock the mutex in dtor
121 { if ( IsOk() ) m_mutex
.Unlock(); }
124 // no assignment operator nor copy ctor
125 wxMutexLocker(const wxMutexLocker
&);
126 wxMutexLocker
& operator=(const wxMutexLocker
&);
132 // ----------------------------------------------------------------------------
133 // Critical section: this is the same as mutex but is only visible to the
134 // threads of the same process. For the platforms which don't have native
135 // support for critical sections, they're implemented entirely in terms of
138 // NB: wxCriticalSection object does not allocate any memory in its ctor
139 // which makes it possible to have static globals of this class
140 // ----------------------------------------------------------------------------
142 class WXDLLEXPORT wxCriticalSectionInternal
;
144 // in order to avoid any overhead under platforms where critical sections are
145 // just mutexes make all wxCriticalSection class functions inline
146 #if !defined(__WXMSW__) && !defined(__WXPM__) && !defined(__WXMAC__)
147 #define WXCRITICAL_INLINE inline
149 #define wxCRITSECT_IS_MUTEX 1
150 #else // MSW || Mac || OS2
151 #define WXCRITICAL_INLINE
153 #define wxCRITSECT_IS_MUTEX 0
156 // you should consider wxCriticalSectionLocker whenever possible instead of
157 // directly working with wxCriticalSection class - it is safer
158 class WXDLLEXPORT wxCriticalSection
162 WXCRITICAL_INLINE
wxCriticalSection();
163 WXCRITICAL_INLINE
~wxCriticalSection();
165 // enter the section (the same as locking a mutex)
166 WXCRITICAL_INLINE
void Enter();
167 // leave the critical section (same as unlocking a mutex)
168 WXCRITICAL_INLINE
void Leave();
171 // no assignment operator nor copy ctor
172 wxCriticalSection(const wxCriticalSection
&);
173 wxCriticalSection
& operator=(const wxCriticalSection
&);
175 #if wxCRITSECT_IS_MUTEX
177 #elif defined(__WXMSW__)
178 // we can't allocate any memory in the ctor, so use placement new -
179 // unfortunately, we have to hardcode the sizeof() here because we can't
180 // include windows.h from this public header
182 #elif !defined(__WXPM__)
183 wxCriticalSectionInternal
*m_critsect
;
189 // keep your preprocessor name space clean
190 #undef WXCRITICAL_INLINE
192 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
194 class WXDLLEXPORT wxCriticalSectionLocker
197 inline wxCriticalSectionLocker(wxCriticalSection
& critsect
);
198 inline ~wxCriticalSectionLocker();
201 // no assignment operator nor copy ctor
202 wxCriticalSectionLocker(const wxCriticalSectionLocker
&);
203 wxCriticalSectionLocker
& operator=(const wxCriticalSectionLocker
&);
205 wxCriticalSection
& m_critsect
;
208 // ----------------------------------------------------------------------------
209 // Condition handler.
210 // ----------------------------------------------------------------------------
212 class wxConditionInternal
;
213 class WXDLLEXPORT wxCondition
216 // constructor & destructor
220 // Waits indefinitely.
221 void Wait(wxMutex
& mutex
);
222 // Waits until a signal is raised or the timeout is elapsed.
223 bool Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
);
224 // Raises a signal: only one "Waiter" is released.
226 // Broadcasts to all "Waiters".
230 wxConditionInternal
*p_internal
;
233 // ----------------------------------------------------------------------------
234 // Thread management class
235 // ----------------------------------------------------------------------------
237 // FIXME Thread termination model is still unclear. Delete() should probably
238 // have a timeout after which the thread must be Kill()ed.
240 // NB: in the function descriptions the words "this thread" mean the thread
241 // created by the wxThread object while "main thread" is the thread created
242 // during the process initialization (a.k.a. the GUI thread)
243 class wxThreadInternal
;
244 class WXDLLEXPORT wxThread
247 // the return type for the thread function
248 typedef void *ExitCode
;
251 // Returns the wxThread object for the calling thread. NULL is returned
252 // if the caller is the main thread (but it's recommended to use
253 // IsMain() and only call This() for threads other than the main one
254 // because NULL is also returned on error). If the thread wasn't
255 // created with wxThread class, the returned value is undefined.
256 static wxThread
*This();
258 // Returns true if current thread is the main thread.
259 static bool IsMain();
261 // Release the rest of our time slice leting the other threads run
264 // Sleep during the specified period of time in milliseconds
266 // NB: at least under MSW worker threads can not call ::wxSleep()!
267 static void Sleep(unsigned long milliseconds
);
269 // default constructor
272 // function that change the thread state
273 // create a new thread - call Run() to start it
274 wxThreadError
Create();
276 // starts execution of the thread - from the moment Run() is called the
277 // execution of wxThread::Entry() may start at any moment, caller
278 // shouldn't suppose that it starts after (or before) Run() returns.
281 // stops the thread if it's running and deletes the wxThread object
282 // freeing its memory. This function should also be called if the
283 // Create() or Run() fails to free memory (otherwise it will be done by
284 // the thread itself when it terminates). The return value is the
285 // thread exit code if the thread was gracefully terminated, 0 if it
286 // wasn't running and -1 if an error occured.
289 // kills the thread without giving it any chance to clean up - should
290 // not be used in normal circumstances, use Delete() instead. It is a
291 // dangerous function that should only be used in the most extreme
292 // cases! The wxThread object is deleted by Kill() if thread was
293 // killed (i.e. no errors occured).
294 wxThreadError
Kill();
296 // pause a running thread
297 wxThreadError
Pause();
299 // resume a paused thread
300 wxThreadError
Resume();
303 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
305 // NB: the priority can only be set before the thread is created
306 void SetPriority(unsigned int prio
);
308 // Get the current priority.
309 unsigned int GetPriority() const;
311 // Get the thread ID - a platform dependent number which uniquely
312 // identifies a thread inside a process
313 unsigned long GetID() const;
315 // thread status inquiries
316 // Returns true if the thread is alive: i.e. running or suspended
317 bool IsAlive() const;
318 // Returns true if the thread is running (not paused, not killed).
319 bool IsRunning() const;
320 // Returns true if the thread is suspended
321 bool IsPaused() const;
323 // called when the thread exits - in the context of this thread
325 // NB: this function will not be called if the thread is Kill()ed
326 virtual void OnExit() { }
329 // Returns TRUE if the thread was asked to terminate: this function should
330 // be called by the thread from time to time, otherwise the main thread
331 // will be left forever in Delete()!
334 // exits from the current thread - can be called only from this thread
335 void Exit(void *exitcode
= 0);
337 // destructor is private - user code can't delete thread objects, they will
338 // auto-delete themselves (and thus must be always allocated on the heap).
339 // Use Delete() or Kill() instead.
341 // NB: derived classes dtors shouldn't be public neither!
344 // entry point for the thread - called by Run() and executes in the context
346 virtual void *Entry() = 0;
349 // no copy ctor/assignment operator
350 wxThread(const wxThread
&);
351 wxThread
& operator=(const wxThread
&);
353 friend class wxThreadInternal
;
355 // the (platform-dependent) thread class implementation
356 wxThreadInternal
*p_internal
;
358 // protects access to any methods of wxThreadInternal object
359 wxCriticalSection m_critsect
;
362 // ----------------------------------------------------------------------------
363 // Automatic initialization
364 // ----------------------------------------------------------------------------
366 // GUI mutex handling.
367 void WXDLLEXPORT
wxMutexGuiEnter();
368 void WXDLLEXPORT
wxMutexGuiLeave();
370 // macros for entering/leaving critical sections which may be used without
371 // having to take them inside "#if wxUSE_THREADS"
372 #define wxENTER_CRIT_SECT(cs) (cs)->Enter()
373 #define wxLEAVE_CRIT_SECT(cs) (cs)->Leave()
374 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(*cs)
376 #else // !wxUSE_THREADS
378 #include "wx/defs.h" // for WXDLLEXPORT
381 inline void WXDLLEXPORT
wxMutexGuiEnter() { }
382 inline void WXDLLEXPORT
wxMutexGuiLeave() { }
384 // macros for entering/leaving critical sections which may be used without
385 // having to take them inside "#if wxUSE_THREADS"
386 #define wxENTER_CRIT_SECT(cs)
387 #define wxLEAVE_CRIT_SECT(cs)
388 #define wxCRIT_SECT_LOCKER(name, cs)
390 #endif // wxUSE_THREADS
392 // automatically unlock GUI mutex in dtor
393 class WXDLLEXPORT wxMutexGuiLocker
396 wxMutexGuiLocker() { wxMutexGuiEnter(); }
397 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
400 // -----------------------------------------------------------------------------
401 // implementation only until the end of file
402 // -----------------------------------------------------------------------------
406 #if defined(__WXMSW__)
407 // unlock GUI if there are threads waiting for and lock it back when
408 // there are no more of them - should be called periodically by the main
410 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
412 // returns TRUE if the main thread has GUI lock
413 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
415 // wakes up the main thread if it's sleeping inside ::GetMessage()
416 extern void WXDLLEXPORT
wxWakeUpMainThread();
418 // return TRUE if the main thread is waiting for some other to terminate:
419 // wxApp then should block all "dangerous" messages
420 extern bool WXDLLEXPORT
wxIsWaitingForThread();
421 #elif defined(__WXMAC__)
422 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
424 // returns TRUE if the main thread has GUI lock
425 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
427 // wakes up the main thread if it's sleeping inside ::GetMessage()
428 extern void WXDLLEXPORT
wxWakeUpMainThread();
430 // return TRUE if the main thread is waiting for some other to terminate:
431 // wxApp then should block all "dangerous" messages
432 extern bool WXDLLEXPORT
wxIsWaitingForThread();
433 #elif defined(__WXPM__)
434 // unlock GUI if there are threads waiting for and lock it back when
435 // there are no more of them - should be called periodically by the main
437 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
439 // returns TRUE if the main thread has GUI lock
440 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
442 // return TRUE if the main thread is waiting for some other to terminate:
443 // wxApp then should block all "dangerous" messages
444 extern bool WXDLLEXPORT
wxIsWaitingForThread();
447 // implement wxCriticalSection using mutexes
448 inline wxCriticalSection::wxCriticalSection() { }
449 inline wxCriticalSection::~wxCriticalSection() { }
451 inline void wxCriticalSection::Enter() { (void)m_mutex
.Lock(); }
452 inline void wxCriticalSection::Leave() { (void)m_mutex
.Unlock(); }
455 // we can define these inline functions now (they should be defined after
456 // wxCriticalSection::Enter/Leave)
458 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection
& cs
)
459 : m_critsect(cs
) { m_critsect
.Enter(); }
461 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect
.Leave(); }
462 #endif // wxUSE_THREADS
464 #endif // __THREADH__