attempts to make wxCondition::Broadcast() and Signal() work simultaneously - currentl...
[wxWidgets.git] / include / wx / thread.h
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: thread.h
3 // Purpose: Thread API
4 // Author: Guilhem Lavaux
5 // Modified by: Vadim Zeitlin (modifications partly inspired by omnithreads
6 // package from Olivetti & Oracle Research Laboratory)
7 // Created: 04/13/98
8 // RCS-ID: $Id$
9 // Copyright: (c) Guilhem Lavaux
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
12
13 #ifndef __THREADH__
14 #define __THREADH__
15
16 // ----------------------------------------------------------------------------
17 // headers
18 // ----------------------------------------------------------------------------
19
20 // get the value of wxUSE_THREADS configuration flag
21 #include "wx/setup.h"
22
23 #if wxUSE_THREADS
24
25 // only for wxUSE_THREADS - otherwise we'd get undefined symbols
26 #ifdef __GNUG__
27 #pragma interface "thread.h"
28 #endif
29
30 // Windows headers define it
31 #ifdef Yield
32 #undef Yield
33 #endif
34
35 #include "wx/module.h"
36
37 // ----------------------------------------------------------------------------
38 // constants
39 // ----------------------------------------------------------------------------
40
41 enum wxMutexError
42 {
43 wxMUTEX_NO_ERROR = 0,
44 wxMUTEX_DEAD_LOCK, // Mutex has been already locked by THE CALLING thread
45 wxMUTEX_BUSY, // Mutex has been already locked by ONE thread
46 wxMUTEX_UNLOCKED,
47 wxMUTEX_MISC_ERROR
48 };
49
50 enum wxThreadError
51 {
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
58 };
59
60 enum wxThreadKind
61 {
62 wxTHREAD_DETACHED,
63 wxTHREAD_JOINABLE
64 };
65
66 // defines the interval of priority
67 enum
68 {
69 WXTHREAD_MIN_PRIORITY = 0u,
70 WXTHREAD_DEFAULT_PRIORITY = 50u,
71 WXTHREAD_MAX_PRIORITY = 100u
72 };
73
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 // ----------------------------------------------------------------------------
80
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
85 {
86 public:
87 // constructor & destructor
88 wxMutex();
89 ~wxMutex();
90
91 // Lock the mutex.
92 wxMutexError Lock();
93 // Try to lock the mutex: if it can't, returns immediately with an error.
94 wxMutexError TryLock();
95 // Unlock the mutex.
96 wxMutexError Unlock();
97
98 // Returns true if the mutex is locked.
99 bool IsLocked() const { return (m_locked > 0); }
100
101 protected:
102 // no assignment operator nor copy ctor
103 wxMutex(const wxMutex&);
104 wxMutex& operator=(const wxMutex&);
105
106 int m_locked;
107 wxMutexInternal *m_internal;
108 };
109
110 // a helper class which locks the mutex in the ctor and unlocks it in the dtor:
111 // this ensures that mutex is always unlocked, even if the function returns or
112 // throws an exception before it reaches the end
113 class WXDLLEXPORT wxMutexLocker
114 {
115 public:
116 // lock the mutex in the ctor
117 wxMutexLocker(wxMutex& mutex) : m_mutex(mutex)
118 { m_isOk = m_mutex.Lock() == wxMUTEX_NO_ERROR; }
119
120 // returns TRUE if mutex was successfully locked in ctor
121 bool IsOk() const
122 { return m_isOk; }
123
124 // unlock the mutex in dtor
125 ~wxMutexLocker()
126 { if ( IsOk() ) m_mutex.Unlock(); }
127
128 private:
129 // no assignment operator nor copy ctor
130 wxMutexLocker(const wxMutexLocker&);
131 wxMutexLocker& operator=(const wxMutexLocker&);
132
133 bool m_isOk;
134 wxMutex& m_mutex;
135 };
136
137 // ----------------------------------------------------------------------------
138 // Critical section: this is the same as mutex but is only visible to the
139 // threads of the same process. For the platforms which don't have native
140 // support for critical sections, they're implemented entirely in terms of
141 // mutexes.
142 //
143 // NB: wxCriticalSection object does not allocate any memory in its ctor
144 // which makes it possible to have static globals of this class
145 // ----------------------------------------------------------------------------
146
147 class WXDLLEXPORT wxCriticalSectionInternal;
148
149 // in order to avoid any overhead under platforms where critical sections are
150 // just mutexes make all wxCriticalSection class functions inline
151 #if !defined(__WXMSW__) && !defined(__WXPM__)
152 #define WXCRITICAL_INLINE inline
153
154 #define wxCRITSECT_IS_MUTEX 1
155 #else // MSW || OS2
156 #define WXCRITICAL_INLINE
157
158 #define wxCRITSECT_IS_MUTEX 0
159 #endif // MSW/!MSW
160
161 // you should consider wxCriticalSectionLocker whenever possible instead of
162 // directly working with wxCriticalSection class - it is safer
163 class WXDLLEXPORT wxCriticalSection
164 {
165 public:
166 // ctor & dtor
167 WXCRITICAL_INLINE wxCriticalSection();
168 WXCRITICAL_INLINE ~wxCriticalSection();
169
170 // enter the section (the same as locking a mutex)
171 WXCRITICAL_INLINE void Enter();
172 // leave the critical section (same as unlocking a mutex)
173 WXCRITICAL_INLINE void Leave();
174
175 private:
176 // no assignment operator nor copy ctor
177 wxCriticalSection(const wxCriticalSection&);
178 wxCriticalSection& operator=(const wxCriticalSection&);
179
180 #if wxCRITSECT_IS_MUTEX
181 wxMutex m_mutex;
182 #elif defined(__WXMSW__)
183 // we can't allocate any memory in the ctor, so use placement new -
184 // unfortunately, we have to hardcode the sizeof() here because we can't
185 // include windows.h from this public header
186 char m_buffer[24];
187 #elif !defined(__WXPM__)
188 wxCriticalSectionInternal *m_critsect;
189 #else
190 // nothing for OS/2
191 #endif // !Unix/Unix
192 };
193
194 // keep your preprocessor name space clean
195 #undef WXCRITICAL_INLINE
196
197 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
198 // to th mutexes
199 class WXDLLEXPORT wxCriticalSectionLocker
200 {
201 public:
202 inline wxCriticalSectionLocker(wxCriticalSection& critsect);
203 inline ~wxCriticalSectionLocker();
204
205 private:
206 // no assignment operator nor copy ctor
207 wxCriticalSectionLocker(const wxCriticalSectionLocker&);
208 wxCriticalSectionLocker& operator=(const wxCriticalSectionLocker&);
209
210 wxCriticalSection& m_critsect;
211 };
212
213 // ----------------------------------------------------------------------------
214 // Condition variable: allows to block the thread execution until something
215 // happens (== condition is signaled)
216 // ----------------------------------------------------------------------------
217
218 class wxConditionInternal;
219 class WXDLLEXPORT wxCondition
220 {
221 public:
222 // constructor & destructor
223 wxCondition();
224 ~wxCondition();
225
226 // wait until the condition is signaled
227 // waits indefinitely.
228 void Wait();
229 // waits until a signal is raised or the timeout elapses
230 bool Wait(unsigned long sec, unsigned long nsec);
231
232 // signal the condition
233 // wakes up one (and only one) of the waiting threads
234 void Signal();
235 // wakes up all threads waiting on this condition
236 void Broadcast();
237
238 #ifdef __WXDEBUG__
239 // for debugging purposes only
240 void *GetId() const { return m_internal; }
241 #endif // __WXDEBUG__
242
243 private:
244 wxConditionInternal *m_internal;
245 };
246
247 // ----------------------------------------------------------------------------
248 // Thread class
249 // ----------------------------------------------------------------------------
250
251 // there are two different kinds of threads: joinable and detached (default)
252 // ones. Only joinable threads can return a return code and only detached
253 // threads auto-delete themselves - the user should delete the joinable
254 // threads manually.
255
256 // NB: in the function descriptions the words "this thread" mean the thread
257 // created by the wxThread object while "main thread" is the thread created
258 // during the process initialization (a.k.a. the GUI thread)
259
260 // On VMS thread pointers are 64 bits (also needed for other systems???
261 #ifdef __VMS
262 typedef unsigned long long wxThreadIdType;
263 #else
264 typedef unsigned long wxThreadIdType;
265 #endif
266
267 class wxThreadInternal;
268 class WXDLLEXPORT wxThread
269 {
270 public:
271 // the return type for the thread function
272 typedef void *ExitCode;
273
274 // static functions
275 // Returns the wxThread object for the calling thread. NULL is returned
276 // if the caller is the main thread (but it's recommended to use
277 // IsMain() and only call This() for threads other than the main one
278 // because NULL is also returned on error). If the thread wasn't
279 // created with wxThread class, the returned value is undefined.
280 static wxThread *This();
281
282 // Returns true if current thread is the main thread.
283 static bool IsMain();
284
285 // Release the rest of our time slice leting the other threads run
286 static void Yield();
287
288 // Sleep during the specified period of time in milliseconds
289 //
290 // NB: at least under MSW worker threads can not call ::wxSleep()!
291 static void Sleep(unsigned long milliseconds);
292
293 // get the number of system CPUs - useful with SetConcurrency()
294 // (the "best" value for it is usually number of CPUs + 1)
295 //
296 // Returns -1 if unknown, number of CPUs otherwise
297 static int GetCPUCount();
298
299 // Get the platform specific thread ID and return as a long. This
300 // can be used to uniquely identify threads, even if they are not
301 // wxThreads. This is used by wxPython.
302 static wxThreadIdType GetCurrentId();
303
304 // sets the concurrency level: this is, roughly, the number of threads
305 // the system tries to schedule to run in parallel. 0 means the
306 // default value (usually acceptable, but may not yield the best
307 // performance for this process)
308 //
309 // Returns TRUE on success, FALSE otherwise (if not implemented, for
310 // example)
311 static bool SetConcurrency(size_t level);
312
313 // constructor only creates the C++ thread object and doesn't create (or
314 // start) the real thread
315 wxThread(wxThreadKind kind = wxTHREAD_DETACHED);
316
317 // functions that change the thread state: all these can only be called
318 // from _another_ thread (typically the thread that created this one, e.g.
319 // the main thread), not from the thread itself
320
321 // create a new thread and optionally set the stack size on
322 // platforms that support that - call Run() to start it
323 // (special cased for watcom which won't accept 0 default)
324
325 wxThreadError Create(unsigned int stackSize = 0);
326
327 // starts execution of the thread - from the moment Run() is called
328 // the execution of wxThread::Entry() may start at any moment, caller
329 // shouldn't suppose that it starts after (or before) Run() returns.
330 wxThreadError Run();
331
332 // stops the thread if it's running and deletes the wxThread object if
333 // this is a detached thread freeing its memory - otherwise (for
334 // joinable threads) you still need to delete wxThread object
335 // yourself.
336 //
337 // this function only works if the thread calls TestDestroy()
338 // periodically - the thread will only be deleted the next time it
339 // does it!
340 //
341 // will fill the rc pointer with the thread exit code if it's !NULL
342 wxThreadError Delete(ExitCode *rc = (ExitCode *)NULL);
343
344 // waits for a joinable thread to finish and returns its exit code
345 //
346 // Returns (ExitCode)-1 on error (for example, if the thread is not
347 // joinable)
348 ExitCode Wait();
349
350 // kills the thread without giving it any chance to clean up - should
351 // not be used in normal circumstances, use Delete() instead. It is a
352 // dangerous function that should only be used in the most extreme
353 // cases!
354 //
355 // The wxThread object is deleted by Kill() if the thread is
356 // detachable, but you still have to delete it manually for joinable
357 // threads.
358 wxThreadError Kill();
359
360 // pause a running thread: as Delete(), this only works if the thread
361 // calls TestDestroy() regularly
362 wxThreadError Pause();
363
364 // resume a paused thread
365 wxThreadError Resume();
366
367 // priority
368 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
369 //
370 // NB: the priority can only be set before the thread is created
371 void SetPriority(unsigned int prio);
372
373 // Get the current priority.
374 unsigned int GetPriority() const;
375
376 // thread status inquiries
377 // Returns true if the thread is alive: i.e. running or suspended
378 bool IsAlive() const;
379 // Returns true if the thread is running (not paused, not killed).
380 bool IsRunning() const;
381 // Returns true if the thread is suspended
382 bool IsPaused() const;
383
384 // is the thread of detached kind?
385 bool IsDetached() const { return m_isDetached; }
386
387 // Get the thread ID - a platform dependent number which uniquely
388 // identifies a thread inside a process
389 wxThreadIdType GetId() const;
390
391 // called when the thread exits - in the context of this thread
392 //
393 // NB: this function will not be called if the thread is Kill()ed
394 virtual void OnExit() { }
395
396 // dtor is public, but the detached threads should never be deleted - use
397 // Delete() instead (or leave the thread terminate by itself)
398 virtual ~wxThread();
399
400 protected:
401 // Returns TRUE if the thread was asked to terminate: this function should
402 // be called by the thread from time to time, otherwise the main thread
403 // will be left forever in Delete()!
404 bool TestDestroy();
405
406 // exits from the current thread - can be called only from this thread
407 void Exit(ExitCode exitcode = 0);
408
409 // entry point for the thread - called by Run() and executes in the context
410 // of this thread.
411 virtual void *Entry() = 0;
412
413 private:
414 // no copy ctor/assignment operator
415 wxThread(const wxThread&);
416 wxThread& operator=(const wxThread&);
417
418 friend class wxThreadInternal;
419
420 // the (platform-dependent) thread class implementation
421 wxThreadInternal *m_internal;
422
423 // protects access to any methods of wxThreadInternal object
424 wxCriticalSection m_critsect;
425
426 // true if the thread is detached, false if it is joinable
427 bool m_isDetached;
428 };
429
430 // ----------------------------------------------------------------------------
431 // Automatic initialization
432 // ----------------------------------------------------------------------------
433
434 // GUI mutex handling.
435 void WXDLLEXPORT wxMutexGuiEnter();
436 void WXDLLEXPORT wxMutexGuiLeave();
437
438 // macros for entering/leaving critical sections which may be used without
439 // having to take them inside "#if wxUSE_THREADS"
440 #define wxENTER_CRIT_SECT(cs) (cs).Enter()
441 #define wxLEAVE_CRIT_SECT(cs) (cs).Leave()
442 #define wxCRIT_SECT_DECLARE(cs) static wxCriticalSection cs
443 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(cs)
444
445 #else // !wxUSE_THREADS
446
447 #include "wx/defs.h" // for WXDLLEXPORT
448
449 // no thread support
450 inline void WXDLLEXPORT wxMutexGuiEnter() { }
451 inline void WXDLLEXPORT wxMutexGuiLeave() { }
452
453 // macros for entering/leaving critical sections which may be used without
454 // having to take them inside "#if wxUSE_THREADS"
455 #define wxENTER_CRIT_SECT(cs)
456 #define wxLEAVE_CRIT_SECT(cs)
457 #define wxCRIT_SECT_DECLARE(cs)
458 #define wxCRIT_SECT_LOCKER(name, cs)
459
460 #endif // wxUSE_THREADS
461
462 // automatically unlock GUI mutex in dtor
463 class WXDLLEXPORT wxMutexGuiLocker
464 {
465 public:
466 wxMutexGuiLocker() { wxMutexGuiEnter(); }
467 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
468 };
469
470 // -----------------------------------------------------------------------------
471 // implementation only until the end of file
472 // -----------------------------------------------------------------------------
473
474 #if wxUSE_THREADS
475
476 #if defined(__WXMSW__)
477 // unlock GUI if there are threads waiting for and lock it back when
478 // there are no more of them - should be called periodically by the main
479 // thread
480 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
481
482 // returns TRUE if the main thread has GUI lock
483 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
484
485 // wakes up the main thread if it's sleeping inside ::GetMessage()
486 extern void WXDLLEXPORT wxWakeUpMainThread();
487
488 // return TRUE if the main thread is waiting for some other to terminate:
489 // wxApp then should block all "dangerous" messages
490 extern bool WXDLLEXPORT wxIsWaitingForThread();
491 #elif defined(__WXMAC__)
492 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
493
494 // returns TRUE if the main thread has GUI lock
495 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
496
497 // wakes up the main thread if it's sleeping inside ::GetMessage()
498 extern void WXDLLEXPORT wxWakeUpMainThread();
499
500 // return TRUE if the main thread is waiting for some other to terminate:
501 // wxApp then should block all "dangerous" messages
502 extern bool WXDLLEXPORT wxIsWaitingForThread();
503
504 // implement wxCriticalSection using mutexes
505 inline wxCriticalSection::wxCriticalSection() { }
506 inline wxCriticalSection::~wxCriticalSection() { }
507
508 inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
509 inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
510 #elif defined(__WXPM__)
511 // unlock GUI if there are threads waiting for and lock it back when
512 // there are no more of them - should be called periodically by the main
513 // thread
514 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
515
516 // returns TRUE if the main thread has GUI lock
517 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
518
519 // return TRUE if the main thread is waiting for some other to terminate:
520 // wxApp then should block all "dangerous" messages
521 extern bool WXDLLEXPORT wxIsWaitingForThread();
522
523 #else // !MSW && !PM
524 // implement wxCriticalSection using mutexes
525 inline wxCriticalSection::wxCriticalSection() { }
526 inline wxCriticalSection::~wxCriticalSection() { }
527
528 inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
529 inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
530 #endif // MSW/!MSW
531
532 // we can define these inline functions now (they should be defined after
533 // wxCriticalSection::Enter/Leave)
534 inline
535 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection& cs)
536 : m_critsect(cs) { m_critsect.Enter(); }
537 inline
538 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect.Leave(); }
539 #endif // wxUSE_THREADS
540
541 #endif // __THREADH__
542
543 // vi:sts=4:sw=4:et