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
24 /* otherwise we get undefined references for non-thread case (KB)*/
26 #pragma interface "thread.h"
29 // Windows headers define it
34 #include "wx/module.h"
36 // ----------------------------------------------------------------------------
38 // ----------------------------------------------------------------------------
43 wxMUTEX_DEAD_LOCK
, // Mutex has been already locked by THE CALLING thread
44 wxMUTEX_BUSY
, // Mutex has been already locked by ONE thread
51 wxTHREAD_NO_ERROR
= 0, // No error
52 wxTHREAD_NO_RESOURCE
, // No resource left to create a new thread
53 wxTHREAD_RUNNING
, // The thread is already running
54 wxTHREAD_NOT_RUNNING
, // The thread isn't running
55 wxTHREAD_MISC_ERROR
// Some other error
58 // defines the interval of priority
59 #define WXTHREAD_MIN_PRIORITY 0u
60 #define WXTHREAD_DEFAULT_PRIORITY 50u
61 #define WXTHREAD_MAX_PRIORITY 100u
63 // ----------------------------------------------------------------------------
64 // A mutex object is a synchronization object whose state is set to signaled
65 // when it is not owned by any thread, and nonsignaled when it is owned. Its
66 // name comes from its usefulness in coordinating mutually-exclusive access to
67 // a shared resource. Only one thread at a time can own a mutex object.
68 // ----------------------------------------------------------------------------
70 // you should consider wxMutexLocker whenever possible instead of directly
71 // working with wxMutex class - it is safer
72 class WXDLLEXPORT wxMutexInternal
;
73 class WXDLLEXPORT wxMutex
76 // constructor & destructor
82 // Try to lock the mutex: if it can't, returns immediately with an error.
83 wxMutexError
TryLock();
85 wxMutexError
Unlock();
87 // Returns true if the mutex is locked.
88 bool IsLocked() const { return (m_locked
> 0); }
91 friend class wxCondition
;
93 // no assignment operator nor copy ctor
94 wxMutex(const wxMutex
&);
95 wxMutex
& operator=(const wxMutex
&);
98 wxMutexInternal
*p_internal
;
101 // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
102 // this ensures that mutex is always unlocked, even if the function returns or
103 // throws an exception before it reaches the end
104 class WXDLLEXPORT wxMutexLocker
107 // lock the mutex in the ctor
108 wxMutexLocker(wxMutex
& mutex
) : m_mutex(mutex
)
109 { m_isOk
= m_mutex
.Lock() == wxMUTEX_NO_ERROR
; }
111 // returns TRUE if mutex was successfully locked in ctor
115 // unlock the mutex in dtor
117 { if ( IsOk() ) m_mutex
.Unlock(); }
120 // no assignment operator nor copy ctor
121 wxMutexLocker(const wxMutexLocker
&);
122 wxMutexLocker
& operator=(const wxMutexLocker
&);
128 // ----------------------------------------------------------------------------
129 // Critical section: this is the same as mutex but is only visible to the
130 // threads of the same process. For the platforms which don't have native
131 // support for critical sections, they're implemented entirely in terms of
133 // ----------------------------------------------------------------------------
135 // in order to avoid any overhead under !MSW make all wxCriticalSection class
136 // functions inline - but this can't be done under MSW
137 #if defined(__WXMSW__) || defined(__WXPM__)
138 class WXDLLEXPORT wxCriticalSectionInternal
;
139 #define WXCRITICAL_INLINE
140 #elif defined(__WXMAC__)
141 class WXDLLEXPORT wxCriticalSectionInternal
;
142 #define WXCRITICAL_INLINE
144 #define WXCRITICAL_INLINE inline
147 // you should consider wxCriticalSectionLocker whenever possible instead of
148 // directly working with wxCriticalSection class - it is safer
149 class WXDLLEXPORT wxCriticalSection
153 WXCRITICAL_INLINE
wxCriticalSection();
154 WXCRITICAL_INLINE
~wxCriticalSection();
156 // enter the section (the same as locking a mutex)
157 WXCRITICAL_INLINE
void Enter();
158 // leave the critical section (same as unlocking a mutex)
159 WXCRITICAL_INLINE
void Leave();
162 // no assignment operator nor copy ctor
163 wxCriticalSection(const wxCriticalSection
&);
164 wxCriticalSection
& operator=(const wxCriticalSection
&);
166 #if defined(__WXMSW__) || defined(__WXPM__) || defined(__WXMAC__)
167 wxCriticalSectionInternal
*m_critsect
;
173 // keep your preprocessor name space clean
174 #undef WXCRITICAL_INLINE
176 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
178 class WXDLLEXPORT wxCriticalSectionLocker
181 inline wxCriticalSectionLocker(wxCriticalSection
& critsect
);
182 inline ~wxCriticalSectionLocker();
185 // no assignment operator nor copy ctor
186 wxCriticalSectionLocker(const wxCriticalSectionLocker
&);
187 wxCriticalSectionLocker
& operator=(const wxCriticalSectionLocker
&);
189 wxCriticalSection
& m_critsect
;
192 // ----------------------------------------------------------------------------
193 // Condition handler.
194 // ----------------------------------------------------------------------------
196 class wxConditionInternal
;
197 class WXDLLEXPORT wxCondition
200 // constructor & destructor
204 // Waits indefinitely.
205 void Wait(wxMutex
& mutex
);
206 // Waits until a signal is raised or the timeout is elapsed.
207 bool Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
);
208 // Raises a signal: only one "Waiter" is released.
210 // Broadcasts to all "Waiters".
214 wxConditionInternal
*p_internal
;
217 // ----------------------------------------------------------------------------
218 // Thread management class
219 // ----------------------------------------------------------------------------
221 // FIXME Thread termination model is still unclear. Delete() should probably
222 // have a timeout after which the thread must be Kill()ed.
224 // NB: in the function descriptions the words "this thread" mean the thread
225 // created by the wxThread object while "main thread" is the thread created
226 // during the process initialization (a.k.a. the GUI thread)
227 class wxThreadInternal
;
228 class WXDLLEXPORT wxThread
231 // the return type for the thread function
232 typedef void *ExitCode
;
235 // Returns the wxThread object for the calling thread. NULL is returned
236 // if the caller is the main thread (but it's recommended to use
237 // IsMain() and only call This() for threads other than the main one
238 // because NULL is also returned on error). If the thread wasn't
239 // created with wxThread class, the returned value is undefined.
240 static wxThread
*This();
242 // Returns true if current thread is the main thread.
243 static bool IsMain();
245 // Release the rest of our time slice leting the other threads run
248 // Sleep during the specified period of time in milliseconds
250 // NB: at least under MSW worker threads can not call ::wxSleep()!
251 static void Sleep(unsigned long milliseconds
);
253 // default constructor
256 // function that change the thread state
257 // create a new thread - call Run() to start it
258 wxThreadError
Create();
260 // starts execution of the thread - from the moment Run() is called the
261 // execution of wxThread::Entry() may start at any moment, caller
262 // shouldn't suppose that it starts after (or before) Run() returns.
265 // stops the thread if it's running and deletes the wxThread object
266 // freeing its memory. This function should also be called if the
267 // Create() or Run() fails to free memory (otherwise it will be done by
268 // the thread itself when it terminates). The return value is the
269 // thread exit code if the thread was gracefully terminated, 0 if it
270 // wasn't running and -1 if an error occured.
273 // kills the thread without giving it any chance to clean up - should
274 // not be used in normal circumstances, use Delete() instead. It is a
275 // dangerous function that should only be used in the most extreme
276 // cases! The wxThread object is deleted by Kill() if thread was
277 // killed (i.e. no errors occured).
278 wxThreadError
Kill();
280 // pause a running thread
281 wxThreadError
Pause();
283 // resume a paused thread
284 wxThreadError
Resume();
287 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
289 // NB: the priority can only be set before the thread is created
290 void SetPriority(unsigned int prio
);
292 // Get the current priority.
293 unsigned int GetPriority() const;
295 // Get the thread ID - a platform dependent number which uniquely
296 // identifies a thread inside a process
297 unsigned long GetID() const;
299 // thread status inquiries
300 // Returns true if the thread is alive: i.e. running or suspended
301 bool IsAlive() const;
302 // Returns true if the thread is running (not paused, not killed).
303 bool IsRunning() const;
304 // Returns true if the thread is suspended
305 bool IsPaused() const;
307 // called when the thread exits - in the context of this thread
309 // NB: this function will not be called if the thread is Kill()ed
310 virtual void OnExit() { }
313 // Returns TRUE if the thread was asked to terminate: this function should
314 // be called by the thread from time to time, otherwise the main thread
315 // will be left forever in Delete()!
318 // exits from the current thread - can be called only from this thread
319 void Exit(void *exitcode
= 0);
321 // destructor is private - user code can't delete thread objects, they will
322 // auto-delete themselves (and thus must be always allocated on the heap).
323 // Use Delete() or Kill() instead.
325 // NB: derived classes dtors shouldn't be public neither!
328 // entry point for the thread - called by Run() and executes in the context
330 virtual void *Entry() = 0;
333 // no copy ctor/assignment operator
334 wxThread(const wxThread
&);
335 wxThread
& operator=(const wxThread
&);
337 friend class wxThreadInternal
;
339 // the (platform-dependent) thread class implementation
340 wxThreadInternal
*p_internal
;
342 // protects access to any methods of wxThreadInternal object
343 wxCriticalSection m_critsect
;
346 // ----------------------------------------------------------------------------
347 // Automatic initialization
348 // ----------------------------------------------------------------------------
350 // GUI mutex handling.
351 void WXDLLEXPORT
wxMutexGuiEnter();
352 void WXDLLEXPORT
wxMutexGuiLeave();
354 // macros for entering/leaving critical sections which may be used without
355 // having to take them inside "#if wxUSE_THREADS"
356 #define wxENTER_CRIT_SECT(cs) (cs)->Enter()
357 #define wxLEAVE_CRIT_SECT(cs) (cs)->Leave()
358 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(*cs)
360 #else // !wxUSE_THREADS
362 #include "wx/defs.h" // for WXDLLEXPORT
365 inline void WXDLLEXPORT
wxMutexGuiEnter() { }
366 inline void WXDLLEXPORT
wxMutexGuiLeave() { }
368 // macros for entering/leaving critical sections which may be used without
369 // having to take them inside "#if wxUSE_THREADS"
370 #define wxENTER_CRIT_SECT(cs)
371 #define wxLEAVE_CRIT_SECT(cs)
372 #define wxCRIT_SECT_LOCKER(name, cs)
374 #endif // wxUSE_THREADS
376 // automatically unlock GUI mutex in dtor
377 class WXDLLEXPORT wxMutexGuiLocker
380 wxMutexGuiLocker() { wxMutexGuiEnter(); }
381 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
384 // -----------------------------------------------------------------------------
385 // implementation only until the end of file
386 // -----------------------------------------------------------------------------
390 #if defined(__WXMSW__)
391 // unlock GUI if there are threads waiting for and lock it back when
392 // there are no more of them - should be called periodically by the main
394 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
396 // returns TRUE if the main thread has GUI lock
397 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
399 // wakes up the main thread if it's sleeping inside ::GetMessage()
400 extern void WXDLLEXPORT
wxWakeUpMainThread();
402 // return TRUE if the main thread is waiting for some other to terminate:
403 // wxApp then should block all "dangerous" messages
404 extern bool WXDLLEXPORT
wxIsWaitingForThread();
405 #elif defined(__WXMAC__)
406 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
408 // returns TRUE if the main thread has GUI lock
409 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
411 // wakes up the main thread if it's sleeping inside ::GetMessage()
412 extern void WXDLLEXPORT
wxWakeUpMainThread();
414 // return TRUE if the main thread is waiting for some other to terminate:
415 // wxApp then should block all "dangerous" messages
416 extern bool WXDLLEXPORT
wxIsWaitingForThread();
417 #elif defined(__WXPM__)
418 // unlock GUI if there are threads waiting for and lock it back when
419 // there are no more of them - should be called periodically by the main
421 extern void WXDLLEXPORT
wxMutexGuiLeaveOrEnter();
423 // returns TRUE if the main thread has GUI lock
424 extern bool WXDLLEXPORT
wxGuiOwnedByMainThread();
425 // return TRUE if the main thread is waiting for some other to terminate:
426 // wxApp then should block all "dangerous" messages
427 extern bool WXDLLEXPORT
wxIsWaitingForThread();
429 // implement wxCriticalSection using mutexes
430 inline wxCriticalSection::wxCriticalSection() { }
431 inline wxCriticalSection::~wxCriticalSection() { }
433 inline void wxCriticalSection::Enter() { (void)m_mutex
.Lock(); }
434 inline void wxCriticalSection::Leave() { (void)m_mutex
.Unlock(); }
437 // we can define these inline functions now (they should be defined after
438 // wxCriticalSection::Enter/Leave)
440 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection
& cs
)
441 : m_critsect(cs
) { m_critsect
.Enter(); }
443 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect
.Leave(); }
444 #endif // wxUSE_THREADS
446 #endif // __THREADH__