1. wxIcon/wxCursor change, wxGDIImage class added
[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_MISC_ERROR // Some other error
57 };
58
59 // defines the interval of priority
60 enum
61 {
62 WXTHREAD_MIN_PRIORITY = 0u,
63 WXTHREAD_DEFAULT_PRIORITY = 50u,
64 WXTHREAD_MAX_PRIORITY = 100u
65 };
66
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 // ----------------------------------------------------------------------------
73
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
78 {
79 public:
80 // constructor & destructor
81 wxMutex();
82 ~wxMutex();
83
84 // Lock the mutex.
85 wxMutexError Lock();
86 // Try to lock the mutex: if it can't, returns immediately with an error.
87 wxMutexError TryLock();
88 // Unlock the mutex.
89 wxMutexError Unlock();
90
91 // Returns true if the mutex is locked.
92 bool IsLocked() const { return (m_locked > 0); }
93
94 protected:
95 friend class wxCondition;
96
97 // no assignment operator nor copy ctor
98 wxMutex(const wxMutex&);
99 wxMutex& operator=(const wxMutex&);
100
101 int m_locked;
102 wxMutexInternal *p_internal;
103 };
104
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
109 {
110 public:
111 // lock the mutex in the ctor
112 wxMutexLocker(wxMutex& mutex) : m_mutex(mutex)
113 { m_isOk = m_mutex.Lock() == wxMUTEX_NO_ERROR; }
114
115 // returns TRUE if mutex was successfully locked in ctor
116 bool IsOk() const
117 { return m_isOk; }
118
119 // unlock the mutex in dtor
120 ~wxMutexLocker()
121 { if ( IsOk() ) m_mutex.Unlock(); }
122
123 private:
124 // no assignment operator nor copy ctor
125 wxMutexLocker(const wxMutexLocker&);
126 wxMutexLocker& operator=(const wxMutexLocker&);
127
128 bool m_isOk;
129 wxMutex& m_mutex;
130 };
131
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
136 // mutexes.
137 //
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 // ----------------------------------------------------------------------------
141
142 class WXDLLEXPORT wxCriticalSectionInternal;
143
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
148
149 #define wxCRITSECT_IS_MUTEX 1
150 #else // MSW || Mac || OS2
151 #define WXCRITICAL_INLINE
152
153 #define wxCRITSECT_IS_MUTEX 0
154 #endif // MSW/!MSW
155
156 // you should consider wxCriticalSectionLocker whenever possible instead of
157 // directly working with wxCriticalSection class - it is safer
158 class WXDLLEXPORT wxCriticalSection
159 {
160 public:
161 // ctor & dtor
162 WXCRITICAL_INLINE wxCriticalSection();
163 WXCRITICAL_INLINE ~wxCriticalSection();
164
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();
169
170 private:
171 // no assignment operator nor copy ctor
172 wxCriticalSection(const wxCriticalSection&);
173 wxCriticalSection& operator=(const wxCriticalSection&);
174
175 #if wxCRITSECT_IS_MUTEX
176 wxMutex m_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
181 char m_buffer[24];
182 #elif !defined(__WXPM__)
183 wxCriticalSectionInternal *m_critsect;
184 #else
185 // nothing for OS/2
186 #endif // !Unix/Unix
187 };
188
189 // keep your preprocessor name space clean
190 #undef WXCRITICAL_INLINE
191
192 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
193 // to th mutexes
194 class WXDLLEXPORT wxCriticalSectionLocker
195 {
196 public:
197 inline wxCriticalSectionLocker(wxCriticalSection& critsect);
198 inline ~wxCriticalSectionLocker();
199
200 private:
201 // no assignment operator nor copy ctor
202 wxCriticalSectionLocker(const wxCriticalSectionLocker&);
203 wxCriticalSectionLocker& operator=(const wxCriticalSectionLocker&);
204
205 wxCriticalSection& m_critsect;
206 };
207
208 // ----------------------------------------------------------------------------
209 // Condition handler.
210 // ----------------------------------------------------------------------------
211
212 class wxConditionInternal;
213 class WXDLLEXPORT wxCondition
214 {
215 public:
216 // constructor & destructor
217 wxCondition();
218 ~wxCondition();
219
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.
225 void Signal();
226 // Broadcasts to all "Waiters".
227 void Broadcast();
228
229 private:
230 wxConditionInternal *p_internal;
231 };
232
233 // ----------------------------------------------------------------------------
234 // Thread management class
235 // ----------------------------------------------------------------------------
236
237 // FIXME Thread termination model is still unclear. Delete() should probably
238 // have a timeout after which the thread must be Kill()ed.
239
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
245 {
246 public:
247 // the return type for the thread function
248 typedef void *ExitCode;
249
250 // static functions
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();
257
258 // Returns true if current thread is the main thread.
259 static bool IsMain();
260
261 // Release the rest of our time slice leting the other threads run
262 static void Yield();
263
264 // Sleep during the specified period of time in milliseconds
265 //
266 // NB: at least under MSW worker threads can not call ::wxSleep()!
267 static void Sleep(unsigned long milliseconds);
268
269 // default constructor
270 wxThread();
271
272 // function that change the thread state
273 // create a new thread - call Run() to start it
274 wxThreadError Create();
275
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.
279 wxThreadError Run();
280
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.
287 ExitCode Delete();
288
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();
295
296 // pause a running thread
297 wxThreadError Pause();
298
299 // resume a paused thread
300 wxThreadError Resume();
301
302 // priority
303 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
304 //
305 // NB: the priority can only be set before the thread is created
306 void SetPriority(unsigned int prio);
307
308 // Get the current priority.
309 unsigned int GetPriority() const;
310
311 // Get the thread ID - a platform dependent number which uniquely
312 // identifies a thread inside a process
313 unsigned long GetID() const;
314
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;
322
323 // called when the thread exits - in the context of this thread
324 //
325 // NB: this function will not be called if the thread is Kill()ed
326 virtual void OnExit() { }
327
328 protected:
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()!
332 bool TestDestroy();
333
334 // exits from the current thread - can be called only from this thread
335 void Exit(void *exitcode = 0);
336
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.
340 //
341 // NB: derived classes dtors shouldn't be public neither!
342 virtual ~wxThread();
343
344 // entry point for the thread - called by Run() and executes in the context
345 // of this thread.
346 virtual void *Entry() = 0;
347
348 private:
349 // no copy ctor/assignment operator
350 wxThread(const wxThread&);
351 wxThread& operator=(const wxThread&);
352
353 friend class wxThreadInternal;
354
355 // the (platform-dependent) thread class implementation
356 wxThreadInternal *p_internal;
357
358 // protects access to any methods of wxThreadInternal object
359 wxCriticalSection m_critsect;
360 };
361
362 // ----------------------------------------------------------------------------
363 // Automatic initialization
364 // ----------------------------------------------------------------------------
365
366 // GUI mutex handling.
367 void WXDLLEXPORT wxMutexGuiEnter();
368 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) (cs)->Enter()
373 #define wxLEAVE_CRIT_SECT(cs) (cs)->Leave()
374 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(*cs)
375
376 #else // !wxUSE_THREADS
377
378 #include "wx/defs.h" // for WXDLLEXPORT
379
380 // no thread support
381 inline void WXDLLEXPORT wxMutexGuiEnter() { }
382 inline void WXDLLEXPORT wxMutexGuiLeave() { }
383
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)
389
390 #endif // wxUSE_THREADS
391
392 // automatically unlock GUI mutex in dtor
393 class WXDLLEXPORT wxMutexGuiLocker
394 {
395 public:
396 wxMutexGuiLocker() { wxMutexGuiEnter(); }
397 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
398 };
399
400 // -----------------------------------------------------------------------------
401 // implementation only until the end of file
402 // -----------------------------------------------------------------------------
403
404 #if wxUSE_THREADS
405
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
409 // thread
410 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
411
412 // returns TRUE if the main thread has GUI lock
413 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
414
415 // wakes up the main thread if it's sleeping inside ::GetMessage()
416 extern void WXDLLEXPORT wxWakeUpMainThread();
417
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();
423
424 // returns TRUE if the main thread has GUI lock
425 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
426
427 // wakes up the main thread if it's sleeping inside ::GetMessage()
428 extern void WXDLLEXPORT wxWakeUpMainThread();
429
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
436 // thread
437 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
438
439 // returns TRUE if the main thread has GUI lock
440 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
441
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();
445
446 #else // !MSW && !PM
447 // implement wxCriticalSection using mutexes
448 inline wxCriticalSection::wxCriticalSection() { }
449 inline wxCriticalSection::~wxCriticalSection() { }
450
451 inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
452 inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
453 #endif // MSW/!MSW
454
455 // we can define these inline functions now (they should be defined after
456 // wxCriticalSection::Enter/Leave)
457 inline
458 wxCriticalSectionLocker:: wxCriticalSectionLocker(wxCriticalSection& cs)
459 : m_critsect(cs) { m_critsect.Enter(); }
460 inline
461 wxCriticalSectionLocker::~wxCriticalSectionLocker() { m_critsect.Leave(); }
462 #endif // wxUSE_THREADS
463
464 #endif // __THREADH__