]> git.saurik.com Git - wxWidgets.git/blob - include/wx/thread.h
and the compilation fix for the warning fixes
[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(__WXPM__)
141 #define WXCRITICAL_INLINE
142 #else // !MSW && !PM
143 #define WXCRITICAL_INLINE inline
144 #endif // MSW/!MSW
145
146 // you should consider wxCriticalSectionLocker whenever possible instead of
147 // directly working with wxCriticalSection class - it is safer
148 class WXDLLEXPORT wxCriticalSection
149 {
150 public:
151 // ctor & dtor
152 WXCRITICAL_INLINE wxCriticalSection();
153 WXCRITICAL_INLINE ~wxCriticalSection();
154
155 // enter the section (the same as locking a mutex)
156 WXCRITICAL_INLINE void Enter();
157 // leave the critical section (same as unlocking a mutex)
158 WXCRITICAL_INLINE void Leave();
159
160 private:
161 // no assignment operator nor copy ctor
162 wxCriticalSection(const wxCriticalSection&);
163 wxCriticalSection& operator=(const wxCriticalSection&);
164
165 #if defined(__WXMSW__)
166 wxCriticalSectionInternal *m_critsect;
167 #else // !MSW
168 wxMutex m_mutex;
169 #endif // MSW/!MSW
170 };
171
172 // keep your preprocessor name space clean
173 #undef WXCRITICAL_INLINE
174
175 // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
176 // to th mutexes
177 class WXDLLEXPORT wxCriticalSectionLocker
178 {
179 public:
180 wxCriticalSectionLocker(wxCriticalSection& critsect) : m_critsect(critsect)
181 { m_critsect.Enter(); }
182 ~wxCriticalSectionLocker()
183 { m_critsect.Leave(); }
184
185 private:
186 // no assignment operator nor copy ctor
187 wxCriticalSectionLocker(const wxCriticalSectionLocker&);
188 wxCriticalSectionLocker& operator=(const wxCriticalSectionLocker&);
189
190 wxCriticalSection& m_critsect;
191 };
192
193 // ----------------------------------------------------------------------------
194 // Condition handler.
195 // ----------------------------------------------------------------------------
196
197 class wxConditionInternal;
198 class WXDLLEXPORT wxCondition
199 {
200 public:
201 // constructor & destructor
202 wxCondition();
203 ~wxCondition();
204
205 // Waits indefinitely.
206 void Wait(wxMutex& mutex);
207 // Waits until a signal is raised or the timeout is elapsed.
208 bool Wait(wxMutex& mutex, unsigned long sec, unsigned long nsec);
209 // Raises a signal: only one "Waiter" is released.
210 void Signal();
211 // Broadcasts to all "Waiters".
212 void Broadcast();
213
214 private:
215 wxConditionInternal *p_internal;
216 };
217
218 // ----------------------------------------------------------------------------
219 // Thread management class
220 // ----------------------------------------------------------------------------
221
222 // FIXME Thread termination model is still unclear. Delete() should probably
223 // have a timeout after which the thread must be Kill()ed.
224
225 // NB: in the function descriptions the words "this thread" mean the thread
226 // created by the wxThread object while "main thread" is the thread created
227 // during the process initialization (a.k.a. the GUI thread)
228 class wxThreadInternal;
229 class WXDLLEXPORT wxThread
230 {
231 public:
232 // the return type for the thread function
233 typedef void *ExitCode;
234
235 // static functions
236 // Returns the wxThread object for the calling thread. NULL is returned
237 // if the caller is the main thread (but it's recommended to use
238 // IsMain() and only call This() for threads other than the main one
239 // because NULL is also returned on error). If the thread wasn't
240 // created with wxThread class, the returned value is undefined.
241 static wxThread *This();
242
243 // Returns true if current thread is the main thread.
244 static bool IsMain();
245
246 // Release the rest of our time slice leting the other threads run
247 static void Yield();
248
249 // Sleep during the specified period of time in milliseconds
250 //
251 // NB: at least under MSW worker threads can not call ::wxSleep()!
252 static void Sleep(unsigned long milliseconds);
253
254 // default constructor
255 wxThread();
256
257 // function that change the thread state
258 // create a new thread - call Run() to start it
259 wxThreadError Create();
260
261 // starts execution of the thread - from the moment Run() is called the
262 // execution of wxThread::Entry() may start at any moment, caller
263 // shouldn't suppose that it starts after (or before) Run() returns.
264 wxThreadError Run();
265
266 // stops the thread if it's running and deletes the wxThread object
267 // freeing its memory. This function should also be called if the
268 // Create() or Run() fails to free memory (otherwise it will be done by
269 // the thread itself when it terminates). The return value is the
270 // thread exit code if the thread was gracefully terminated, 0 if it
271 // wasn't running and -1 if an error occured.
272 ExitCode Delete();
273
274 // kills the thread without giving it any chance to clean up - should
275 // not be used in normal circumstances, use Delete() instead. It is a
276 // dangerous function that should only be used in the most extreme
277 // cases! The wxThread object is deleted by Kill() if thread was
278 // killed (i.e. no errors occured).
279 wxThreadError Kill();
280
281 // pause a running thread
282 wxThreadError Pause();
283
284 // resume a paused thread
285 wxThreadError Resume();
286
287 // priority
288 // Sets the priority to "prio": see WXTHREAD_XXX_PRIORITY constants
289 //
290 // NB: the priority can only be set before the thread is created
291 void SetPriority(unsigned int prio);
292
293 // Get the current priority.
294 unsigned int GetPriority() const;
295
296 // Get the thread ID - a platform dependent number which uniquely
297 // identifies a thread inside a process
298 unsigned long GetID() const;
299
300 // thread status inquiries
301 // Returns true if the thread is alive: i.e. running or suspended
302 bool IsAlive() const;
303 // Returns true if the thread is running (not paused, not killed).
304 bool IsRunning() const;
305 // Returns true if the thread is suspended
306 bool IsPaused() const;
307
308 // called when the thread exits - in the context of this thread
309 //
310 // NB: this function will not be called if the thread is Kill()ed
311 virtual void OnExit() { }
312
313 protected:
314 // Returns TRUE if the thread was asked to terminate: this function should
315 // be called by the thread from time to time, otherwise the main thread
316 // will be left forever in Delete()!
317 bool TestDestroy();
318
319 // exits from the current thread - can be called only from this thread
320 void Exit(void *exitcode = 0);
321
322 // destructor is private - user code can't delete thread objects, they will
323 // auto-delete themselves (and thus must be always allocated on the heap).
324 // Use Delete() or Kill() instead.
325 //
326 // NB: derived classes dtors shouldn't be public neither!
327 virtual ~wxThread();
328
329 // entry point for the thread - called by Run() and executes in the context
330 // of this thread.
331 virtual void *Entry() = 0;
332
333 private:
334 // no copy ctor/assignment operator
335 wxThread(const wxThread&);
336 wxThread& operator=(const wxThread&);
337
338 friend class wxThreadInternal;
339
340 // the (platform-dependent) thread class implementation
341 wxThreadInternal *p_internal;
342
343 // protects access to any methods of wxThreadInternal object
344 wxCriticalSection m_critsect;
345 };
346
347 // ----------------------------------------------------------------------------
348 // Automatic initialization
349 // ----------------------------------------------------------------------------
350
351 // GUI mutex handling.
352 void WXDLLEXPORT wxMutexGuiEnter();
353 void WXDLLEXPORT wxMutexGuiLeave();
354
355 // macros for entering/leaving critical sections which may be used without
356 // having to take them inside "#if wxUSE_THREADS"
357 #define wxENTER_CRIT_SECT(cs) (cs)->Enter()
358 #define wxLEAVE_CRIT_SECT(cs) (cs)->Leave()
359 #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(*cs)
360
361 #else // !wxUSE_THREADS
362
363 #include "wx/defs.h" // for WXDLLEXPORT
364
365 // no thread support
366 inline void WXDLLEXPORT wxMutexGuiEnter() { }
367 inline void WXDLLEXPORT wxMutexGuiLeave() { }
368
369 // macros for entering/leaving critical sections which may be used without
370 // having to take them inside "#if wxUSE_THREADS"
371 #define wxENTER_CRIT_SECT(cs)
372 #define wxLEAVE_CRIT_SECT(cs)
373 #define wxCRIT_SECT_LOCKER(name, cs)
374
375 #endif // wxUSE_THREADS
376
377 // automatically unlock GUI mutex in dtor
378 class WXDLLEXPORT wxMutexGuiLocker
379 {
380 public:
381 wxMutexGuiLocker() { wxMutexGuiEnter(); }
382 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
383 };
384
385 // -----------------------------------------------------------------------------
386 // implementation only until the end of file
387 // -----------------------------------------------------------------------------
388 #if wxUSE_THREADS
389 #if defined(__WXMSW__)
390 // unlock GUI if there are threads waiting for and lock it back when
391 // there are no more of them - should be called periodically by the main
392 // thread
393 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
394
395 // returns TRUE if the main thread has GUI lock
396 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
397
398 // wakes up the main thread if it's sleeping inside ::GetMessage()
399 extern void WXDLLEXPORT wxWakeUpMainThread();
400
401 // return TRUE if the main thread is waiting for some other to terminate:
402 // wxApp then should block all "dangerous" messages
403 extern bool WXDLLEXPORT wxIsWaitingForThread();
404 #elif defined(__WXPM__)
405 // unlock GUI if there are threads waiting for and lock it back when
406 // there are no more of them - should be called periodically by the main
407 // thread
408 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
409
410 // returns TRUE if the main thread has GUI lock
411 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
412
413 inline wxCriticalSection::wxCriticalSection() { }
414 inline wxCriticalSection::~wxCriticalSection() { }
415 #else // !MSW && !PM
416 // implement wxCriticalSection using mutexes
417 inline wxCriticalSection::wxCriticalSection() { }
418 inline wxCriticalSection::~wxCriticalSection() { }
419
420 inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); }
421 inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); }
422 #endif // MSW/!MSW
423 #endif // wxUSE_THREADS
424
425 #endif // __THREADH__