OS/2 thread updates
[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 /* otherwise we get undefined references for non-thread case (KB)*/
25 #ifdef __GNUG__
26 #pragma interface "thread.h"
27 #endif
28
29 // Windows headers define it
30 #ifdef Yield
31 #undef Yield
32 #endif
33
34 #include "wx/module.h"
35
36 // ----------------------------------------------------------------------------
37 // constants
38 // ----------------------------------------------------------------------------
39
40 typedef enum
41 {
42 wxMUTEX_NO_ERROR = 0,
43 wxMUTEX_DEAD_LOCK, // Mutex has been already locked by THE CALLING thread
44 wxMUTEX_BUSY, // Mutex has been already locked by ONE thread
45 wxMUTEX_UNLOCKED,
46 wxMUTEX_MISC_ERROR
47 } wxMutexError;
48
49 typedef enum
50 {
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
56 } wxThreadError;
57
58 // defines the interval of priority
59 #define WXTHREAD_MIN_PRIORITY 0u
60 #define WXTHREAD_DEFAULT_PRIORITY 50u
61 #define WXTHREAD_MAX_PRIORITY 100u
62
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 // ----------------------------------------------------------------------------
69
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
74 {
75 public:
76 // constructor & destructor
77 wxMutex();
78 ~wxMutex();
79
80 // Lock the mutex.
81 wxMutexError Lock();
82 // Try to lock the mutex: if it can't, returns immediately with an error.
83 wxMutexError TryLock();
84 // Unlock the mutex.
85 wxMutexError Unlock();
86
87 // Returns true if the mutex is locked.
88 bool IsLocked() const { return (m_locked > 0); }
89
90 protected:
91 friend class wxCondition;
92
93 // no assignment operator nor copy ctor
94 wxMutex(const wxMutex&);
95 wxMutex& operator=(const wxMutex&);
96
97 int m_locked;
98 wxMutexInternal *p_internal;
99 };
100
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
105 {
106 public:
107 // lock the mutex in the ctor
108 wxMutexLocker(wxMutex& mutex) : m_mutex(mutex)
109 { m_isOk = m_mutex.Lock() == wxMUTEX_NO_ERROR; }
110
111 // returns TRUE if mutex was successfully locked in ctor
112 bool IsOk() const
113 { return m_isOk; }
114
115 // unlock the mutex in dtor
116 ~wxMutexLocker()
117 { if ( IsOk() ) m_mutex.Unlock(); }
118
119 private:
120 // no assignment operator nor copy ctor
121 wxMutexLocker(const wxMutexLocker&);
122 wxMutexLocker& operator=(const wxMutexLocker&);
123
124 bool m_isOk;
125 wxMutex& m_mutex;
126 };
127
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
132 // mutexes
133 // ----------------------------------------------------------------------------
134
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__)
138 class WXDLLEXPORT wxCriticalSectionInternal;
139 #define WXCRITICAL_INLINE
140 #elif defined(__WXMAC__)
141 class WXDLLEXPORT wxCriticalSectionInternal;
142 #define WXCRITICAL_INLINE
143 #elif defined(__WXPM__)
144 #define WXCRITICAL_INLINE
145 #else // !MSW && !PM
146 #define WXCRITICAL_INLINE inline
147 #endif // MSW/!MSW
148
149 // you should consider wxCriticalSectionLocker whenever possible instead of
150 // directly working with wxCriticalSection class - it is safer
151 class WXDLLEXPORT wxCriticalSection
152 {
153 public:
154 // ctor & dtor
155 WXCRITICAL_INLINE wxCriticalSection();
156 WXCRITICAL_INLINE ~wxCriticalSection();
157
158 // enter the section (the same as locking a mutex)
159 WXCRITICAL_INLINE void Enter();
160 // leave the critical section (same as unlocking a mutex)
161 WXCRITICAL_INLINE void Leave();
162
163 private:
164 // no assignment operator nor copy ctor
165 wxCriticalSection(const wxCriticalSection&);
166 wxCriticalSection& operator=(const wxCriticalSection&);
167
168 #if defined(__WXMSW__) || defined(__WXMAC__)
169 wxCriticalSectionInternal *m_critsect;
170 #else // !MSW
171 wxMutex m_mutex;
172 #endif // MSW/!MSW
173 };
174
175 // keep your preprocessor name space clean
176 #undef WXCRITICAL_INLINE
177
178 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
179 // to th mutexes
180 class WXDLLEXPORT wxCriticalSectionLocker
181 {
182 public:
183 inline wxCriticalSectionLocker(wxCriticalSection& critsect);
184 inline ~wxCriticalSectionLocker();
185
186 private:
187 // no assignment operator nor copy ctor
188 wxCriticalSectionLocker(const wxCriticalSectionLocker&);
189 wxCriticalSectionLocker& operator=(const wxCriticalSectionLocker&);
190
191 wxCriticalSection& m_critsect;
192 };
193
194 // ----------------------------------------------------------------------------
195 // Condition handler.
196 // ----------------------------------------------------------------------------
197
198 class wxConditionInternal;
199 class WXDLLEXPORT wxCondition
200 {
201 public:
202 // constructor & destructor
203 wxCondition();
204 ~wxCondition();
205
206 // Waits indefinitely.
207 void Wait(wxMutex& mutex);
208 // Waits until a signal is raised or the timeout is elapsed.
209 bool Wait(wxMutex& mutex, unsigned long sec, unsigned long nsec);
210 // Raises a signal: only one "Waiter" is released.
211 void Signal();
212 // Broadcasts to all "Waiters".
213 void Broadcast();
214
215 private:
216 wxConditionInternal *p_internal;
217 };
218
219 // ----------------------------------------------------------------------------
220 // Thread management class
221 // ----------------------------------------------------------------------------
222
223 // FIXME Thread termination model is still unclear. Delete() should probably
224 // have a timeout after which the thread must be Kill()ed.
225
226 // NB: in the function descriptions the words "this thread" mean the thread
227 // created by the wxThread object while "main thread" is the thread created
228 // during the process initialization (a.k.a. the GUI thread)
229 class wxThreadInternal;
230 class WXDLLEXPORT wxThread
231 {
232 public:
233 // the return type for the thread function
234 typedef void *ExitCode;
235
236 // static functions
237 // Returns the wxThread object for the calling thread. NULL is returned
238 // if the caller is the main thread (but it's recommended to use
239 // IsMain() and only call This() for threads other than the main one
240 // because NULL is also returned on error). If the thread wasn't
241 // created with wxThread class, the returned value is undefined.
242 static wxThread *This();
243
244 // Returns true if current thread is the main thread.
245 static bool IsMain();
246
247 // Release the rest of our time slice leting the other threads run
248 static void Yield();
249
250 // Sleep during the specified period of time in milliseconds
251 //
252 // NB: at least under MSW worker threads can not call ::wxSleep()!
253 static void Sleep(unsigned long milliseconds);
254
255 // default constructor
256 wxThread();
257
258 // function that change the thread state
259 // create a new thread - call Run() to start it
260 wxThreadError Create();
261
262 // starts execution of the thread - from the moment Run() is called the
263 // execution of wxThread::Entry() may start at any moment, caller
264 // shouldn't suppose that it starts after (or before) Run() returns.
265 wxThreadError Run();
266
267 // stops the thread if it's running and deletes the wxThread object
268 // freeing its memory. This function should also be called if the
269 // Create() or Run() fails to free memory (otherwise it will be done by
270 // the thread itself when it terminates). The return value is the
271 // thread exit code if the thread was gracefully terminated, 0 if it
272 // wasn't running and -1 if an error occured.
273 ExitCode Delete();
274
275 // kills the thread without giving it any chance to clean up - should
276 // not be used in normal circumstances, use Delete() instead. It is a
277 // dangerous function that should only be used in the most extreme
278 // cases! The wxThread object is deleted by Kill() if thread was
279 // killed (i.e. no errors occured).
280 wxThreadError Kill();
281
282 // pause a running thread
283 wxThreadError Pause();
284
285 // resume a paused thread
286 wxThreadError Resume();
287
288 // priority
289 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
290 //
291 // NB: the priority can only be set before the thread is created
292 void SetPriority(unsigned int prio);
293
294 // Get the current priority.
295 unsigned int GetPriority() const;
296
297 // Get the thread ID - a platform dependent number which uniquely
298 // identifies a thread inside a process
299 unsigned long GetID() const;
300
301 // thread status inquiries
302 // Returns true if the thread is alive: i.e. running or suspended
303 bool IsAlive() const;
304 // Returns true if the thread is running (not paused, not killed).
305 bool IsRunning() const;
306 // Returns true if the thread is suspended
307 bool IsPaused() const;
308
309 // called when the thread exits - in the context of this thread
310 //
311 // NB: this function will not be called if the thread is Kill()ed
312 virtual void OnExit() { }
313
314 protected:
315 // Returns TRUE if the thread was asked to terminate: this function should
316 // be called by the thread from time to time, otherwise the main thread
317 // will be left forever in Delete()!
318 bool TestDestroy();
319
320 // exits from the current thread - can be called only from this thread
321 void Exit(void *exitcode = 0);
322
323 // destructor is private - user code can't delete thread objects, they will
324 // auto-delete themselves (and thus must be always allocated on the heap).
325 // Use Delete() or Kill() instead.
326 //
327 // NB: derived classes dtors shouldn't be public neither!
328 virtual ~wxThread();
329
330 // entry point for the thread - called by Run() and executes in the context
331 // of this thread.
332 virtual void *Entry() = 0;
333
334 private:
335 // no copy ctor/assignment operator
336 wxThread(const wxThread&);
337 wxThread& operator=(const wxThread&);
338
339 friend class wxThreadInternal;
340
341 // the (platform-dependent) thread class implementation
342 wxThreadInternal *p_internal;
343
344 // protects access to any methods of wxThreadInternal object
345 wxCriticalSection m_critsect;
346 };
347
348 // ----------------------------------------------------------------------------
349 // Automatic initialization
350 // ----------------------------------------------------------------------------
351
352 // GUI mutex handling.
353 void WXDLLEXPORT wxMutexGuiEnter();
354 void WXDLLEXPORT wxMutexGuiLeave();
355
356 // macros for entering/leaving critical sections which may be used without
357 // having to take them inside "#if wxUSE_THREADS"
358 #define wxENTER_CRIT_SECT(cs) (cs)->Enter()
359 #define wxLEAVE_CRIT_SECT(cs) (cs)->Leave()
360 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(*cs)
361
362 #else // !wxUSE_THREADS
363
364 #include "wx/defs.h" // for WXDLLEXPORT
365
366 // no thread support
367 inline void WXDLLEXPORT wxMutexGuiEnter() { }
368 inline void WXDLLEXPORT wxMutexGuiLeave() { }
369
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)
373 #define wxLEAVE_CRIT_SECT(cs)
374 #define wxCRIT_SECT_LOCKER(name, cs)
375
376 #endif // wxUSE_THREADS
377
378 // automatically unlock GUI mutex in dtor
379 class WXDLLEXPORT wxMutexGuiLocker
380 {
381 public:
382 wxMutexGuiLocker() { wxMutexGuiEnter(); }
383 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
384 };
385
386 // -----------------------------------------------------------------------------
387 // implementation only until the end of file
388 // -----------------------------------------------------------------------------
389
390 #if wxUSE_THREADS
391
392 #if defined(__WXMSW__)
393 // unlock GUI if there are threads waiting for and lock it back when
394 // there are no more of them - should be called periodically by the main
395 // thread
396 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
397
398 // returns TRUE if the main thread has GUI lock
399 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
400
401 // wakes up the main thread if it's sleeping inside ::GetMessage()
402 extern void WXDLLEXPORT wxWakeUpMainThread();
403
404 // return TRUE if the main thread is waiting for some other to terminate:
405 // wxApp then should block all "dangerous" messages
406 extern bool WXDLLEXPORT wxIsWaitingForThread();
407 #elif defined(__WXMAC__)
408 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
409
410 // returns TRUE if the main thread has GUI lock
411 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
412
413 // wakes up the main thread if it's sleeping inside ::GetMessage()
414 extern void WXDLLEXPORT wxWakeUpMainThread();
415
416 // return TRUE if the main thread is waiting for some other to terminate:
417 // wxApp then should block all "dangerous" messages
418 extern bool WXDLLEXPORT wxIsWaitingForThread();
419 #elif defined(__WXPM__)
420 // unlock GUI if there are threads waiting for and lock it back when
421 // there are no more of them - should be called periodically by the main
422 // thread
423 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
424
425 // returns TRUE if the main thread has GUI lock
426 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
427
428 // return TRUE if the main thread is waiting for some other to terminate:
429 // wxApp then should block all "dangerous" messages
430 extern bool WXDLLEXPORT wxIsWaitingForThread();
431
432 #else // !MSW && !PM
433 // implement wxCriticalSection using mutexes
434 inline wxCriticalSection::wxCriticalSection() { }
435 inline wxCriticalSection::~wxCriticalSection() { }
436
437 inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
438 inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
439 #endif // MSW/!MSW
440
441 // we can define these inline functions now (they should be defined after
442 // wxCriticalSection::Enter/Leave)
443 inline
444 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection& cs)
445 : m_critsect(cs) { m_critsect.Enter(); }
446 inline
447 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect.Leave(); }
448 #endif // wxUSE_THREADS
449
450 #endif // __THREADH__