]> git.saurik.com Git - wxWidgets.git/blame - include/wx/thread.h
1. wxIcon/wxCursor change, wxGDIImage class added
[wxWidgets.git] / include / wx / thread.h
CommitLineData
10b959e3
JS
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.h
3// Purpose: Thread API
4// Author: Guilhem Lavaux
bf1852e1
VZ
5// Modified by: Vadim Zeitlin (modifications partly inspired by omnithreads
6// package from Olivetti & Oracle Research Laboratory)
10b959e3
JS
7// Created: 04/13/98
8// RCS-ID: $Id$
9// Copyright: (c) Guilhem Lavaux
10// Licence: wxWindows licence
11/////////////////////////////////////////////////////////////////////////////
12
c2dd8380
GL
13#ifndef __THREADH__
14#define __THREADH__
10b959e3 15
9d133d87
VZ
16// ----------------------------------------------------------------------------
17// headers
18// ----------------------------------------------------------------------------
bf1852e1
VZ
19
20// get the value of wxUSE_THREADS configuration flag
10b959e3 21#include "wx/setup.h"
9d133d87
VZ
22
23#if wxUSE_THREADS
6d167489
VZ
24
25// only for wxUSE_THREADS - otherwise we'd get undefined symbols
80cb83be
KB
26#ifdef __GNUG__
27 #pragma interface "thread.h"
28#endif
bf1852e1
VZ
29
30// Windows headers define it
31#ifdef Yield
32 #undef Yield
33#endif
34
d524867f 35#include "wx/module.h"
10b959e3 36
a6b0bd49
VZ
37// ----------------------------------------------------------------------------
38// constants
39// ----------------------------------------------------------------------------
40
6d167489 41enum wxMutexError
d524867f 42{
a6b0bd49 43 wxMUTEX_NO_ERROR = 0,
bf1852e1 44 wxMUTEX_DEAD_LOCK, // Mutex has been already locked by THE CALLING thread
a6b0bd49
VZ
45 wxMUTEX_BUSY, // Mutex has been already locked by ONE thread
46 wxMUTEX_UNLOCKED,
47 wxMUTEX_MISC_ERROR
6d167489 48};
10b959e3 49
6d167489 50enum wxThreadError
d524867f 51{
a6b0bd49
VZ
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
6d167489 57};
10b959e3 58
bf1852e1 59// defines the interval of priority
6d167489
VZ
60enum
61{
62 WXTHREAD_MIN_PRIORITY = 0u,
63 WXTHREAD_DEFAULT_PRIORITY = 50u,
64 WXTHREAD_MAX_PRIORITY = 100u
65};
10b959e3 66
d524867f 67// ----------------------------------------------------------------------------
9d133d87
VZ
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.
a6b0bd49 72// ----------------------------------------------------------------------------
d524867f 73
9d133d87
VZ
74// you should consider wxMutexLocker whenever possible instead of directly
75// working with wxMutex class - it is safer
c2dd8380 76class WXDLLEXPORT wxMutexInternal;
bf1852e1 77class WXDLLEXPORT wxMutex
d524867f 78{
10b959e3 79public:
bf1852e1 80 // constructor & destructor
cb4f1ca4
VZ
81 wxMutex();
82 ~wxMutex();
10b959e3 83
cb4f1ca4
VZ
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();
10b959e3 90
cb4f1ca4
VZ
91 // Returns true if the mutex is locked.
92 bool IsLocked() const { return (m_locked > 0); }
a6b0bd49 93
10b959e3 94protected:
cb4f1ca4 95 friend class wxCondition;
10b959e3 96
cb4f1ca4
VZ
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;
10b959e3
JS
103};
104
9d133d87
VZ
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
108class WXDLLEXPORT wxMutexLocker
109{
110public:
111 // lock the mutex in the ctor
7c3d7e2d
VZ
112 wxMutexLocker(wxMutex& mutex) : m_mutex(mutex)
113 { m_isOk = m_mutex.Lock() == wxMUTEX_NO_ERROR; }
9d133d87
VZ
114
115 // returns TRUE if mutex was successfully locked in ctor
7c3d7e2d
VZ
116 bool IsOk() const
117 { return m_isOk; }
9d133d87
VZ
118
119 // unlock the mutex in dtor
7c3d7e2d
VZ
120 ~wxMutexLocker()
121 { if ( IsOk() ) m_mutex.Unlock(); }
9d133d87
VZ
122
123private:
cb4f1ca4
VZ
124 // no assignment operator nor copy ctor
125 wxMutexLocker(const wxMutexLocker&);
126 wxMutexLocker& operator=(const wxMutexLocker&);
127
9d133d87 128 bool m_isOk;
7c3d7e2d 129 wxMutex& m_mutex;
9d133d87
VZ
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
6d167489
VZ
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
9d133d87
VZ
140// ----------------------------------------------------------------------------
141
6d167489
VZ
142class 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__)
f6ddc54a 147 #define WXCRITICAL_INLINE inline
6d167489
VZ
148
149 #define wxCRITSECT_IS_MUTEX 1
150#else // MSW || Mac || OS2
151 #define WXCRITICAL_INLINE
152
153 #define wxCRITSECT_IS_MUTEX 0
f6ddc54a 154#endif // MSW/!MSW
bf1852e1
VZ
155
156// you should consider wxCriticalSectionLocker whenever possible instead of
157// directly working with wxCriticalSection class - it is safer
9d133d87
VZ
158class WXDLLEXPORT wxCriticalSection
159{
160public:
161 // ctor & dtor
f6ddc54a
VZ
162 WXCRITICAL_INLINE wxCriticalSection();
163 WXCRITICAL_INLINE ~wxCriticalSection();
9d133d87
VZ
164
165 // enter the section (the same as locking a mutex)
68401dfe 166 WXCRITICAL_INLINE void Enter();
9d133d87 167 // leave the critical section (same as unlocking a mutex)
68401dfe 168 WXCRITICAL_INLINE void Leave();
9d133d87
VZ
169
170private:
cb4f1ca4
VZ
171 // no assignment operator nor copy ctor
172 wxCriticalSection(const wxCriticalSection&);
173 wxCriticalSection& operator=(const wxCriticalSection&);
174
6d167489 175#if wxCRITSECT_IS_MUTEX
f6ddc54a 176 wxMutex m_mutex;
6d167489
VZ
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
9d133d87
VZ
187};
188
bf1852e1
VZ
189// keep your preprocessor name space clean
190#undef WXCRITICAL_INLINE
191
9d133d87
VZ
192// wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is
193// to th mutexes
194class WXDLLEXPORT wxCriticalSectionLocker
195{
196public:
dcda1c71
VZ
197 inline wxCriticalSectionLocker(wxCriticalSection& critsect);
198 inline ~wxCriticalSectionLocker();
9d133d87
VZ
199
200private:
cb4f1ca4
VZ
201 // no assignment operator nor copy ctor
202 wxCriticalSectionLocker(const wxCriticalSectionLocker&);
203 wxCriticalSectionLocker& operator=(const wxCriticalSectionLocker&);
204
bee503b0 205 wxCriticalSection& m_critsect;
9d133d87
VZ
206};
207
a6b0bd49 208// ----------------------------------------------------------------------------
10b959e3 209// Condition handler.
a6b0bd49 210// ----------------------------------------------------------------------------
d524867f 211
10b959e3 212class wxConditionInternal;
bf1852e1 213class WXDLLEXPORT wxCondition
d524867f 214{
10b959e3
JS
215public:
216 // constructor & destructor
ee4f8c2a
JS
217 wxCondition();
218 ~wxCondition();
10b959e3 219
ee4f8c2a 220 // Waits indefinitely.
10b959e3
JS
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.
ee4f8c2a 225 void Signal();
10b959e3 226 // Broadcasts to all "Waiters".
ee4f8c2a 227 void Broadcast();
a6b0bd49 228
10b959e3
JS
229private:
230 wxConditionInternal *p_internal;
231};
232
a6b0bd49 233// ----------------------------------------------------------------------------
10b959e3 234// Thread management class
a6b0bd49 235// ----------------------------------------------------------------------------
d524867f 236
bf1852e1
VZ
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)
10b959e3 243class wxThreadInternal;
bf1852e1 244class WXDLLEXPORT wxThread
d524867f 245{
10b959e3 246public:
bf1852e1
VZ
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
a737331d 321 bool IsPaused() const;
bf1852e1
VZ
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() { }
10b959e3 327
bf1852e1
VZ
328protected:
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()!
8c10faf1 332 bool TestDestroy();
10b959e3 333
bf1852e1
VZ
334 // exits from the current thread - can be called only from this thread
335 void Exit(void *exitcode = 0);
c2dd8380 336
bf1852e1
VZ
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();
9d133d87 343
bf1852e1
VZ
344 // entry point for the thread - called by Run() and executes in the context
345 // of this thread.
346 virtual void *Entry() = 0;
a6b0bd49 347
10b959e3 348private:
bf1852e1
VZ
349 // no copy ctor/assignment operator
350 wxThread(const wxThread&);
351 wxThread& operator=(const wxThread&);
10b959e3 352
bf1852e1
VZ
353 friend class wxThreadInternal;
354
355 // the (platform-dependent) thread class implementation
356 wxThreadInternal *p_internal;
10b959e3 357
bf1852e1
VZ
358 // protects access to any methods of wxThreadInternal object
359 wxCriticalSection m_critsect;
10b959e3
JS
360};
361
a6b0bd49 362// ----------------------------------------------------------------------------
d524867f 363// Automatic initialization
a6b0bd49 364// ----------------------------------------------------------------------------
10b959e3 365
9d133d87
VZ
366// GUI mutex handling.
367void WXDLLEXPORT wxMutexGuiEnter();
368void WXDLLEXPORT wxMutexGuiLeave();
d524867f 369
72cdf4c9
VZ
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
9d133d87 376#else // !wxUSE_THREADS
d524867f 377
ed58dbea 378#include "wx/defs.h" // for WXDLLEXPORT
518b5d2f 379
9d133d87
VZ
380// no thread support
381inline void WXDLLEXPORT wxMutexGuiEnter() { }
382inline void WXDLLEXPORT wxMutexGuiLeave() { }
d524867f 383
72cdf4c9
VZ
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
9d133d87 390#endif // wxUSE_THREADS
10b959e3 391
bee503b0
VZ
392// automatically unlock GUI mutex in dtor
393class WXDLLEXPORT wxMutexGuiLocker
394{
395public:
396 wxMutexGuiLocker() { wxMutexGuiEnter(); }
397 ~wxMutexGuiLocker() { wxMutexGuiLeave(); }
398};
399
f6ddc54a
VZ
400// -----------------------------------------------------------------------------
401// implementation only until the end of file
402// -----------------------------------------------------------------------------
dcda1c71 403
9838df2c 404#if wxUSE_THREADS
dcda1c71 405
d8dd11ba 406#if defined(__WXMSW__)
f6ddc54a
VZ
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
a0abb8a8 410 extern void WXDLLEXPORT wxMutexGuiLeaveOrEnter();
f6ddc54a
VZ
411
412 // returns TRUE if the main thread has GUI lock
a0abb8a8 413 extern bool WXDLLEXPORT wxGuiOwnedByMainThread();
f6ddc54a
VZ
414
415 // wakes up the main thread if it's sleeping inside ::GetMessage()
a0abb8a8 416 extern void WXDLLEXPORT wxWakeUpMainThread();
bf1852e1 417
e7549107
SC
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
bf1852e1
VZ
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();
d8dd11ba
DW
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();
20947e08 441
d45d30c8
DW
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();
20947e08 445
d8dd11ba 446#else // !MSW && !PM
f6ddc54a
VZ
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
dcda1c71
VZ
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(); }
f6ddc54a
VZ
462#endif // wxUSE_THREADS
463
a6b0bd49 464#endif // __THREADH__