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