/src/wxwidgets/include/wx/thread.h
Line | Count | Source (jump to first uncovered line) |
1 | | ///////////////////////////////////////////////////////////////////////////// |
2 | | // Name: wx/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 | | // Copyright: (c) Guilhem Lavaux |
9 | | // Licence: wxWindows licence |
10 | | ///////////////////////////////////////////////////////////////////////////// |
11 | | |
12 | | #ifndef _WX_THREAD_H_ |
13 | | #define _WX_THREAD_H_ |
14 | | |
15 | | // ---------------------------------------------------------------------------- |
16 | | // headers |
17 | | // ---------------------------------------------------------------------------- |
18 | | |
19 | | // get the value of wxUSE_THREADS configuration flag |
20 | | #include "wx/defs.h" |
21 | | |
22 | | #if wxUSE_THREADS |
23 | | |
24 | | // ---------------------------------------------------------------------------- |
25 | | // constants |
26 | | // ---------------------------------------------------------------------------- |
27 | | |
28 | | enum wxMutexError |
29 | | { |
30 | | wxMUTEX_NO_ERROR = 0, // operation completed successfully |
31 | | wxMUTEX_INVALID, // mutex hasn't been initialized |
32 | | wxMUTEX_DEAD_LOCK, // mutex is already locked by the calling thread |
33 | | wxMUTEX_BUSY, // mutex is already locked by another thread |
34 | | wxMUTEX_UNLOCKED, // attempt to unlock a mutex which is not locked |
35 | | wxMUTEX_TIMEOUT, // LockTimeout() has timed out |
36 | | wxMUTEX_MISC_ERROR // any other error |
37 | | }; |
38 | | |
39 | | enum wxCondError |
40 | | { |
41 | | wxCOND_NO_ERROR = 0, |
42 | | wxCOND_INVALID, |
43 | | wxCOND_TIMEOUT, // WaitTimeout() has timed out |
44 | | wxCOND_MISC_ERROR |
45 | | }; |
46 | | |
47 | | enum wxSemaError |
48 | | { |
49 | | wxSEMA_NO_ERROR = 0, |
50 | | wxSEMA_INVALID, // semaphore hasn't been initialized successfully |
51 | | wxSEMA_BUSY, // returned by TryWait() if Wait() would block |
52 | | wxSEMA_TIMEOUT, // returned by WaitTimeout() |
53 | | wxSEMA_OVERFLOW, // Post() would increase counter past the max |
54 | | wxSEMA_MISC_ERROR |
55 | | }; |
56 | | |
57 | | enum wxThreadError |
58 | | { |
59 | | wxTHREAD_NO_ERROR = 0, // No error |
60 | | wxTHREAD_NO_RESOURCE, // No resource left to create a new thread |
61 | | wxTHREAD_RUNNING, // The thread is already running |
62 | | wxTHREAD_NOT_RUNNING, // The thread isn't running |
63 | | wxTHREAD_KILLED, // Thread we waited for had to be killed |
64 | | wxTHREAD_MISC_ERROR // Some other error |
65 | | }; |
66 | | |
67 | | enum wxThreadKind |
68 | | { |
69 | | wxTHREAD_DETACHED, |
70 | | wxTHREAD_JOINABLE |
71 | | }; |
72 | | |
73 | | enum wxThreadWait |
74 | | { |
75 | | wxTHREAD_WAIT_BLOCK, |
76 | | wxTHREAD_WAIT_YIELD, // process events while waiting; MSW only |
77 | | wxTHREAD_WAIT_DEFAULT = wxTHREAD_WAIT_BLOCK |
78 | | }; |
79 | | |
80 | | // Obsolete synonyms for wxPRIORITY_XXX for backwards compatibility-only |
81 | | enum |
82 | | { |
83 | | WXTHREAD_MIN_PRIORITY = wxPRIORITY_MIN, |
84 | | WXTHREAD_DEFAULT_PRIORITY = wxPRIORITY_DEFAULT, |
85 | | WXTHREAD_MAX_PRIORITY = wxPRIORITY_MAX |
86 | | }; |
87 | | |
88 | | // There are 2 types of mutexes: normal mutexes and recursive ones. The attempt |
89 | | // to lock a normal mutex by a thread which already owns it results in |
90 | | // undefined behaviour (it always works under Windows, it will almost always |
91 | | // result in a deadlock under Unix). Locking a recursive mutex in such |
92 | | // situation always succeeds and it must be unlocked as many times as it has |
93 | | // been locked. |
94 | | // |
95 | | // However recursive mutexes have several important drawbacks: first, in the |
96 | | // POSIX implementation, they're less efficient. Second, and more importantly, |
97 | | // they CANNOT BE USED WITH CONDITION VARIABLES under Unix! Using them with |
98 | | // wxCondition will work under Windows and some Unices (notably Linux) but will |
99 | | // deadlock under other Unix versions (e.g. Solaris). As it might be difficult |
100 | | // to ensure that a recursive mutex is not used with wxCondition, it is a good |
101 | | // idea to avoid using recursive mutexes at all. Also, the last problem with |
102 | | // them is that some (older) Unix versions don't support this at all -- which |
103 | | // results in a configure warning when building and a deadlock when using them. |
104 | | enum wxMutexType |
105 | | { |
106 | | // normal mutex: try to always use this one |
107 | | wxMUTEX_DEFAULT, |
108 | | |
109 | | // recursive mutex: don't use these ones with wxCondition |
110 | | wxMUTEX_RECURSIVE |
111 | | }; |
112 | | |
113 | | // forward declarations |
114 | | class WXDLLIMPEXP_FWD_BASE wxThreadHelper; |
115 | | class WXDLLIMPEXP_FWD_BASE wxConditionInternal; |
116 | | class WXDLLIMPEXP_FWD_BASE wxMutexInternal; |
117 | | class WXDLLIMPEXP_FWD_BASE wxSemaphoreInternal; |
118 | | class WXDLLIMPEXP_FWD_BASE wxThreadInternal; |
119 | | |
120 | | // ---------------------------------------------------------------------------- |
121 | | // A mutex object is a synchronization object whose state is set to signaled |
122 | | // when it is not owned by any thread, and nonsignaled when it is owned. Its |
123 | | // name comes from its usefulness in coordinating mutually-exclusive access to |
124 | | // a shared resource. Only one thread at a time can own a mutex object. |
125 | | // ---------------------------------------------------------------------------- |
126 | | |
127 | | // you should consider wxMutexLocker whenever possible instead of directly |
128 | | // working with wxMutex class - it is safer |
129 | | class WXDLLIMPEXP_BASE wxMutex |
130 | | { |
131 | | public: |
132 | | // constructor & destructor |
133 | | // ------------------------ |
134 | | |
135 | | // create either default (always safe) or recursive mutex |
136 | | wxMutex(wxMutexType mutexType = wxMUTEX_DEFAULT); |
137 | | |
138 | | // destroys the mutex kernel object |
139 | | ~wxMutex(); |
140 | | |
141 | | // test if the mutex has been created successfully |
142 | | bool IsOk() const; |
143 | | |
144 | | // mutex operations |
145 | | // ---------------- |
146 | | |
147 | | // Lock the mutex, blocking on it until it is unlocked by the other thread. |
148 | | // The result of locking a mutex already locked by the current thread |
149 | | // depend on the mutex type. |
150 | | // |
151 | | // The caller must call Unlock() later if Lock() returned wxMUTEX_NO_ERROR. |
152 | | wxMutexError Lock(); |
153 | | |
154 | | // Same as Lock() but return wxMUTEX_TIMEOUT if the mutex can't be locked |
155 | | // during the given number of milliseconds |
156 | | wxMutexError LockTimeout(unsigned long ms); |
157 | | |
158 | | // Try to lock the mutex: if it is currently locked, return immediately |
159 | | // with an error. Otherwise the caller must call Unlock(). |
160 | | wxMutexError TryLock(); |
161 | | |
162 | | // Unlock the mutex. It is an error to unlock an already unlocked mutex |
163 | | wxMutexError Unlock(); |
164 | | |
165 | | protected: |
166 | | wxMutexInternal *m_internal; |
167 | | |
168 | | friend class wxConditionInternal; |
169 | | |
170 | | wxDECLARE_NO_COPY_CLASS(wxMutex); |
171 | | }; |
172 | | |
173 | | // a helper class which locks the mutex in the ctor and unlocks it in the dtor: |
174 | | // this ensures that mutex is always unlocked, even if the function returns or |
175 | | // throws an exception before it reaches the end |
176 | | class WXDLLIMPEXP_BASE wxMutexLocker |
177 | | { |
178 | | public: |
179 | | // lock the mutex in the ctor |
180 | | wxMutexLocker(wxMutex& mutex) |
181 | 0 | : m_isOk(false), m_mutex(mutex) |
182 | 0 | { m_isOk = ( m_mutex.Lock() == wxMUTEX_NO_ERROR ); } |
183 | | |
184 | | // returns true if mutex was successfully locked in ctor |
185 | | bool IsOk() const |
186 | 0 | { return m_isOk; } |
187 | | |
188 | | // unlock the mutex in dtor |
189 | | ~wxMutexLocker() |
190 | 0 | { if ( IsOk() ) m_mutex.Unlock(); } |
191 | | |
192 | | private: |
193 | | // no assignment operator nor copy ctor |
194 | | wxMutexLocker(const wxMutexLocker&); |
195 | | wxMutexLocker& operator=(const wxMutexLocker&); |
196 | | |
197 | | bool m_isOk; |
198 | | wxMutex& m_mutex; |
199 | | }; |
200 | | |
201 | | // ---------------------------------------------------------------------------- |
202 | | // Critical section: this is the same as mutex but is only visible to the |
203 | | // threads of the same process. For the platforms which don't have native |
204 | | // support for critical sections, they're implemented entirely in terms of |
205 | | // mutexes. |
206 | | // |
207 | | // NB: wxCriticalSection object does not allocate any memory in its ctor |
208 | | // which makes it possible to have static globals of this class |
209 | | // ---------------------------------------------------------------------------- |
210 | | |
211 | | // in order to avoid any overhead under platforms where critical sections are |
212 | | // just mutexes make all wxCriticalSection class functions inline |
213 | | #if !defined(__WINDOWS__) |
214 | | #define wxCRITSECT_IS_MUTEX 1 |
215 | | |
216 | | #define wxCRITSECT_INLINE WXEXPORT inline |
217 | | #else // MSW |
218 | | #define wxCRITSECT_IS_MUTEX 0 |
219 | | |
220 | | #define wxCRITSECT_INLINE |
221 | | #endif // MSW/!MSW |
222 | | |
223 | | enum wxCriticalSectionType |
224 | | { |
225 | | // recursive critical section |
226 | | wxCRITSEC_DEFAULT, |
227 | | |
228 | | // non-recursive critical section |
229 | | wxCRITSEC_NON_RECURSIVE |
230 | | }; |
231 | | |
232 | | // you should consider wxCriticalSectionLocker whenever possible instead of |
233 | | // directly working with wxCriticalSection class - it is safer |
234 | | class WXDLLIMPEXP_BASE wxCriticalSection |
235 | | { |
236 | | public: |
237 | | // ctor & dtor |
238 | | wxCRITSECT_INLINE wxCriticalSection( wxCriticalSectionType critSecType = wxCRITSEC_DEFAULT ); |
239 | | wxCRITSECT_INLINE ~wxCriticalSection(); |
240 | | // enter the section (the same as locking a mutex) |
241 | | wxCRITSECT_INLINE void Enter(); |
242 | | |
243 | | // try to enter the section (the same as trying to lock a mutex) |
244 | | wxCRITSECT_INLINE bool TryEnter(); |
245 | | |
246 | | // leave the critical section (same as unlocking a mutex) |
247 | | wxCRITSECT_INLINE void Leave(); |
248 | | |
249 | | private: |
250 | | #if wxCRITSECT_IS_MUTEX |
251 | | wxMutex m_mutex; |
252 | | #elif defined(__WINDOWS__) |
253 | | // we can't allocate any memory in the ctor, so use placement new - |
254 | | // unfortunately, we have to hardcode the sizeof() here because we can't |
255 | | // include windows.h from this public header and we also have to use the |
256 | | // union to force the correct (i.e. maximal) alignment |
257 | | // |
258 | | // if CRITICAL_SECTION size changes in Windows, you'll get an assert from |
259 | | // thread.cpp and will need to increase the buffer size |
260 | | #ifdef __WIN64__ |
261 | | typedef char wxCritSectBuffer[40]; |
262 | | #else // __WIN32__ |
263 | | typedef char wxCritSectBuffer[24]; |
264 | | #endif |
265 | | union |
266 | | { |
267 | | unsigned long m_dummy1; |
268 | | void *m_dummy2; |
269 | | |
270 | | wxCritSectBuffer m_buffer; |
271 | | }; |
272 | | #endif // Unix/Win32 |
273 | | |
274 | | wxDECLARE_NO_COPY_CLASS(wxCriticalSection); |
275 | | }; |
276 | | |
277 | | #if wxCRITSECT_IS_MUTEX |
278 | | // implement wxCriticalSection using mutexes |
279 | | inline wxCriticalSection::wxCriticalSection( wxCriticalSectionType critSecType ) |
280 | 8 | : m_mutex( critSecType == wxCRITSEC_DEFAULT ? wxMUTEX_RECURSIVE : wxMUTEX_DEFAULT ) { } |
281 | 0 | inline wxCriticalSection::~wxCriticalSection() { } |
282 | | |
283 | 8 | inline void wxCriticalSection::Enter() { (void)m_mutex.Lock(); } |
284 | 0 | inline bool wxCriticalSection::TryEnter() { return m_mutex.TryLock() == wxMUTEX_NO_ERROR; } |
285 | 8 | inline void wxCriticalSection::Leave() { (void)m_mutex.Unlock(); } |
286 | | #endif // wxCRITSECT_IS_MUTEX |
287 | | |
288 | | #undef wxCRITSECT_INLINE |
289 | | #undef wxCRITSECT_IS_MUTEX |
290 | | |
291 | | // wxCriticalSectionLocker is the same to critical sections as wxMutexLocker is |
292 | | // to mutexes |
293 | | class WXDLLIMPEXP_BASE wxCriticalSectionLocker |
294 | | { |
295 | | public: |
296 | | wxCriticalSectionLocker(wxCriticalSection& cs) |
297 | 8 | : m_critsect(cs) |
298 | 8 | { |
299 | 8 | m_critsect.Enter(); |
300 | 8 | } |
301 | | |
302 | | ~wxCriticalSectionLocker() |
303 | 8 | { |
304 | 8 | m_critsect.Leave(); |
305 | 8 | } |
306 | | |
307 | | private: |
308 | | wxCriticalSection& m_critsect; |
309 | | |
310 | | wxDECLARE_NO_COPY_CLASS(wxCriticalSectionLocker); |
311 | | }; |
312 | | |
313 | | // ---------------------------------------------------------------------------- |
314 | | // wxCondition models a POSIX condition variable which allows one (or more) |
315 | | // thread(s) to wait until some condition is fulfilled |
316 | | // ---------------------------------------------------------------------------- |
317 | | |
318 | | class WXDLLIMPEXP_BASE wxCondition |
319 | | { |
320 | | public: |
321 | | // Each wxCondition object is associated with a (single) wxMutex object. |
322 | | // The mutex object MUST be locked before calling Wait() |
323 | | wxCondition(wxMutex& mutex); |
324 | | |
325 | | // dtor is not virtual, don't use this class polymorphically |
326 | | ~wxCondition(); |
327 | | |
328 | | // return true if the condition has been created successfully |
329 | | bool IsOk() const; |
330 | | |
331 | | // NB: the associated mutex MUST be locked beforehand by the calling thread |
332 | | // |
333 | | // it atomically releases the lock on the associated mutex |
334 | | // and starts waiting to be woken up by a Signal()/Broadcast() |
335 | | // once its signaled, then it will wait until it can reacquire |
336 | | // the lock on the associated mutex object, before returning. |
337 | | wxCondError Wait(); |
338 | | |
339 | | // std::condition_variable-like variant that evaluates the associated condition |
340 | | template<typename Functor> |
341 | | wxCondError Wait(const Functor& predicate) |
342 | | { |
343 | | while ( !predicate() ) |
344 | | { |
345 | | wxCondError e = Wait(); |
346 | | if ( e != wxCOND_NO_ERROR ) |
347 | | return e; |
348 | | } |
349 | | return wxCOND_NO_ERROR; |
350 | | } |
351 | | |
352 | | // exactly as Wait() except that it may also return if the specified |
353 | | // timeout elapses even if the condition hasn't been signalled: in this |
354 | | // case, the return value is wxCOND_TIMEOUT, otherwise (i.e. in case of a |
355 | | // normal return) it is wxCOND_NO_ERROR. |
356 | | // |
357 | | // the timeout parameter specifies an interval that needs to be waited for |
358 | | // in milliseconds |
359 | | wxCondError WaitTimeout(unsigned long milliseconds); |
360 | | |
361 | | // NB: the associated mutex may or may not be locked by the calling thread |
362 | | // |
363 | | // this method unblocks one thread if any are blocking on the condition. |
364 | | // if no thread is blocking in Wait(), then the signal is NOT remembered |
365 | | // The thread which was blocking on Wait() will then reacquire the lock |
366 | | // on the associated mutex object before returning |
367 | | wxCondError Signal(); |
368 | | |
369 | | // NB: the associated mutex may or may not be locked by the calling thread |
370 | | // |
371 | | // this method unblocks all threads if any are blocking on the condition. |
372 | | // if no thread is blocking in Wait(), then the signal is NOT remembered |
373 | | // The threads which were blocking on Wait() will then reacquire the lock |
374 | | // on the associated mutex object before returning. |
375 | | wxCondError Broadcast(); |
376 | | |
377 | | private: |
378 | | wxConditionInternal *m_internal; |
379 | | |
380 | | wxDECLARE_NO_COPY_CLASS(wxCondition); |
381 | | }; |
382 | | |
383 | | // ---------------------------------------------------------------------------- |
384 | | // wxSemaphore: a counter limiting the number of threads concurrently accessing |
385 | | // a shared resource |
386 | | // ---------------------------------------------------------------------------- |
387 | | |
388 | | class WXDLLIMPEXP_BASE wxSemaphore |
389 | | { |
390 | | public: |
391 | | // specifying a maxcount of 0 actually makes wxSemaphore behave as if there |
392 | | // is no upper limit, if maxcount is 1 the semaphore behaves as a mutex |
393 | | wxSemaphore( int initialcount = 0, int maxcount = 0 ); |
394 | | |
395 | | // dtor is not virtual, don't use this class polymorphically |
396 | | ~wxSemaphore(); |
397 | | |
398 | | // return true if the semaphore has been created successfully |
399 | | bool IsOk() const; |
400 | | |
401 | | // wait indefinitely, until the semaphore count goes beyond 0 |
402 | | // and then decrement it and return (this method might have been called |
403 | | // Acquire()) |
404 | | wxSemaError Wait(); |
405 | | |
406 | | // same as Wait(), but does not block, returns wxSEMA_NO_ERROR if |
407 | | // successful and wxSEMA_BUSY if the count is currently zero |
408 | | wxSemaError TryWait(); |
409 | | |
410 | | // same as Wait(), but as a timeout limit, returns wxSEMA_NO_ERROR if the |
411 | | // semaphore was acquired and wxSEMA_TIMEOUT if the timeout has elapsed |
412 | | wxSemaError WaitTimeout(unsigned long milliseconds); |
413 | | |
414 | | // increments the semaphore count and signals one of the waiting threads |
415 | | wxSemaError Post(); |
416 | | |
417 | | private: |
418 | | wxSemaphoreInternal *m_internal; |
419 | | |
420 | | wxDECLARE_NO_COPY_CLASS(wxSemaphore); |
421 | | }; |
422 | | |
423 | | // ---------------------------------------------------------------------------- |
424 | | // wxThread: class encapsulating a thread of execution |
425 | | // ---------------------------------------------------------------------------- |
426 | | |
427 | | // there are two different kinds of threads: joinable and detached (default) |
428 | | // ones. Only joinable threads can return a return code and only detached |
429 | | // threads auto-delete themselves - the user should delete the joinable |
430 | | // threads manually. |
431 | | |
432 | | // NB: in the function descriptions the words "this thread" mean the thread |
433 | | // created by the wxThread object while "main thread" is the thread created |
434 | | // during the process initialization (a.k.a. the GUI thread) |
435 | | |
436 | | // On VMS thread pointers are 64 bits (also needed for other systems??? |
437 | | #ifdef __VMS |
438 | | typedef unsigned long long wxThreadIdType; |
439 | | #else |
440 | | typedef unsigned long wxThreadIdType; |
441 | | #endif |
442 | | |
443 | | class WXDLLIMPEXP_BASE wxThread |
444 | | { |
445 | | public: |
446 | | // the return type for the thread function |
447 | | typedef void *ExitCode; |
448 | | |
449 | | // static functions |
450 | | // Returns the wxThread object for the calling thread. nullptr is returned |
451 | | // if the caller is the main thread (but it's recommended to use |
452 | | // IsMain() and only call This() for threads other than the main one |
453 | | // because nullptr is also returned on error). If the thread wasn't |
454 | | // created with wxThread class, the returned value is undefined. |
455 | | static wxThread *This(); |
456 | | |
457 | | // Returns true if current thread is the main thread. |
458 | | // |
459 | | // Notice that it also returns true if main thread id hadn't been |
460 | | // initialized yet on the assumption that it's too early in wx startup |
461 | | // process for any other threads to have been created in this case. |
462 | | static bool IsMain() |
463 | 84.3k | { |
464 | 84.3k | return !ms_idMainThread || GetCurrentId() == ms_idMainThread; |
465 | 84.3k | } |
466 | | |
467 | | // Return the main thread id |
468 | 0 | static wxThreadIdType GetMainId() { return ms_idMainThread; } |
469 | | |
470 | | // Release the rest of our time slice letting the other threads run |
471 | | static void Yield(); |
472 | | |
473 | | // Sleep during the specified period of time in milliseconds |
474 | | // |
475 | | // This is the same as wxMilliSleep(). |
476 | | static void Sleep(unsigned long milliseconds); |
477 | | |
478 | | // get the number of system CPUs - useful with SetConcurrency() |
479 | | // (the "best" value for it is usually number of CPUs + 1) |
480 | | // |
481 | | // Returns -1 if unknown, number of CPUs otherwise |
482 | | static int GetCPUCount(); |
483 | | |
484 | | // Get the platform specific thread ID and return as a long. This |
485 | | // can be used to uniquely identify threads, even if they are not |
486 | | // wxThreads. This is used by wxPython. |
487 | | static wxThreadIdType GetCurrentId(); |
488 | | |
489 | | // sets the concurrency level: this is, roughly, the number of threads |
490 | | // the system tries to schedule to run in parallel. 0 means the |
491 | | // default value (usually acceptable, but may not yield the best |
492 | | // performance for this process) |
493 | | // |
494 | | // Returns true on success, false otherwise (if not implemented, for |
495 | | // example) |
496 | | static bool SetConcurrency(size_t level); |
497 | | |
498 | | // constructor only creates the C++ thread object and doesn't create (or |
499 | | // start) the real thread |
500 | | wxThread(wxThreadKind kind = wxTHREAD_DETACHED); |
501 | | |
502 | | // functions that change the thread state: all these can only be called |
503 | | // from _another_ thread (typically the thread that created this one, e.g. |
504 | | // the main thread), not from the thread itself |
505 | | |
506 | | // create a new thread and optionally set the stack size on |
507 | | // platforms that support that - call Run() to start it |
508 | | wxThreadError Create(unsigned int stackSize = 0); |
509 | | |
510 | | // starts execution of the thread - from the moment Run() is called |
511 | | // the execution of wxThread::Entry() may start at any moment, caller |
512 | | // shouldn't suppose that it starts after (or before) Run() returns. |
513 | | wxThreadError Run(); |
514 | | |
515 | | // stops the thread if it's running and deletes the wxThread object if |
516 | | // this is a detached thread freeing its memory - otherwise (for |
517 | | // joinable threads) you still need to delete wxThread object |
518 | | // yourself. |
519 | | // |
520 | | // this function only works if the thread calls TestDestroy() |
521 | | // periodically - the thread will only be deleted the next time it |
522 | | // does it! |
523 | | // |
524 | | // will fill the rc pointer with the thread exit code if it's non-null |
525 | | wxThreadError Delete(ExitCode *rc = nullptr, |
526 | | wxThreadWait waitMode = wxTHREAD_WAIT_DEFAULT); |
527 | | |
528 | | // waits for a joinable thread to finish and returns its exit code |
529 | | // |
530 | | // Returns (ExitCode)-1 on error (for example, if the thread is not |
531 | | // joinable) |
532 | | ExitCode Wait(wxThreadWait waitMode = wxTHREAD_WAIT_DEFAULT); |
533 | | |
534 | | // kills the thread without giving it any chance to clean up - should |
535 | | // not be used under normal circumstances, use Delete() instead. |
536 | | // It is a dangerous function that should only be used in the most |
537 | | // extreme cases! |
538 | | // |
539 | | // The wxThread object is deleted by Kill() if the thread is |
540 | | // detachable, but you still have to delete it manually for joinable |
541 | | // threads. |
542 | | wxThreadError Kill(); |
543 | | |
544 | | // pause a running thread: as Delete(), this only works if the thread |
545 | | // calls TestDestroy() regularly |
546 | | wxThreadError Pause(); |
547 | | |
548 | | // resume a paused thread |
549 | | wxThreadError Resume(); |
550 | | |
551 | | // priority |
552 | | // Sets the priority to "prio" which must be in 0..100 range (see |
553 | | // also wxPRIORITY_XXX constants). |
554 | | void SetPriority(unsigned int prio); |
555 | | |
556 | | // Get the current priority. |
557 | | unsigned int GetPriority() const; |
558 | | |
559 | | // thread status inquiries |
560 | | // Returns true if the thread is alive: i.e. running or suspended |
561 | | bool IsAlive() const; |
562 | | // Returns true if the thread is running (not paused, not killed). |
563 | | bool IsRunning() const; |
564 | | // Returns true if the thread is suspended |
565 | | bool IsPaused() const; |
566 | | |
567 | | // is the thread of detached kind? |
568 | 0 | bool IsDetached() const { return m_isDetached; } |
569 | | |
570 | | // Get the thread ID - a platform dependent number which uniquely |
571 | | // identifies a thread inside a process |
572 | | wxThreadIdType GetId() const; |
573 | | |
574 | | #ifdef __WINDOWS__ |
575 | | // Get the internal OS handle |
576 | | WXHANDLE MSWGetHandle() const; |
577 | | #endif // __WINDOWS__ |
578 | | |
579 | | wxThreadKind GetKind() const |
580 | 0 | { return m_isDetached ? wxTHREAD_DETACHED : wxTHREAD_JOINABLE; } |
581 | | |
582 | | // Returns true if the thread was asked to terminate: this function should |
583 | | // be called by the thread from time to time, otherwise the main thread |
584 | | // will be left forever in Delete()! |
585 | | virtual bool TestDestroy(); |
586 | | |
587 | | // dtor is public, but the detached threads should never be deleted - use |
588 | | // Delete() instead (or leave the thread terminate by itself) |
589 | | virtual ~wxThread(); |
590 | | |
591 | | // sets name to assist debugging |
592 | | static bool SetNameForCurrent(const wxString &name); |
593 | | |
594 | | protected: |
595 | | // sets name to assist debugging |
596 | | bool SetName(const wxString &name); |
597 | | |
598 | | // exits from the current thread - can be called only from this thread |
599 | | void Exit(ExitCode exitcode = nullptr); |
600 | | |
601 | | // entry point for the thread - called by Run() and executes in the context |
602 | | // of this thread. |
603 | | virtual void *Entry() = 0; |
604 | | |
605 | | // Callbacks which may be overridden by the derived class to perform some |
606 | | // specific actions when the thread is deleted or killed. By default they |
607 | | // do nothing. |
608 | | |
609 | | // This one is called by Delete() before actually deleting the thread and |
610 | | // is executed in the context of the thread that called Delete(). |
611 | 0 | virtual void OnDelete() {} |
612 | | |
613 | | // This one is called by Kill() before killing the thread and is executed |
614 | | // in the context of the thread that called Kill(). |
615 | 0 | virtual void OnKill() {} |
616 | | |
617 | | // called when the thread exits - in the context of this thread |
618 | | // |
619 | | // NB: this function will not be called if the thread is Kill()ed |
620 | 0 | virtual void OnExit() {} |
621 | | |
622 | | private: |
623 | | // no copy ctor/assignment operator |
624 | | wxThread(const wxThread&); |
625 | | wxThread& operator=(const wxThread&); |
626 | | |
627 | | friend class wxThreadInternal; |
628 | | friend class wxThreadModule; |
629 | | |
630 | | |
631 | | // the main thread identifier, should be set on startup |
632 | | static wxThreadIdType ms_idMainThread; |
633 | | |
634 | | // the (platform-dependent) thread class implementation |
635 | | wxThreadInternal *m_internal; |
636 | | |
637 | | // protects access to any methods of wxThreadInternal object |
638 | | mutable wxCriticalSection m_critsect; |
639 | | |
640 | | // true if the thread is detached, false if it is joinable |
641 | | bool m_isDetached; |
642 | | }; |
643 | | |
644 | | // wxThreadHelperThread class |
645 | | // -------------------------- |
646 | | |
647 | | class wxThreadHelperThread : public wxThread |
648 | | { |
649 | | public: |
650 | | // constructor only creates the C++ thread object and doesn't create (or |
651 | | // start) the real thread |
652 | | wxThreadHelperThread(wxThreadHelper& owner, wxThreadKind kind) |
653 | | : wxThread(kind), m_owner(owner) |
654 | 0 | { } |
655 | | |
656 | | protected: |
657 | | // entry point for the thread -- calls Entry() in owner. |
658 | | virtual void *Entry() override; |
659 | | |
660 | | private: |
661 | | // the owner of the thread |
662 | | wxThreadHelper& m_owner; |
663 | | |
664 | | // no copy ctor/assignment operator |
665 | | wxThreadHelperThread(const wxThreadHelperThread&); |
666 | | wxThreadHelperThread& operator=(const wxThreadHelperThread&); |
667 | | }; |
668 | | |
669 | | // ---------------------------------------------------------------------------- |
670 | | // wxThreadHelper: this class implements the threading logic to run a |
671 | | // background task in another object (such as a window). It is a mix-in: just |
672 | | // derive from it to implement a threading background task in your class. |
673 | | // ---------------------------------------------------------------------------- |
674 | | |
675 | | class wxThreadHelper |
676 | | { |
677 | | private: |
678 | | void KillThread() |
679 | 0 | { |
680 | 0 | // If wxThreadHelperThread is detached and is about to finish, it will |
681 | 0 | // set m_thread to nullptr so don't delete it then. |
682 | 0 | // But if KillThread is called before wxThreadHelperThread (in detached mode) |
683 | 0 | // sets it to nullptr, then the thread object still exists and can be killed |
684 | 0 | wxCriticalSectionLocker locker(m_critSection); |
685 | 0 |
|
686 | 0 | if ( m_thread ) |
687 | 0 | { |
688 | 0 | m_thread->Kill(); |
689 | 0 |
|
690 | 0 | if ( m_kind == wxTHREAD_JOINABLE ) |
691 | 0 | delete m_thread; |
692 | 0 |
|
693 | 0 | m_thread = nullptr; |
694 | 0 | } |
695 | 0 | } |
696 | | |
697 | | public: |
698 | | // constructor only initializes m_thread to nullptr |
699 | | wxThreadHelper(wxThreadKind kind = wxTHREAD_JOINABLE) |
700 | 0 | : m_thread(nullptr), m_kind(kind) { } |
701 | | |
702 | | // destructor deletes m_thread |
703 | 0 | virtual ~wxThreadHelper() { KillThread(); } |
704 | | |
705 | | // create a new thread (and optionally set the stack size on platforms that |
706 | | // support/need that), call Run() to start it |
707 | | wxThreadError CreateThread(wxThreadKind kind = wxTHREAD_JOINABLE, |
708 | | unsigned int stackSize = 0) |
709 | 0 | { |
710 | 0 | KillThread(); |
711 | 0 |
|
712 | 0 | m_kind = kind; |
713 | 0 | m_thread = new wxThreadHelperThread(*this, m_kind); |
714 | 0 |
|
715 | 0 | return m_thread->Create(stackSize); |
716 | 0 | } |
717 | | |
718 | | // entry point for the thread - called by Run() and executes in the context |
719 | | // of this thread. |
720 | | virtual void *Entry() = 0; |
721 | | |
722 | | // returns a pointer to the thread which can be used to call Run() |
723 | | wxThread *GetThread() const |
724 | 0 | { |
725 | 0 | wxCriticalSectionLocker locker(m_critSection); |
726 | 0 |
|
727 | 0 | wxThread* thread = m_thread; |
728 | 0 |
|
729 | 0 | return thread; |
730 | 0 | } |
731 | | |
732 | | protected: |
733 | | wxThread *m_thread; |
734 | | wxThreadKind m_kind; |
735 | | mutable wxCriticalSection m_critSection; // To guard the m_thread variable |
736 | | |
737 | | friend class wxThreadHelperThread; |
738 | | }; |
739 | | |
740 | | // call Entry() in owner, put it down here to avoid circular declarations |
741 | | inline void *wxThreadHelperThread::Entry() |
742 | 0 | { |
743 | 0 | void * const result = m_owner.Entry(); |
744 | |
|
745 | 0 | wxCriticalSectionLocker locker(m_owner.m_critSection); |
746 | | |
747 | | // Detached thread will be deleted after returning, so make sure |
748 | | // wxThreadHelper::GetThread will not return an invalid pointer. |
749 | | // And that wxThreadHelper::KillThread will not try to kill |
750 | | // an already deleted thread |
751 | 0 | if ( m_owner.m_kind == wxTHREAD_DETACHED ) |
752 | 0 | m_owner.m_thread = nullptr; |
753 | |
|
754 | 0 | return result; |
755 | 0 | } |
756 | | |
757 | | // ---------------------------------------------------------------------------- |
758 | | // Automatic initialization |
759 | | // ---------------------------------------------------------------------------- |
760 | | |
761 | | // GUI mutex handling. |
762 | | void WXDLLIMPEXP_BASE wxMutexGuiEnter(); |
763 | | void WXDLLIMPEXP_BASE wxMutexGuiLeave(); |
764 | | |
765 | | // macros for entering/leaving critical sections which may be used without |
766 | | // having to take them inside "#if wxUSE_THREADS" |
767 | 0 | #define wxENTER_CRIT_SECT(cs) (cs).Enter() |
768 | 0 | #define wxLEAVE_CRIT_SECT(cs) (cs).Leave() |
769 | | #define wxCRIT_SECT_DECLARE(cs) static wxCriticalSection cs |
770 | | #define wxCRIT_SECT_DECLARE_MEMBER(cs) wxCriticalSection cs |
771 | 8 | #define wxCRIT_SECT_LOCKER(name, cs) wxCriticalSectionLocker name(cs) |
772 | | |
773 | | // function for checking if we're in the main thread which may be used whether |
774 | | // wxUSE_THREADS is 0 or 1 |
775 | 0 | inline bool wxIsMainThread() { return wxThread::IsMain(); } |
776 | | |
777 | | #else // !wxUSE_THREADS |
778 | | |
779 | | // no thread support |
780 | | inline void wxMutexGuiEnter() { } |
781 | | inline void wxMutexGuiLeave() { } |
782 | | |
783 | | // macros for entering/leaving critical sections which may be used without |
784 | | // having to take them inside "#if wxUSE_THREADS" |
785 | | // (the implementation uses dummy structs to force semicolon after the macro) |
786 | | #define wxENTER_CRIT_SECT(cs) do {} while (0) |
787 | | #define wxLEAVE_CRIT_SECT(cs) do {} while (0) |
788 | | #define wxCRIT_SECT_DECLARE(cs) struct wxDummyCS##cs |
789 | | #define wxCRIT_SECT_DECLARE_MEMBER(cs) struct wxDummyCSMember##cs { } |
790 | | #define wxCRIT_SECT_LOCKER(name, cs) struct wxDummyCSLocker##name |
791 | | |
792 | | // if there is only one thread, it is always the main one |
793 | | inline bool wxIsMainThread() { return true; } |
794 | | |
795 | | #endif // wxUSE_THREADS/!wxUSE_THREADS |
796 | | |
797 | | // mark part of code as being a critical section: this macro declares a |
798 | | // critical section with the given name and enters it immediately and leaves |
799 | | // it at the end of the current scope |
800 | | // |
801 | | // example: |
802 | | // |
803 | | // int Count() |
804 | | // { |
805 | | // static int s_counter = 0; |
806 | | // |
807 | | // wxCRITICAL_SECTION(counter); |
808 | | // |
809 | | // return ++s_counter; |
810 | | // } |
811 | | // |
812 | | // this function is MT-safe in presence of the threads but there is no |
813 | | // overhead when the library is compiled without threads |
814 | | #define wxCRITICAL_SECTION(name) \ |
815 | | wxCRIT_SECT_DECLARE(s_cs##name); \ |
816 | | wxCRIT_SECT_LOCKER(cs##name##Locker, s_cs##name) |
817 | | |
818 | | // automatically lock GUI mutex in ctor and unlock it in dtor |
819 | | class WXDLLIMPEXP_BASE wxMutexGuiLocker |
820 | | { |
821 | | public: |
822 | 0 | wxMutexGuiLocker() { wxMutexGuiEnter(); } |
823 | 0 | ~wxMutexGuiLocker() { wxMutexGuiLeave(); } |
824 | | }; |
825 | | |
826 | | // ----------------------------------------------------------------------------- |
827 | | // implementation only until the end of file |
828 | | // ----------------------------------------------------------------------------- |
829 | | |
830 | | #if wxUSE_THREADS |
831 | | |
832 | | #if defined(__WINDOWS__) || defined(__DARWIN__) |
833 | | // unlock GUI if there are threads waiting for and lock it back when |
834 | | // there are no more of them - should be called periodically by the main |
835 | | // thread |
836 | | extern void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter(); |
837 | | |
838 | | // returns true if the main thread has GUI lock |
839 | | extern bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread(); |
840 | | |
841 | | // wakes up the main thread if it's sleeping inside ::GetMessage() |
842 | | extern void WXDLLIMPEXP_BASE wxWakeUpMainThread(); |
843 | | |
844 | | #ifndef __DARWIN__ |
845 | | // return true if the main thread is waiting for some other to terminate: |
846 | | // wxApp then should block all "dangerous" messages |
847 | | extern bool WXDLLIMPEXP_BASE wxIsWaitingForThread(); |
848 | | #endif |
849 | | #endif // MSW, OSX |
850 | | |
851 | | #endif // wxUSE_THREADS |
852 | | |
853 | | #endif // _WX_THREAD_H_ |