]>
Commit | Line | Data |
---|---|---|
518b5d2f | 1 | ///////////////////////////////////////////////////////////////////////////// |
ad9835c9 | 2 | // Name: src/unix/threadpsx.cpp |
518b5d2f VZ |
3 | // Purpose: wxThread (Posix) Implementation |
4 | // Author: Original from Wolfram Gloger/Guilhem Lavaux | |
be809868 | 5 | // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore |
518b5d2f VZ |
6 | // Created: 04/22/98 |
7 | // RCS-ID: $Id$ | |
8 | // Copyright: (c) Wolfram Gloger (1996, 1997) | |
9 | // Guilhem Lavaux (1998) | |
8d5eff60 | 10 | // Vadim Zeitlin (1999-2002) |
518b5d2f | 11 | // Robert Roebling (1999) |
be809868 | 12 | // K. S. Sreeram (2002) |
65571936 | 13 | // Licence: wxWindows licence |
518b5d2f VZ |
14 | ///////////////////////////////////////////////////////////////////////////// |
15 | ||
16 | // ============================================================================ | |
17 | // declaration | |
18 | // ============================================================================ | |
19 | ||
20 | // ---------------------------------------------------------------------------- | |
21 | // headers | |
22 | // ---------------------------------------------------------------------------- | |
23 | ||
14f355c2 VS |
24 | // for compilers that support precompilation, includes "wx.h". |
25 | #include "wx/wxprec.h" | |
518b5d2f | 26 | |
7bcb11d3 | 27 | #if wxUSE_THREADS |
518b5d2f | 28 | |
88a7a4e1 | 29 | #include "wx/thread.h" |
79b7b95a | 30 | #include "wx/except.h" |
88a7a4e1 | 31 | |
ad9835c9 | 32 | #ifndef WX_PRECOMP |
79b7b95a | 33 | #include "wx/app.h" |
ad9835c9 | 34 | #include "wx/dynarray.h" |
88a7a4e1 | 35 | #include "wx/intl.h" |
e4db172a | 36 | #include "wx/log.h" |
de6185e2 | 37 | #include "wx/utils.h" |
c0badb70 | 38 | #include "wx/timer.h" |
bb90a3e6 | 39 | #include "wx/stopwatch.h" |
02761f6c | 40 | #include "wx/module.h" |
ad9835c9 WS |
41 | #endif |
42 | ||
518b5d2f VZ |
43 | #include <stdio.h> |
44 | #include <unistd.h> | |
45 | #include <pthread.h> | |
46 | #include <errno.h> | |
47 | #include <time.h> | |
feedacd8 | 48 | #include <sys/time.h> // needed for at least __QNX__ |
4f66d445 | 49 | #ifdef HAVE_SCHED_H |
518b5d2f VZ |
50 | #include <sched.h> |
51 | #endif | |
52 | ||
ef8d96c2 VZ |
53 | #ifdef HAVE_THR_SETCONCURRENCY |
54 | #include <thread.h> | |
55 | #endif | |
56 | ||
57 | // we use wxFFile under Linux in GetCPUCount() | |
58 | #ifdef __LINUX__ | |
59 | #include "wx/ffile.h" | |
feedacd8 | 60 | #include <sys/resource.h> // for setpriority() |
ef8d96c2 VZ |
61 | #endif |
62 | ||
35e9c131 VS |
63 | #define THR_ID_CAST(id) (reinterpret_cast<void*>(id)) |
64 | #define THR_ID(thr) THR_ID_CAST((thr)->GetId()) | |
ef4f69ec | 65 | |
518b5d2f VZ |
66 | // ---------------------------------------------------------------------------- |
67 | // constants | |
68 | // ---------------------------------------------------------------------------- | |
69 | ||
882eefb1 VZ |
70 | // the possible states of the thread and transitions from them |
71 | enum wxThreadState | |
518b5d2f VZ |
72 | { |
73 | STATE_NEW, // didn't start execution yet (=> RUNNING) | |
882eefb1 VZ |
74 | STATE_RUNNING, // running (=> PAUSED or EXITED) |
75 | STATE_PAUSED, // suspended (=> RUNNING or EXITED) | |
76 | STATE_EXITED // thread doesn't exist any more | |
518b5d2f VZ |
77 | }; |
78 | ||
9fc3ad34 VZ |
79 | // the exit value of a thread which has been cancelled |
80 | static const wxThread::ExitCode EXITCODE_CANCELLED = (wxThread::ExitCode)-1; | |
81 | ||
9e84b847 | 82 | // trace mask for wxThread operations |
9a83f860 | 83 | #define TRACE_THREADS wxT("thread") |
9fc3ad34 | 84 | |
9e84b847 | 85 | // you can get additional debugging messages for the semaphore operations |
9a83f860 | 86 | #define TRACE_SEMA wxT("semaphore") |
9e84b847 | 87 | |
9fc3ad34 VZ |
88 | // ---------------------------------------------------------------------------- |
89 | // private functions | |
90 | // ---------------------------------------------------------------------------- | |
91 | ||
92 | static void ScheduleThreadForDeletion(); | |
93 | static void DeleteThread(wxThread *This); | |
94 | ||
882eefb1 | 95 | // ---------------------------------------------------------------------------- |
9e84b847 | 96 | // private classes |
882eefb1 VZ |
97 | // ---------------------------------------------------------------------------- |
98 | ||
9e84b847 | 99 | // an (non owning) array of pointers to threads |
0d2c74c6 | 100 | WX_DEFINE_ARRAY_PTR(wxThread *, wxArrayThread); |
518b5d2f | 101 | |
9e84b847 VZ |
102 | // an entry for a thread we can wait for |
103 | ||
518b5d2f VZ |
104 | // ----------------------------------------------------------------------------- |
105 | // global data | |
106 | // ----------------------------------------------------------------------------- | |
107 | ||
108 | // we keep the list of all threads created by the application to be able to | |
109 | // terminate them on exit if there are some left - otherwise the process would | |
110 | // be left in memory | |
111 | static wxArrayThread gs_allThreads; | |
112 | ||
25b34b26 VZ |
113 | // a mutex to protect gs_allThreads |
114 | static wxMutex *gs_mutexAllThreads = NULL; | |
115 | ||
518b5d2f | 116 | // the id of the main thread |
f9226383 VZ |
117 | // |
118 | // we suppose that 0 is not a valid pthread_t value but in principle this might | |
119 | // be false (e.g. if it's a selector-like value), wxThread::IsMain() would need | |
120 | // to be updated in such case | |
121 | wxThreadIdType wxThread::ms_idMainThread = 0; | |
518b5d2f VZ |
122 | |
123 | // the key for the pointer to the associated wxThread object | |
124 | static pthread_key_t gs_keySelf; | |
125 | ||
9fc3ad34 VZ |
126 | // the number of threads which are being deleted - the program won't exit |
127 | // until there are any left | |
128 | static size_t gs_nThreadsBeingDeleted = 0; | |
129 | ||
130 | // a mutex to protect gs_nThreadsBeingDeleted | |
d3b9f782 | 131 | static wxMutex *gs_mutexDeleteThread = NULL; |
9fc3ad34 VZ |
132 | |
133 | // and a condition variable which will be signaled when all | |
134 | // gs_nThreadsBeingDeleted will have been deleted | |
d3b9f782 | 135 | static wxCondition *gs_condAllDeleted = NULL; |
9fc3ad34 | 136 | |
c80217d1 VS |
137 | // this mutex must be acquired before any call to a GUI function |
138 | // (it's not inside #if wxUSE_GUI because this file is compiled as part | |
139 | // of wxBase) | |
140 | static wxMutex *gs_mutexGui = NULL; | |
518b5d2f | 141 | |
9e84b847 VZ |
142 | // when we wait for a thread to exit, we're blocking on a condition which the |
143 | // thread signals in its SignalExit() method -- but this condition can't be a | |
144 | // member of the thread itself as a detached thread may delete itself at any | |
145 | // moment and accessing the condition member of the thread after this would | |
146 | // result in a disaster | |
147 | // | |
148 | // so instead we maintain a global list of the structs below for the threads | |
149 | // we're interested in waiting on | |
150 | ||
518b5d2f | 151 | // ============================================================================ |
8d5eff60 | 152 | // wxMutex implementation |
518b5d2f VZ |
153 | // ============================================================================ |
154 | ||
8d5eff60 VZ |
155 | // ---------------------------------------------------------------------------- |
156 | // wxMutexInternal | |
157 | // ---------------------------------------------------------------------------- | |
518b5d2f | 158 | |
9e84b847 VZ |
159 | // this is a simple wrapper around pthread_mutex_t which provides error |
160 | // checking | |
518b5d2f VZ |
161 | class wxMutexInternal |
162 | { | |
163 | public: | |
9e84b847 | 164 | wxMutexInternal(wxMutexType mutexType); |
8d5eff60 VZ |
165 | ~wxMutexInternal(); |
166 | ||
167 | wxMutexError Lock(); | |
696d13ee | 168 | wxMutexError Lock(unsigned long ms); |
8d5eff60 VZ |
169 | wxMutexError TryLock(); |
170 | wxMutexError Unlock(); | |
171 | ||
9e84b847 VZ |
172 | bool IsOk() const { return m_isOk; } |
173 | ||
696d13ee VZ |
174 | private: |
175 | // convert the result of pthread_mutex_[timed]lock() call to wx return code | |
176 | wxMutexError HandleLockResult(int err); | |
177 | ||
8d5eff60 | 178 | private: |
9fc3ad34 | 179 | pthread_mutex_t m_mutex; |
9e84b847 | 180 | bool m_isOk; |
375f364e RR |
181 | wxMutexType m_type; |
182 | unsigned long m_owningThread; | |
be809868 | 183 | |
9e84b847 | 184 | // wxConditionInternal uses our m_mutex |
be809868 | 185 | friend class wxConditionInternal; |
518b5d2f VZ |
186 | }; |
187 | ||
123dca7d VZ |
188 | #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \ |
189 | wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL) | |
707a3782 VS |
190 | // on some systems pthread_mutexattr_settype() is not in the headers (but it is |
191 | // in the library, otherwise we wouldn't compile this code at all) | |
192 | extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t *, int); | |
193 | #endif | |
194 | ||
9e84b847 | 195 | wxMutexInternal::wxMutexInternal(wxMutexType mutexType) |
518b5d2f | 196 | { |
375f364e RR |
197 | m_type = mutexType; |
198 | m_owningThread = 0; | |
199 | ||
9e84b847 VZ |
200 | int err; |
201 | switch ( mutexType ) | |
202 | { | |
203 | case wxMUTEX_RECURSIVE: | |
204 | // support recursive locks like Win32, i.e. a thread can lock a | |
205 | // mutex which it had itself already locked | |
206 | // | |
207 | // unfortunately initialization of recursive mutexes is non | |
208 | // portable, so try several methods | |
d9b9876f | 209 | #ifdef HAVE_PTHREAD_MUTEXATTR_T |
9e84b847 VZ |
210 | { |
211 | pthread_mutexattr_t attr; | |
212 | pthread_mutexattr_init(&attr); | |
213 | pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); | |
d9b9876f | 214 | |
9e84b847 VZ |
215 | err = pthread_mutex_init(&m_mutex, &attr); |
216 | } | |
d9b9876f | 217 | #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER) |
9e84b847 VZ |
218 | // we can use this only as initializer so we have to assign it |
219 | // first to a temp var - assigning directly to m_mutex wouldn't | |
220 | // even compile | |
221 | { | |
222 | pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; | |
223 | m_mutex = mutex; | |
224 | } | |
d9b9876f | 225 | #else // no recursive mutexes |
9e84b847 | 226 | err = EINVAL; |
d9b9876f | 227 | #endif // HAVE_PTHREAD_MUTEXATTR_T/... |
9e84b847 VZ |
228 | break; |
229 | ||
230 | default: | |
9a83f860 | 231 | wxFAIL_MSG( wxT("unknown mutex type") ); |
9e84b847 VZ |
232 | // fall through |
233 | ||
234 | case wxMUTEX_DEFAULT: | |
235 | err = pthread_mutex_init(&m_mutex, NULL); | |
236 | break; | |
237 | } | |
238 | ||
239 | m_isOk = err == 0; | |
240 | if ( !m_isOk ) | |
241 | { | |
401eb3de | 242 | wxLogApiError( wxT("pthread_mutex_init()"), err); |
9e84b847 | 243 | } |
8d5eff60 VZ |
244 | } |
245 | ||
246 | wxMutexInternal::~wxMutexInternal() | |
247 | { | |
9e84b847 VZ |
248 | if ( m_isOk ) |
249 | { | |
250 | int err = pthread_mutex_destroy(&m_mutex); | |
251 | if ( err != 0 ) | |
252 | { | |
401eb3de | 253 | wxLogApiError( wxT("pthread_mutex_destroy()"), err); |
9e84b847 VZ |
254 | } |
255 | } | |
8d5eff60 VZ |
256 | } |
257 | ||
258 | wxMutexError wxMutexInternal::Lock() | |
259 | { | |
375f364e RR |
260 | if ((m_type == wxMUTEX_DEFAULT) && (m_owningThread != 0)) |
261 | { | |
262 | if (m_owningThread == wxThread::GetCurrentId()) | |
263 | return wxMUTEX_DEAD_LOCK; | |
264 | } | |
122cf17b | 265 | |
696d13ee VZ |
266 | return HandleLockResult(pthread_mutex_lock(&m_mutex)); |
267 | } | |
268 | ||
269 | wxMutexError wxMutexInternal::Lock(unsigned long ms) | |
270 | { | |
e55a667c | 271 | #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK |
696d13ee VZ |
272 | static const long MSEC_IN_SEC = 1000; |
273 | static const long NSEC_IN_MSEC = 1000000; | |
fd91cec1 | 274 | static const long NSEC_IN_USEC = 1000; |
696d13ee VZ |
275 | static const long NSEC_IN_SEC = MSEC_IN_SEC * NSEC_IN_MSEC; |
276 | ||
277 | time_t seconds = ms/MSEC_IN_SEC; | |
278 | long nanoseconds = (ms % MSEC_IN_SEC) * NSEC_IN_MSEC; | |
279 | timespec ts = { 0, 0 }; | |
280 | ||
fd91cec1 VZ |
281 | // normally we should use clock_gettime(CLOCK_REALTIME) here but this |
282 | // function is in librt and we don't link with it currently, so use | |
283 | // gettimeofday() instead -- if it turns out that this is really too | |
284 | // imprecise, we should modify configure to check if clock_gettime() is | |
285 | // available and whether it requires -lrt and use it instead | |
286 | #if 0 | |
696d13ee VZ |
287 | if ( clock_gettime(CLOCK_REALTIME, &ts) == 0 ) |
288 | { | |
696d13ee | 289 | } |
fd91cec1 VZ |
290 | #else |
291 | struct timeval tv; | |
292 | if ( wxGetTimeOfDay(&tv) != -1 ) | |
293 | { | |
294 | ts.tv_sec = tv.tv_sec; | |
295 | ts.tv_nsec = tv.tv_usec*NSEC_IN_USEC; | |
296 | } | |
297 | #endif | |
696d13ee VZ |
298 | else // fall back on system timer |
299 | { | |
fd91cec1 VZ |
300 | ts.tv_sec = time(NULL); |
301 | } | |
302 | ||
303 | ts.tv_sec += seconds; | |
304 | ts.tv_nsec += nanoseconds; | |
305 | if ( ts.tv_nsec > NSEC_IN_SEC ) | |
306 | { | |
307 | ts.tv_sec += 1; | |
308 | ts.tv_nsec -= NSEC_IN_SEC; | |
696d13ee VZ |
309 | } |
310 | ||
311 | return HandleLockResult(pthread_mutex_timedlock(&m_mutex, &ts)); | |
e55a667c VZ |
312 | #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK |
313 | wxUnusedVar(ms); | |
314 | ||
315 | return wxMUTEX_MISC_ERROR; | |
316 | #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK | |
696d13ee VZ |
317 | } |
318 | ||
319 | wxMutexError wxMutexInternal::HandleLockResult(int err) | |
320 | { | |
375f364e RR |
321 | // wxPrintf( "err %d\n", err ); |
322 | ||
8d5eff60 VZ |
323 | switch ( err ) |
324 | { | |
325 | case EDEADLK: | |
9e84b847 VZ |
326 | // only error checking mutexes return this value and so it's an |
327 | // unexpected situation -- hence use assert, not wxLogDebug | |
9a83f860 | 328 | wxFAIL_MSG( wxT("mutex deadlock prevented") ); |
8d5eff60 VZ |
329 | return wxMUTEX_DEAD_LOCK; |
330 | ||
8d5eff60 | 331 | case EINVAL: |
9a83f860 | 332 | wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized")); |
9e84b847 | 333 | break; |
8d5eff60 | 334 | |
696d13ee VZ |
335 | case ETIMEDOUT: |
336 | return wxMUTEX_TIMEOUT; | |
337 | ||
8d5eff60 | 338 | case 0: |
375f364e RR |
339 | if (m_type == wxMUTEX_DEFAULT) |
340 | m_owningThread = wxThread::GetCurrentId(); | |
8d5eff60 | 341 | return wxMUTEX_NO_ERROR; |
9e84b847 VZ |
342 | |
343 | default: | |
9a83f860 | 344 | wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err); |
8d5eff60 | 345 | } |
9e84b847 VZ |
346 | |
347 | return wxMUTEX_MISC_ERROR; | |
8d5eff60 VZ |
348 | } |
349 | ||
696d13ee | 350 | |
8d5eff60 VZ |
351 | wxMutexError wxMutexInternal::TryLock() |
352 | { | |
353 | int err = pthread_mutex_trylock(&m_mutex); | |
354 | switch ( err ) | |
355 | { | |
356 | case EBUSY: | |
9e84b847 VZ |
357 | // not an error: mutex is already locked, but we're prepared for |
358 | // this | |
8d5eff60 VZ |
359 | return wxMUTEX_BUSY; |
360 | ||
8d5eff60 | 361 | case EINVAL: |
9a83f860 | 362 | wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized.")); |
9e84b847 | 363 | break; |
8d5eff60 VZ |
364 | |
365 | case 0: | |
375f364e RR |
366 | if (m_type == wxMUTEX_DEFAULT) |
367 | m_owningThread = wxThread::GetCurrentId(); | |
8d5eff60 | 368 | return wxMUTEX_NO_ERROR; |
9e84b847 VZ |
369 | |
370 | default: | |
9a83f860 | 371 | wxLogApiError(wxT("pthread_mutex_trylock()"), err); |
8d5eff60 | 372 | } |
9e84b847 VZ |
373 | |
374 | return wxMUTEX_MISC_ERROR; | |
8d5eff60 VZ |
375 | } |
376 | ||
377 | wxMutexError wxMutexInternal::Unlock() | |
378 | { | |
375f364e | 379 | m_owningThread = 0; |
122cf17b | 380 | |
8d5eff60 VZ |
381 | int err = pthread_mutex_unlock(&m_mutex); |
382 | switch ( err ) | |
383 | { | |
384 | case EPERM: | |
385 | // we don't own the mutex | |
386 | return wxMUTEX_UNLOCKED; | |
387 | ||
8d5eff60 | 388 | case EINVAL: |
9a83f860 | 389 | wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized.")); |
9e84b847 | 390 | break; |
8d5eff60 VZ |
391 | |
392 | case 0: | |
393 | return wxMUTEX_NO_ERROR; | |
518b5d2f | 394 | |
9e84b847 | 395 | default: |
9a83f860 | 396 | wxLogApiError(wxT("pthread_mutex_unlock()"), err); |
518b5d2f VZ |
397 | } |
398 | ||
9e84b847 | 399 | return wxMUTEX_MISC_ERROR; |
518b5d2f VZ |
400 | } |
401 | ||
be809868 | 402 | // =========================================================================== |
8d5eff60 | 403 | // wxCondition implementation |
be809868 | 404 | // =========================================================================== |
8d5eff60 | 405 | |
be809868 | 406 | // --------------------------------------------------------------------------- |
8d5eff60 | 407 | // wxConditionInternal |
be809868 | 408 | // --------------------------------------------------------------------------- |
518b5d2f | 409 | |
9e84b847 VZ |
410 | // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence |
411 | // with a pthread_mutex_t) | |
518b5d2f VZ |
412 | class wxConditionInternal |
413 | { | |
414 | public: | |
c112e100 | 415 | wxConditionInternal(wxMutex& mutex); |
9fc3ad34 VZ |
416 | ~wxConditionInternal(); |
417 | ||
9e84b847 | 418 | bool IsOk() const { return m_isOk && m_mutex.IsOk(); } |
4c460b34 | 419 | |
9e84b847 VZ |
420 | wxCondError Wait(); |
421 | wxCondError WaitTimeout(unsigned long milliseconds); | |
547b93ab | 422 | |
9e84b847 VZ |
423 | wxCondError Signal(); |
424 | wxCondError Broadcast(); | |
4c460b34 | 425 | |
be809868 | 426 | private: |
c112e100 | 427 | // get the POSIX mutex associated with us |
9e84b847 | 428 | pthread_mutex_t *GetPMutex() const { return &m_mutex.m_internal->m_mutex; } |
518b5d2f | 429 | |
c112e100 | 430 | wxMutex& m_mutex; |
be809868 | 431 | pthread_cond_t m_cond; |
9e84b847 VZ |
432 | |
433 | bool m_isOk; | |
8d5eff60 | 434 | }; |
547b93ab | 435 | |
c112e100 VZ |
436 | wxConditionInternal::wxConditionInternal(wxMutex& mutex) |
437 | : m_mutex(mutex) | |
9fc3ad34 | 438 | { |
9e84b847 | 439 | int err = pthread_cond_init(&m_cond, NULL /* default attributes */); |
9fc3ad34 | 440 | |
9e84b847 | 441 | m_isOk = err == 0; |
9fc3ad34 | 442 | |
9e84b847 | 443 | if ( !m_isOk ) |
9fc3ad34 | 444 | { |
9a83f860 | 445 | wxLogApiError(wxT("pthread_cond_init()"), err); |
9fc3ad34 VZ |
446 | } |
447 | } | |
448 | ||
9e84b847 | 449 | wxConditionInternal::~wxConditionInternal() |
4c460b34 | 450 | { |
9e84b847 | 451 | if ( m_isOk ) |
c112e100 | 452 | { |
9e84b847 VZ |
453 | int err = pthread_cond_destroy(&m_cond); |
454 | if ( err != 0 ) | |
455 | { | |
9a83f860 | 456 | wxLogApiError(wxT("pthread_cond_destroy()"), err); |
9e84b847 | 457 | } |
c112e100 | 458 | } |
be809868 | 459 | } |
4c460b34 | 460 | |
9e84b847 | 461 | wxCondError wxConditionInternal::Wait() |
be809868 | 462 | { |
9e84b847 VZ |
463 | int err = pthread_cond_wait(&m_cond, GetPMutex()); |
464 | if ( err != 0 ) | |
465 | { | |
9a83f860 | 466 | wxLogApiError(wxT("pthread_cond_wait()"), err); |
4c460b34 | 467 | |
9e84b847 | 468 | return wxCOND_MISC_ERROR; |
be809868 | 469 | } |
4c460b34 | 470 | |
9e84b847 | 471 | return wxCOND_NO_ERROR; |
be809868 | 472 | } |
60ce696e | 473 | |
9e84b847 | 474 | wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds) |
be809868 | 475 | { |
be809868 | 476 | wxLongLong curtime = wxGetLocalTimeMillis(); |
9e84b847 | 477 | curtime += milliseconds; |
be809868 VZ |
478 | wxLongLong temp = curtime / 1000; |
479 | int sec = temp.GetLo(); | |
9e84b847 | 480 | temp *= 1000; |
be809868 VZ |
481 | temp = curtime - temp; |
482 | int millis = temp.GetLo(); | |
483 | ||
484 | timespec tspec; | |
485 | ||
486 | tspec.tv_sec = sec; | |
487 | tspec.tv_nsec = millis * 1000L * 1000L; | |
4c460b34 | 488 | |
9e84b847 VZ |
489 | int err = pthread_cond_timedwait( &m_cond, GetPMutex(), &tspec ); |
490 | switch ( err ) | |
491 | { | |
492 | case ETIMEDOUT: | |
493 | return wxCOND_TIMEOUT; | |
494 | ||
495 | case 0: | |
496 | return wxCOND_NO_ERROR; | |
497 | ||
498 | default: | |
9a83f860 | 499 | wxLogApiError(wxT("pthread_cond_timedwait()"), err); |
9e84b847 VZ |
500 | } |
501 | ||
502 | return wxCOND_MISC_ERROR; | |
9fc3ad34 VZ |
503 | } |
504 | ||
9e84b847 | 505 | wxCondError wxConditionInternal::Signal() |
9fc3ad34 | 506 | { |
9e84b847 VZ |
507 | int err = pthread_cond_signal(&m_cond); |
508 | if ( err != 0 ) | |
509 | { | |
9a83f860 | 510 | wxLogApiError(wxT("pthread_cond_signal()"), err); |
9e84b847 VZ |
511 | |
512 | return wxCOND_MISC_ERROR; | |
513 | } | |
514 | ||
515 | return wxCOND_NO_ERROR; | |
be809868 | 516 | } |
547b93ab | 517 | |
9e84b847 | 518 | wxCondError wxConditionInternal::Broadcast() |
be809868 | 519 | { |
9e84b847 VZ |
520 | int err = pthread_cond_broadcast(&m_cond); |
521 | if ( err != 0 ) | |
522 | { | |
9a83f860 | 523 | wxLogApiError(wxT("pthread_cond_broadcast()"), err); |
9e84b847 VZ |
524 | |
525 | return wxCOND_MISC_ERROR; | |
526 | } | |
527 | ||
528 | return wxCOND_NO_ERROR; | |
be809868 VZ |
529 | } |
530 | ||
531 | // =========================================================================== | |
532 | // wxSemaphore implementation | |
533 | // =========================================================================== | |
9fc3ad34 | 534 | |
be809868 VZ |
535 | // --------------------------------------------------------------------------- |
536 | // wxSemaphoreInternal | |
537 | // --------------------------------------------------------------------------- | |
538 | ||
9e84b847 VZ |
539 | // we implement the semaphores using mutexes and conditions instead of using |
540 | // the sem_xxx() POSIX functions because they're not widely available and also | |
541 | // because it's impossible to implement WaitTimeout() using them | |
be809868 VZ |
542 | class wxSemaphoreInternal |
543 | { | |
544 | public: | |
9e84b847 | 545 | wxSemaphoreInternal(int initialcount, int maxcount); |
be809868 | 546 | |
9e84b847 | 547 | bool IsOk() const { return m_isOk; } |
be809868 | 548 | |
9e84b847 VZ |
549 | wxSemaError Wait(); |
550 | wxSemaError TryWait(); | |
551 | wxSemaError WaitTimeout(unsigned long milliseconds); | |
be809868 | 552 | |
9e84b847 | 553 | wxSemaError Post(); |
be809868 VZ |
554 | |
555 | private: | |
556 | wxMutex m_mutex; | |
557 | wxCondition m_cond; | |
558 | ||
9e84b847 VZ |
559 | size_t m_count, |
560 | m_maxcount; | |
561 | ||
562 | bool m_isOk; | |
be809868 VZ |
563 | }; |
564 | ||
9e84b847 | 565 | wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount) |
c112e100 | 566 | : m_cond(m_mutex) |
be809868 VZ |
567 | { |
568 | ||
9e84b847 VZ |
569 | if ( (initialcount < 0 || maxcount < 0) || |
570 | ((maxcount > 0) && (initialcount > maxcount)) ) | |
571 | { | |
9a83f860 | 572 | wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") ); |
9e84b847 | 573 | |
ad9835c9 | 574 | m_isOk = false; |
9e84b847 VZ |
575 | } |
576 | else | |
be809868 | 577 | { |
9e84b847 VZ |
578 | m_maxcount = (size_t)maxcount; |
579 | m_count = (size_t)initialcount; | |
547b93ab | 580 | } |
547b93ab | 581 | |
9e84b847 | 582 | m_isOk = m_mutex.IsOk() && m_cond.IsOk(); |
be809868 | 583 | } |
547b93ab | 584 | |
9e84b847 | 585 | wxSemaError wxSemaphoreInternal::Wait() |
be809868 | 586 | { |
cd10339a | 587 | wxMutexLocker locker(m_mutex); |
60ce696e | 588 | |
9e84b847 | 589 | while ( m_count == 0 ) |
9fc3ad34 | 590 | { |
9e84b847 | 591 | wxLogTrace(TRACE_SEMA, |
9a83f860 | 592 | wxT("Thread %p waiting for semaphore to become signalled"), |
35e9c131 | 593 | THR_ID_CAST(wxThread::GetCurrentId())); |
9e84b847 VZ |
594 | |
595 | if ( m_cond.Wait() != wxCOND_NO_ERROR ) | |
596 | return wxSEMA_MISC_ERROR; | |
597 | ||
598 | wxLogTrace(TRACE_SEMA, | |
9a83f860 | 599 | wxT("Thread %p finished waiting for semaphore, count = %lu"), |
35e9c131 | 600 | THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count); |
9fc3ad34 | 601 | } |
be809868 | 602 | |
9e84b847 VZ |
603 | m_count--; |
604 | ||
605 | return wxSEMA_NO_ERROR; | |
be809868 VZ |
606 | } |
607 | ||
9e84b847 | 608 | wxSemaError wxSemaphoreInternal::TryWait() |
be809868 | 609 | { |
cd10339a | 610 | wxMutexLocker locker(m_mutex); |
be809868 | 611 | |
9e84b847 VZ |
612 | if ( m_count == 0 ) |
613 | return wxSEMA_BUSY; | |
be809868 | 614 | |
9e84b847 | 615 | m_count--; |
be809868 | 616 | |
9e84b847 | 617 | return wxSEMA_NO_ERROR; |
be809868 VZ |
618 | } |
619 | ||
9e84b847 | 620 | wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds) |
be809868 | 621 | { |
cd10339a | 622 | wxMutexLocker locker(m_mutex); |
be809868 VZ |
623 | |
624 | wxLongLong startTime = wxGetLocalTimeMillis(); | |
625 | ||
9e84b847 | 626 | while ( m_count == 0 ) |
9fc3ad34 | 627 | { |
be809868 | 628 | wxLongLong elapsed = wxGetLocalTimeMillis() - startTime; |
9e84b847 | 629 | long remainingTime = (long)milliseconds - (long)elapsed.GetLo(); |
be809868 | 630 | if ( remainingTime <= 0 ) |
9e84b847 VZ |
631 | { |
632 | // timeout | |
633 | return wxSEMA_TIMEOUT; | |
634 | } | |
be809868 | 635 | |
918dc519 VZ |
636 | switch ( m_cond.WaitTimeout(remainingTime) ) |
637 | { | |
638 | case wxCOND_TIMEOUT: | |
639 | return wxSEMA_TIMEOUT; | |
640 | ||
641 | default: | |
642 | return wxSEMA_MISC_ERROR; | |
643 | ||
644 | case wxCOND_NO_ERROR: | |
645 | ; | |
646 | } | |
9fc3ad34 | 647 | } |
8d5eff60 | 648 | |
9e84b847 | 649 | m_count--; |
be809868 | 650 | |
9e84b847 | 651 | return wxSEMA_NO_ERROR; |
be809868 VZ |
652 | } |
653 | ||
9e84b847 | 654 | wxSemaError wxSemaphoreInternal::Post() |
be809868 | 655 | { |
cd10339a | 656 | wxMutexLocker locker(m_mutex); |
be809868 | 657 | |
9e84b847 | 658 | if ( m_maxcount > 0 && m_count == m_maxcount ) |
60ce696e | 659 | { |
9e84b847 | 660 | return wxSEMA_OVERFLOW; |
60ce696e | 661 | } |
be809868 | 662 | |
9e84b847 | 663 | m_count++; |
518b5d2f | 664 | |
9e84b847 | 665 | wxLogTrace(TRACE_SEMA, |
9a83f860 | 666 | wxT("Thread %p about to signal semaphore, count = %lu"), |
35e9c131 | 667 | THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count); |
2b5f62a0 | 668 | |
9e84b847 VZ |
669 | return m_cond.Signal() == wxCOND_NO_ERROR ? wxSEMA_NO_ERROR |
670 | : wxSEMA_MISC_ERROR; | |
518b5d2f VZ |
671 | } |
672 | ||
be809868 | 673 | // =========================================================================== |
8d5eff60 | 674 | // wxThread implementation |
be809868 | 675 | // =========================================================================== |
518b5d2f | 676 | |
295272bd VZ |
677 | // the thread callback functions must have the C linkage |
678 | extern "C" | |
679 | { | |
680 | ||
816a7358 | 681 | #ifdef wxHAVE_PTHREAD_CLEANUP |
295272bd VZ |
682 | // thread exit function |
683 | void wxPthreadCleanup(void *ptr); | |
816a7358 | 684 | #endif // wxHAVE_PTHREAD_CLEANUP |
90350682 | 685 | |
295272bd | 686 | void *wxPthreadStart(void *ptr); |
90350682 | 687 | |
295272bd | 688 | } // extern "C" |
90350682 | 689 | |
8d5eff60 VZ |
690 | // ---------------------------------------------------------------------------- |
691 | // wxThreadInternal | |
692 | // ---------------------------------------------------------------------------- | |
693 | ||
518b5d2f VZ |
694 | class wxThreadInternal |
695 | { | |
696 | public: | |
697 | wxThreadInternal(); | |
698 | ~wxThreadInternal(); | |
699 | ||
700 | // thread entry function | |
295272bd | 701 | static void *PthreadStart(wxThread *thread); |
518b5d2f VZ |
702 | |
703 | // thread actions | |
704 | // start the thread | |
705 | wxThreadError Run(); | |
9e84b847 VZ |
706 | // unblock the thread allowing it to run |
707 | void SignalRun() { m_semRun.Post(); } | |
518b5d2f | 708 | // ask the thread to terminate |
882eefb1 | 709 | void Wait(); |
518b5d2f VZ |
710 | // go to sleep until Resume() is called |
711 | void Pause(); | |
712 | // resume the thread | |
713 | void Resume(); | |
714 | ||
715 | // accessors | |
716 | // priority | |
717 | int GetPriority() const { return m_prio; } | |
718 | void SetPriority(int prio) { m_prio = prio; } | |
719 | // state | |
882eefb1 | 720 | wxThreadState GetState() const { return m_state; } |
9e84b847 VZ |
721 | void SetState(wxThreadState state) |
722 | { | |
711f12ef | 723 | #if wxUSE_LOG_TRACE |
a243da29 | 724 | static const wxChar *const stateNames[] = |
9e84b847 | 725 | { |
9a83f860 VZ |
726 | wxT("NEW"), |
727 | wxT("RUNNING"), | |
728 | wxT("PAUSED"), | |
729 | wxT("EXITED"), | |
9e84b847 VZ |
730 | }; |
731 | ||
9a83f860 | 732 | wxLogTrace(TRACE_THREADS, wxT("Thread %p: %s => %s."), |
35e9c131 | 733 | THR_ID(this), stateNames[m_state], stateNames[state]); |
711f12ef | 734 | #endif // wxUSE_LOG_TRACE |
9e84b847 VZ |
735 | |
736 | m_state = state; | |
737 | } | |
518b5d2f | 738 | // id |
882eefb1 VZ |
739 | pthread_t GetId() const { return m_threadId; } |
740 | pthread_t *GetIdPtr() { return &m_threadId; } | |
518b5d2f | 741 | // "cancelled" flag |
ad9835c9 | 742 | void SetCancelFlag() { m_cancelled = true; } |
518b5d2f | 743 | bool WasCancelled() const { return m_cancelled; } |
9fc3ad34 VZ |
744 | // exit code |
745 | void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; } | |
746 | wxThread::ExitCode GetExitCode() const { return m_exitcode; } | |
747 | ||
4c460b34 VZ |
748 | // the pause flag |
749 | void SetReallyPaused(bool paused) { m_isPaused = paused; } | |
750 | bool IsReallyPaused() const { return m_isPaused; } | |
751 | ||
9fc3ad34 | 752 | // tell the thread that it is a detached one |
4c460b34 VZ |
753 | void Detach() |
754 | { | |
9e84b847 VZ |
755 | wxCriticalSectionLocker lock(m_csJoinFlag); |
756 | ||
ad9835c9 WS |
757 | m_shouldBeJoined = false; |
758 | m_isDetached = true; | |
4c460b34 | 759 | } |
518b5d2f | 760 | |
816a7358 | 761 | #ifdef wxHAVE_PTHREAD_CLEANUP |
90350682 VZ |
762 | // this is used by wxPthreadCleanup() only |
763 | static void Cleanup(wxThread *thread); | |
816a7358 | 764 | #endif // wxHAVE_PTHREAD_CLEANUP |
90350682 | 765 | |
518b5d2f | 766 | private: |
882eefb1 VZ |
767 | pthread_t m_threadId; // id of the thread |
768 | wxThreadState m_state; // see wxThreadState enum | |
77ffb593 | 769 | int m_prio; // in wxWidgets units: from 0 to 100 |
518b5d2f | 770 | |
9fc3ad34 | 771 | // this flag is set when the thread should terminate |
518b5d2f VZ |
772 | bool m_cancelled; |
773 | ||
be809868 | 774 | // this flag is set when the thread is blocking on m_semSuspend |
4c460b34 VZ |
775 | bool m_isPaused; |
776 | ||
9fc3ad34 VZ |
777 | // the thread exit code - only used for joinable (!detached) threads and |
778 | // is only valid after the thread termination | |
779 | wxThread::ExitCode m_exitcode; | |
780 | ||
781 | // many threads may call Wait(), but only one of them should call | |
782 | // pthread_join(), so we have to keep track of this | |
783 | wxCriticalSection m_csJoinFlag; | |
784 | bool m_shouldBeJoined; | |
4c460b34 | 785 | bool m_isDetached; |
9fc3ad34 | 786 | |
be809868 | 787 | // this semaphore is posted by Run() and the threads Entry() is not |
9fc3ad34 | 788 | // called before it is done |
be809868 | 789 | wxSemaphore m_semRun; |
9fc3ad34 VZ |
790 | |
791 | // this one is signaled when the thread should resume after having been | |
792 | // Pause()d | |
be809868 | 793 | wxSemaphore m_semSuspend; |
518b5d2f VZ |
794 | }; |
795 | ||
9fc3ad34 VZ |
796 | // ---------------------------------------------------------------------------- |
797 | // thread startup and exit functions | |
798 | // ---------------------------------------------------------------------------- | |
799 | ||
295272bd VZ |
800 | void *wxPthreadStart(void *ptr) |
801 | { | |
802 | return wxThreadInternal::PthreadStart((wxThread *)ptr); | |
803 | } | |
804 | ||
805 | void *wxThreadInternal::PthreadStart(wxThread *thread) | |
518b5d2f | 806 | { |
9fc3ad34 | 807 | wxThreadInternal *pthread = thread->m_internal; |
518b5d2f | 808 | |
9a83f860 | 809 | wxLogTrace(TRACE_THREADS, wxT("Thread %p started."), THR_ID(pthread)); |
ef4f69ec | 810 | |
9fc3ad34 VZ |
811 | // associate the thread pointer with the newly created thread so that |
812 | // wxThread::This() will work | |
862cc6f9 VZ |
813 | int rc = pthread_setspecific(gs_keySelf, thread); |
814 | if ( rc != 0 ) | |
518b5d2f | 815 | { |
58230fb1 | 816 | wxLogSysError(rc, _("Cannot start thread: error writing TLS")); |
518b5d2f VZ |
817 | |
818 | return (void *)-1; | |
819 | } | |
9fc3ad34 | 820 | |
4c460b34 VZ |
821 | // have to declare this before pthread_cleanup_push() which defines a |
822 | // block! | |
823 | bool dontRunAtAll; | |
824 | ||
816a7358 | 825 | #ifdef wxHAVE_PTHREAD_CLEANUP |
9fc3ad34 VZ |
826 | // install the cleanup handler which will be called if the thread is |
827 | // cancelled | |
295272bd | 828 | pthread_cleanup_push(wxPthreadCleanup, thread); |
816a7358 | 829 | #endif // wxHAVE_PTHREAD_CLEANUP |
518b5d2f | 830 | |
be809868 VZ |
831 | // wait for the semaphore to be posted from Run() |
832 | pthread->m_semRun.Wait(); | |
518b5d2f | 833 | |
4c460b34 VZ |
834 | // test whether we should run the run at all - may be it was deleted |
835 | // before it started to Run()? | |
836 | { | |
837 | wxCriticalSectionLocker lock(thread->m_critsect); | |
9fc3ad34 | 838 | |
4c460b34 VZ |
839 | dontRunAtAll = pthread->GetState() == STATE_NEW && |
840 | pthread->WasCancelled(); | |
841 | } | |
9fc3ad34 | 842 | |
4c460b34 | 843 | if ( !dontRunAtAll ) |
9fc3ad34 | 844 | { |
4c460b34 | 845 | // call the main entry |
ef4f69ec | 846 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 847 | wxT("Thread %p about to enter its Entry()."), |
ef4f69ec VZ |
848 | THR_ID(pthread)); |
849 | ||
79b7b95a VS |
850 | wxTRY |
851 | { | |
852 | pthread->m_exitcode = thread->Entry(); | |
5092b3ad | 853 | |
79b7b95a | 854 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 855 | wxT("Thread %p Entry() returned %lu."), |
79b7b95a VS |
856 | THR_ID(pthread), wxPtrToUInt(pthread->m_exitcode)); |
857 | } | |
858 | wxCATCH_ALL( wxTheApp->OnUnhandledException(); ) | |
ef4f69ec | 859 | |
4c460b34 VZ |
860 | { |
861 | wxCriticalSectionLocker lock(thread->m_critsect); | |
862 | ||
4c460b34 | 863 | // change the state of the thread to "exited" so that |
90350682 | 864 | // wxPthreadCleanup handler won't do anything from now (if it's |
4c460b34 VZ |
865 | // called before we do pthread_cleanup_pop below) |
866 | pthread->SetState(STATE_EXITED); | |
867 | } | |
9fc3ad34 VZ |
868 | } |
869 | ||
741d91c5 VZ |
870 | // NB: pthread_cleanup_push/pop() are macros and pop contains the matching |
871 | // '}' for the '{' in push, so they must be used in the same block! | |
816a7358 | 872 | #ifdef wxHAVE_PTHREAD_CLEANUP |
741d91c5 VZ |
873 | #ifdef __DECCXX |
874 | // under Tru64 we get a warning from macro expansion | |
875 | #pragma message save | |
876 | #pragma message disable(declbutnotref) | |
877 | #endif | |
878 | ||
9fc3ad34 | 879 | // remove the cleanup handler without executing it |
062c4861 | 880 | pthread_cleanup_pop(FALSE); |
741d91c5 VZ |
881 | |
882 | #ifdef __DECCXX | |
883 | #pragma message restore | |
884 | #endif | |
816a7358 | 885 | #endif // wxHAVE_PTHREAD_CLEANUP |
518b5d2f | 886 | |
4c460b34 VZ |
887 | if ( dontRunAtAll ) |
888 | { | |
9e84b847 | 889 | // FIXME: deleting a possibly joinable thread here??? |
4c460b34 | 890 | delete thread; |
518b5d2f | 891 | |
4c460b34 VZ |
892 | return EXITCODE_CANCELLED; |
893 | } | |
894 | else | |
895 | { | |
896 | // terminate the thread | |
897 | thread->Exit(pthread->m_exitcode); | |
898 | ||
899 | wxFAIL_MSG(wxT("wxThread::Exit() can't return.")); | |
518b5d2f | 900 | |
4c460b34 VZ |
901 | return NULL; |
902 | } | |
518b5d2f VZ |
903 | } |
904 | ||
816a7358 | 905 | #ifdef wxHAVE_PTHREAD_CLEANUP |
5092b3ad | 906 | |
9fc3ad34 | 907 | // this handler is called when the thread is cancelled |
90350682 | 908 | extern "C" void wxPthreadCleanup(void *ptr) |
5092b3ad | 909 | { |
90350682 VZ |
910 | wxThreadInternal::Cleanup((wxThread *)ptr); |
911 | } | |
5092b3ad | 912 | |
90350682 VZ |
913 | void wxThreadInternal::Cleanup(wxThread *thread) |
914 | { | |
b4866582 | 915 | if (pthread_getspecific(gs_keySelf) == 0) return; |
9fc3ad34 VZ |
916 | { |
917 | wxCriticalSectionLocker lock(thread->m_critsect); | |
918 | if ( thread->m_internal->GetState() == STATE_EXITED ) | |
919 | { | |
920 | // thread is already considered as finished. | |
921 | return; | |
922 | } | |
923 | } | |
5092b3ad | 924 | |
9fc3ad34 VZ |
925 | // exit the thread gracefully |
926 | thread->Exit(EXITCODE_CANCELLED); | |
927 | } | |
5092b3ad | 928 | |
816a7358 | 929 | #endif // wxHAVE_PTHREAD_CLEANUP |
5092b3ad | 930 | |
9fc3ad34 VZ |
931 | // ---------------------------------------------------------------------------- |
932 | // wxThreadInternal | |
933 | // ---------------------------------------------------------------------------- | |
5092b3ad | 934 | |
518b5d2f VZ |
935 | wxThreadInternal::wxThreadInternal() |
936 | { | |
937 | m_state = STATE_NEW; | |
ad9835c9 | 938 | m_cancelled = false; |
bbfa0322 VZ |
939 | m_prio = WXTHREAD_DEFAULT_PRIORITY; |
940 | m_threadId = 0; | |
9fc3ad34 | 941 | m_exitcode = 0; |
518b5d2f | 942 | |
ad9835c9 WS |
943 | // set to true only when the thread starts waiting on m_semSuspend |
944 | m_isPaused = false; | |
4c460b34 | 945 | |
9fc3ad34 | 946 | // defaults for joinable threads |
ad9835c9 WS |
947 | m_shouldBeJoined = true; |
948 | m_isDetached = false; | |
518b5d2f VZ |
949 | } |
950 | ||
951 | wxThreadInternal::~wxThreadInternal() | |
952 | { | |
518b5d2f VZ |
953 | } |
954 | ||
955 | wxThreadError wxThreadInternal::Run() | |
956 | { | |
957 | wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING, | |
9fc3ad34 | 958 | wxT("thread may only be started once after Create()") ); |
518b5d2f | 959 | |
9fc3ad34 | 960 | SetState(STATE_RUNNING); |
518b5d2f | 961 | |
9e84b847 VZ |
962 | // wake up threads waiting for our start |
963 | SignalRun(); | |
964 | ||
518b5d2f | 965 | return wxTHREAD_NO_ERROR; |
518b5d2f VZ |
966 | } |
967 | ||
882eefb1 | 968 | void wxThreadInternal::Wait() |
518b5d2f | 969 | { |
9a83f860 | 970 | wxCHECK_RET( !m_isDetached, wxT("can't wait for a detached thread") ); |
9e84b847 | 971 | |
518b5d2f VZ |
972 | // if the thread we're waiting for is waiting for the GUI mutex, we will |
973 | // deadlock so make sure we release it temporarily | |
974 | if ( wxThread::IsMain() ) | |
975 | wxMutexGuiLeave(); | |
976 | ||
547b93ab | 977 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 978 | wxT("Starting to wait for thread %p to exit."), |
ef4f69ec VZ |
979 | THR_ID(this)); |
980 | ||
9e84b847 VZ |
981 | // to avoid memory leaks we should call pthread_join(), but it must only be |
982 | // done once so use a critical section to serialize the code below | |
9fc3ad34 | 983 | { |
4c460b34 VZ |
984 | wxCriticalSectionLocker lock(m_csJoinFlag); |
985 | ||
986 | if ( m_shouldBeJoined ) | |
9fc3ad34 | 987 | { |
4c460b34 VZ |
988 | // FIXME shouldn't we set cancellation type to DISABLED here? If |
989 | // we're cancelled inside pthread_join(), things will almost | |
990 | // certainly break - but if we disable the cancellation, we | |
991 | // might deadlock | |
2b5f62a0 | 992 | if ( pthread_join(GetId(), &m_exitcode) != 0 ) |
4c460b34 | 993 | { |
9e84b847 VZ |
994 | // this is a serious problem, so use wxLogError and not |
995 | // wxLogDebug: it is possible to bring the system to its knees | |
996 | // by creating too many threads and not joining them quite | |
997 | // easily | |
76a6e803 | 998 | wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program")); |
4c460b34 | 999 | } |
9fc3ad34 | 1000 | |
ad9835c9 | 1001 | m_shouldBeJoined = false; |
4c460b34 | 1002 | } |
9fc3ad34 | 1003 | } |
9111db68 | 1004 | |
518b5d2f VZ |
1005 | // reacquire GUI mutex |
1006 | if ( wxThread::IsMain() ) | |
1007 | wxMutexGuiEnter(); | |
1008 | } | |
1009 | ||
518b5d2f VZ |
1010 | void wxThreadInternal::Pause() |
1011 | { | |
882eefb1 VZ |
1012 | // the state is set from the thread which pauses us first, this function |
1013 | // is called later so the state should have been already set | |
518b5d2f | 1014 | wxCHECK_RET( m_state == STATE_PAUSED, |
223d09f6 | 1015 | wxT("thread must first be paused with wxThread::Pause().") ); |
518b5d2f | 1016 | |
ef4f69ec | 1017 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 1018 | wxT("Thread %p goes to sleep."), THR_ID(this)); |
ef4f69ec | 1019 | |
be809868 VZ |
1020 | // wait until the semaphore is Post()ed from Resume() |
1021 | m_semSuspend.Wait(); | |
518b5d2f VZ |
1022 | } |
1023 | ||
1024 | void wxThreadInternal::Resume() | |
1025 | { | |
1026 | wxCHECK_RET( m_state == STATE_PAUSED, | |
223d09f6 | 1027 | wxT("can't resume thread which is not suspended.") ); |
518b5d2f | 1028 | |
4c460b34 VZ |
1029 | // the thread might be not actually paused yet - if there were no call to |
1030 | // TestDestroy() since the last call to Pause() for example | |
1031 | if ( IsReallyPaused() ) | |
1032 | { | |
ef4f69ec | 1033 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 1034 | wxT("Waking up thread %p"), THR_ID(this)); |
ef4f69ec | 1035 | |
4c460b34 | 1036 | // wake up Pause() |
be809868 | 1037 | m_semSuspend.Post(); |
4c460b34 VZ |
1038 | |
1039 | // reset the flag | |
ad9835c9 | 1040 | SetReallyPaused(false); |
4c460b34 VZ |
1041 | } |
1042 | else | |
1043 | { | |
ef4f69ec | 1044 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 1045 | wxT("Thread %p is not yet really paused"), THR_ID(this)); |
4c460b34 | 1046 | } |
518b5d2f VZ |
1047 | |
1048 | SetState(STATE_RUNNING); | |
1049 | } | |
1050 | ||
1051 | // ----------------------------------------------------------------------------- | |
9fc3ad34 | 1052 | // wxThread static functions |
518b5d2f VZ |
1053 | // ----------------------------------------------------------------------------- |
1054 | ||
1055 | wxThread *wxThread::This() | |
1056 | { | |
1057 | return (wxThread *)pthread_getspecific(gs_keySelf); | |
1058 | } | |
1059 | ||
518b5d2f VZ |
1060 | void wxThread::Yield() |
1061 | { | |
6f837e5c | 1062 | #ifdef HAVE_SCHED_YIELD |
518b5d2f | 1063 | sched_yield(); |
6f837e5c | 1064 | #endif |
518b5d2f VZ |
1065 | } |
1066 | ||
ef8d96c2 VZ |
1067 | int wxThread::GetCPUCount() |
1068 | { | |
85bf679a VZ |
1069 | #if defined(_SC_NPROCESSORS_ONLN) |
1070 | // this works for Solaris and Linux 2.6 | |
1071 | int rc = sysconf(_SC_NPROCESSORS_ONLN); | |
1072 | if ( rc != -1 ) | |
1073 | { | |
1074 | return rc; | |
1075 | } | |
1076 | #elif defined(__LINUX__) && wxUSE_FFILE | |
ef8d96c2 VZ |
1077 | // read from proc (can't use wxTextFile here because it's a special file: |
1078 | // it has 0 size but still can be read from) | |
1079 | wxLogNull nolog; | |
1080 | ||
9a83f860 | 1081 | wxFFile file(wxT("/proc/cpuinfo")); |
ef8d96c2 VZ |
1082 | if ( file.IsOpened() ) |
1083 | { | |
1084 | // slurp the whole file | |
1085 | wxString s; | |
1086 | if ( file.ReadAll(&s) ) | |
1087 | { | |
9ec1ed2a | 1088 | // (ab)use Replace() to find the number of "processor: num" strings |
9a83f860 | 1089 | size_t count = s.Replace(wxT("processor\t:"), wxT("")); |
ef8d96c2 VZ |
1090 | if ( count > 0 ) |
1091 | { | |
1092 | return count; | |
1093 | } | |
1094 | ||
9a83f860 | 1095 | wxLogDebug(wxT("failed to parse /proc/cpuinfo")); |
ef8d96c2 VZ |
1096 | } |
1097 | else | |
1098 | { | |
9a83f860 | 1099 | wxLogDebug(wxT("failed to read /proc/cpuinfo")); |
ef8d96c2 VZ |
1100 | } |
1101 | } | |
ef8d96c2 VZ |
1102 | #endif // different ways to get number of CPUs |
1103 | ||
1104 | // unknown | |
1105 | return -1; | |
1106 | } | |
1107 | ||
f9226383 | 1108 | wxThreadIdType wxThread::GetCurrentId() |
1fcfb40d | 1109 | { |
f9226383 | 1110 | return (wxThreadIdType)pthread_self(); |
1fcfb40d RD |
1111 | } |
1112 | ||
ef4f69ec | 1113 | |
ef8d96c2 VZ |
1114 | bool wxThread::SetConcurrency(size_t level) |
1115 | { | |
1116 | #ifdef HAVE_THR_SETCONCURRENCY | |
1117 | int rc = thr_setconcurrency(level); | |
1118 | if ( rc != 0 ) | |
1119 | { | |
9a83f860 | 1120 | wxLogSysError(rc, wxT("thr_setconcurrency() failed")); |
ef8d96c2 VZ |
1121 | } |
1122 | ||
1123 | return rc == 0; | |
1124 | #else // !HAVE_THR_SETCONCURRENCY | |
1125 | // ok only for the default value | |
1126 | return level == 0; | |
1127 | #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY | |
1128 | } | |
1129 | ||
518b5d2f VZ |
1130 | // ----------------------------------------------------------------------------- |
1131 | // creating thread | |
1132 | // ----------------------------------------------------------------------------- | |
1133 | ||
acb8423c | 1134 | wxThread::wxThread(wxThreadKind kind) |
518b5d2f VZ |
1135 | { |
1136 | // add this thread to the global list of all threads | |
25b34b26 VZ |
1137 | { |
1138 | wxMutexLocker lock(*gs_mutexAllThreads); | |
1139 | ||
1140 | gs_allThreads.Add(this); | |
1141 | } | |
518b5d2f | 1142 | |
9fc3ad34 | 1143 | m_internal = new wxThreadInternal(); |
acb8423c VZ |
1144 | |
1145 | m_isDetached = kind == wxTHREAD_DETACHED; | |
518b5d2f VZ |
1146 | } |
1147 | ||
8a077f28 SN |
1148 | #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE |
1149 | #define WXUNUSED_STACKSIZE(identifier) identifier | |
1150 | #else | |
1151 | #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier) | |
1152 | #endif | |
1153 | ||
1154 | wxThreadError wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize)) | |
518b5d2f | 1155 | { |
9fc3ad34 VZ |
1156 | if ( m_internal->GetState() != STATE_NEW ) |
1157 | { | |
1158 | // don't recreate thread | |
518b5d2f | 1159 | return wxTHREAD_RUNNING; |
9fc3ad34 | 1160 | } |
518b5d2f VZ |
1161 | |
1162 | // set up the thread attribute: right now, we only set thread priority | |
1163 | pthread_attr_t attr; | |
1164 | pthread_attr_init(&attr); | |
1165 | ||
8a077f28 SN |
1166 | #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE |
1167 | if (stackSize) | |
1168 | pthread_attr_setstacksize(&attr, stackSize); | |
1169 | #endif | |
1170 | ||
fc9ef629 | 1171 | #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS |
9fc3ad34 VZ |
1172 | int policy; |
1173 | if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 ) | |
518b5d2f | 1174 | { |
58230fb1 | 1175 | wxLogError(_("Cannot retrieve thread scheduling policy.")); |
518b5d2f VZ |
1176 | } |
1177 | ||
fb10f04c JJ |
1178 | #ifdef __VMS__ |
1179 | /* the pthread.h contains too many spaces. This is a work-around */ | |
1180 | # undef sched_get_priority_max | |
1181 | #undef sched_get_priority_min | |
1182 | #define sched_get_priority_max(_pol_) \ | |
1183 | (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX) | |
1184 | #define sched_get_priority_min(_pol_) \ | |
1185 | (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN) | |
1186 | #endif | |
1fcfb40d | 1187 | |
fb10f04c JJ |
1188 | int max_prio = sched_get_priority_max(policy), |
1189 | min_prio = sched_get_priority_min(policy), | |
9fc3ad34 | 1190 | prio = m_internal->GetPriority(); |
518b5d2f VZ |
1191 | |
1192 | if ( min_prio == -1 || max_prio == -1 ) | |
1193 | { | |
58230fb1 | 1194 | wxLogError(_("Cannot get priority range for scheduling policy %d."), |
9fc3ad34 | 1195 | policy); |
518b5d2f | 1196 | } |
bbfa0322 VZ |
1197 | else if ( max_prio == min_prio ) |
1198 | { | |
9fc3ad34 | 1199 | if ( prio != WXTHREAD_DEFAULT_PRIORITY ) |
bbfa0322 VZ |
1200 | { |
1201 | // notify the programmer that this doesn't work here | |
1202 | wxLogWarning(_("Thread priority setting is ignored.")); | |
1203 | } | |
1204 | //else: we have default priority, so don't complain | |
1205 | ||
1206 | // anyhow, don't do anything because priority is just ignored | |
1207 | } | |
518b5d2f VZ |
1208 | else |
1209 | { | |
1210 | struct sched_param sp; | |
9fc3ad34 VZ |
1211 | if ( pthread_attr_getschedparam(&attr, &sp) != 0 ) |
1212 | { | |
9a83f860 | 1213 | wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed")); |
9fc3ad34 VZ |
1214 | } |
1215 | ||
1216 | sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100; | |
1217 | ||
1218 | if ( pthread_attr_setschedparam(&attr, &sp) != 0 ) | |
1219 | { | |
9a83f860 | 1220 | wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed")); |
9fc3ad34 | 1221 | } |
518b5d2f | 1222 | } |
34f8c26e | 1223 | #endif // HAVE_THREAD_PRIORITY_FUNCTIONS |
518b5d2f | 1224 | |
58230fb1 VZ |
1225 | #ifdef HAVE_PTHREAD_ATTR_SETSCOPE |
1226 | // this will make the threads created by this process really concurrent | |
9fc3ad34 VZ |
1227 | if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 ) |
1228 | { | |
9a83f860 | 1229 | wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed")); |
9fc3ad34 | 1230 | } |
58230fb1 VZ |
1231 | #endif // HAVE_PTHREAD_ATTR_SETSCOPE |
1232 | ||
9fc3ad34 VZ |
1233 | // VZ: assume that this one is always available (it's rather fundamental), |
1234 | // if this function is ever missing we should try to use | |
1235 | // pthread_detach() instead (after thread creation) | |
1236 | if ( m_isDetached ) | |
1237 | { | |
1238 | if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 ) | |
1239 | { | |
9a83f860 | 1240 | wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed")); |
9fc3ad34 VZ |
1241 | } |
1242 | ||
1243 | // never try to join detached threads | |
1244 | m_internal->Detach(); | |
1245 | } | |
1246 | //else: threads are created joinable by default, it's ok | |
1247 | ||
518b5d2f | 1248 | // create the new OS thread object |
9fc3ad34 VZ |
1249 | int rc = pthread_create |
1250 | ( | |
1251 | m_internal->GetIdPtr(), | |
1252 | &attr, | |
295272bd | 1253 | wxPthreadStart, |
9fc3ad34 VZ |
1254 | (void *)this |
1255 | ); | |
1256 | ||
1257 | if ( pthread_attr_destroy(&attr) != 0 ) | |
1258 | { | |
9a83f860 | 1259 | wxFAIL_MSG(wxT("pthread_attr_destroy() failed")); |
9fc3ad34 | 1260 | } |
518b5d2f VZ |
1261 | |
1262 | if ( rc != 0 ) | |
1263 | { | |
9fc3ad34 VZ |
1264 | m_internal->SetState(STATE_EXITED); |
1265 | ||
518b5d2f VZ |
1266 | return wxTHREAD_NO_RESOURCE; |
1267 | } | |
1268 | ||
1269 | return wxTHREAD_NO_ERROR; | |
1270 | } | |
1271 | ||
1272 | wxThreadError wxThread::Run() | |
1273 | { | |
9fc3ad34 VZ |
1274 | wxCriticalSectionLocker lock(m_critsect); |
1275 | ||
1276 | wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR, | |
223d09f6 | 1277 | wxT("must call wxThread::Create() first") ); |
bbfa0322 | 1278 | |
9fc3ad34 | 1279 | return m_internal->Run(); |
518b5d2f VZ |
1280 | } |
1281 | ||
1282 | // ----------------------------------------------------------------------------- | |
1283 | // misc accessors | |
1284 | // ----------------------------------------------------------------------------- | |
1285 | ||
1286 | void wxThread::SetPriority(unsigned int prio) | |
1287 | { | |
34f8c26e VZ |
1288 | wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) && |
1289 | ((int)prio <= (int)WXTHREAD_MAX_PRIORITY), | |
223d09f6 | 1290 | wxT("invalid thread priority") ); |
518b5d2f VZ |
1291 | |
1292 | wxCriticalSectionLocker lock(m_critsect); | |
1293 | ||
9fc3ad34 | 1294 | switch ( m_internal->GetState() ) |
518b5d2f VZ |
1295 | { |
1296 | case STATE_NEW: | |
1297 | // thread not yet started, priority will be set when it is | |
9fc3ad34 | 1298 | m_internal->SetPriority(prio); |
518b5d2f VZ |
1299 | break; |
1300 | ||
1301 | case STATE_RUNNING: | |
1302 | case STATE_PAUSED: | |
34f8c26e | 1303 | #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS |
7bfe6a32 | 1304 | #if defined(__LINUX__) |
17a1ebd1 VZ |
1305 | // On Linux, pthread_setschedparam with SCHED_OTHER does not allow |
1306 | // a priority other than 0. Instead, we use the BSD setpriority | |
1307 | // which alllows us to set a 'nice' value between 20 to -20. Only | |
1308 | // super user can set a value less than zero (more negative yields | |
1309 | // higher priority). setpriority set the static priority of a | |
1310 | // process, but this is OK since Linux is configured as a thread | |
1311 | // per process. | |
1312 | // | |
1313 | // FIXME this is not true for 2.6!! | |
7bfe6a32 | 1314 | |
17a1ebd1 VZ |
1315 | // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY |
1316 | // to Unix priorities 20..-20 | |
a07bf2d0 | 1317 | if ( setpriority(PRIO_PROCESS, 0, -(2*(int)prio)/5 + 20) == -1 ) |
17a1ebd1 VZ |
1318 | { |
1319 | wxLogError(_("Failed to set thread priority %d."), prio); | |
7bfe6a32 JS |
1320 | } |
1321 | #else // __LINUX__ | |
518b5d2f VZ |
1322 | { |
1323 | struct sched_param sparam; | |
1324 | sparam.sched_priority = prio; | |
1325 | ||
9fc3ad34 | 1326 | if ( pthread_setschedparam(m_internal->GetId(), |
518b5d2f VZ |
1327 | SCHED_OTHER, &sparam) != 0 ) |
1328 | { | |
1329 | wxLogError(_("Failed to set thread priority %d."), prio); | |
1330 | } | |
1331 | } | |
7bfe6a32 | 1332 | #endif // __LINUX__ |
34f8c26e | 1333 | #endif // HAVE_THREAD_PRIORITY_FUNCTIONS |
518b5d2f VZ |
1334 | break; |
1335 | ||
1336 | case STATE_EXITED: | |
1337 | default: | |
223d09f6 | 1338 | wxFAIL_MSG(wxT("impossible to set thread priority in this state")); |
518b5d2f VZ |
1339 | } |
1340 | } | |
1341 | ||
1342 | unsigned int wxThread::GetPriority() const | |
1343 | { | |
1344 | wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); | |
1345 | ||
9fc3ad34 | 1346 | return m_internal->GetPriority(); |
518b5d2f VZ |
1347 | } |
1348 | ||
547b93ab | 1349 | wxThreadIdType wxThread::GetId() const |
13d068d9 | 1350 | { |
df744f4d | 1351 | return (wxThreadIdType) m_internal->GetId(); |
518b5d2f VZ |
1352 | } |
1353 | ||
1354 | // ----------------------------------------------------------------------------- | |
1355 | // pause/resume | |
1356 | // ----------------------------------------------------------------------------- | |
1357 | ||
1358 | wxThreadError wxThread::Pause() | |
1359 | { | |
4c460b34 | 1360 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, |
9a83f860 | 1361 | wxT("a thread can't pause itself") ); |
4c460b34 | 1362 | |
518b5d2f VZ |
1363 | wxCriticalSectionLocker lock(m_critsect); |
1364 | ||
9fc3ad34 | 1365 | if ( m_internal->GetState() != STATE_RUNNING ) |
518b5d2f | 1366 | { |
223d09f6 | 1367 | wxLogDebug(wxT("Can't pause thread which is not running.")); |
518b5d2f VZ |
1368 | |
1369 | return wxTHREAD_NOT_RUNNING; | |
1370 | } | |
1371 | ||
9fc3ad34 VZ |
1372 | // just set a flag, the thread will be really paused only during the next |
1373 | // call to TestDestroy() | |
1374 | m_internal->SetState(STATE_PAUSED); | |
518b5d2f VZ |
1375 | |
1376 | return wxTHREAD_NO_ERROR; | |
1377 | } | |
1378 | ||
1379 | wxThreadError wxThread::Resume() | |
1380 | { | |
4c460b34 | 1381 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, |
9a83f860 | 1382 | wxT("a thread can't resume itself") ); |
518b5d2f | 1383 | |
4c460b34 | 1384 | wxCriticalSectionLocker lock(m_critsect); |
518b5d2f | 1385 | |
4c460b34 | 1386 | wxThreadState state = m_internal->GetState(); |
9fc3ad34 VZ |
1387 | |
1388 | switch ( state ) | |
518b5d2f | 1389 | { |
9fc3ad34 | 1390 | case STATE_PAUSED: |
9a83f860 | 1391 | wxLogTrace(TRACE_THREADS, wxT("Thread %p suspended, resuming."), |
35e9c131 | 1392 | THR_ID(this)); |
9fc3ad34 VZ |
1393 | |
1394 | m_internal->Resume(); | |
1395 | ||
1396 | return wxTHREAD_NO_ERROR; | |
1397 | ||
1398 | case STATE_EXITED: | |
9a83f860 | 1399 | wxLogTrace(TRACE_THREADS, wxT("Thread %p exited, won't resume."), |
35e9c131 | 1400 | THR_ID(this)); |
9fc3ad34 | 1401 | return wxTHREAD_NO_ERROR; |
518b5d2f | 1402 | |
9fc3ad34 | 1403 | default: |
9a83f860 | 1404 | wxLogDebug(wxT("Attempt to resume a thread which is not paused.")); |
9fc3ad34 VZ |
1405 | |
1406 | return wxTHREAD_MISC_ERROR; | |
518b5d2f VZ |
1407 | } |
1408 | } | |
1409 | ||
1410 | // ----------------------------------------------------------------------------- | |
1411 | // exiting thread | |
1412 | // ----------------------------------------------------------------------------- | |
1413 | ||
9fc3ad34 | 1414 | wxThread::ExitCode wxThread::Wait() |
b568d04f | 1415 | { |
9fc3ad34 | 1416 | wxCHECK_MSG( This() != this, (ExitCode)-1, |
9a83f860 | 1417 | wxT("a thread can't wait for itself") ); |
9fc3ad34 VZ |
1418 | |
1419 | wxCHECK_MSG( !m_isDetached, (ExitCode)-1, | |
9a83f860 | 1420 | wxT("can't wait for detached thread") ); |
9fc3ad34 VZ |
1421 | |
1422 | m_internal->Wait(); | |
b568d04f | 1423 | |
9fc3ad34 | 1424 | return m_internal->GetExitCode(); |
b568d04f VZ |
1425 | } |
1426 | ||
1427 | wxThreadError wxThread::Delete(ExitCode *rc) | |
518b5d2f | 1428 | { |
4c460b34 | 1429 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, |
9a83f860 | 1430 | wxT("a thread can't delete itself") ); |
4c460b34 | 1431 | |
9e84b847 VZ |
1432 | bool isDetached = m_isDetached; |
1433 | ||
518b5d2f | 1434 | m_critsect.Enter(); |
9fc3ad34 | 1435 | wxThreadState state = m_internal->GetState(); |
518b5d2f | 1436 | |
882eefb1 | 1437 | // ask the thread to stop |
9fc3ad34 VZ |
1438 | m_internal->SetCancelFlag(); |
1439 | ||
9111db68 GL |
1440 | m_critsect.Leave(); |
1441 | ||
518b5d2f VZ |
1442 | switch ( state ) |
1443 | { | |
1444 | case STATE_NEW: | |
4c460b34 | 1445 | // we need to wake up the thread so that PthreadStart() will |
9e84b847 VZ |
1446 | // terminate - right now it's blocking on run semaphore in |
1447 | // PthreadStart() | |
4c460b34 VZ |
1448 | m_internal->SignalRun(); |
1449 | ||
1450 | // fall through | |
1451 | ||
518b5d2f VZ |
1452 | case STATE_EXITED: |
1453 | // nothing to do | |
1454 | break; | |
1455 | ||
1456 | case STATE_PAUSED: | |
9e84b847 | 1457 | // resume the thread first |
9fc3ad34 | 1458 | m_internal->Resume(); |
518b5d2f VZ |
1459 | |
1460 | // fall through | |
1461 | ||
1462 | default: | |
9e84b847 | 1463 | if ( !isDetached ) |
9fc3ad34 | 1464 | { |
9e84b847 VZ |
1465 | // wait until the thread stops |
1466 | m_internal->Wait(); | |
9fc3ad34 | 1467 | |
9e84b847 VZ |
1468 | if ( rc ) |
1469 | { | |
1470 | // return the exit code of the thread | |
1471 | *rc = m_internal->GetExitCode(); | |
1472 | } | |
9fc3ad34 | 1473 | } |
9e84b847 | 1474 | //else: can't wait for detached threads |
518b5d2f | 1475 | } |
363daf0b FM |
1476 | |
1477 | if (state == STATE_NEW) | |
1478 | return wxTHREAD_MISC_ERROR; | |
1479 | // for coherency with the MSW implementation, signal the user that | |
1480 | // Delete() was called on a thread which didn't start to run yet. | |
518b5d2f | 1481 | |
acb8423c | 1482 | return wxTHREAD_NO_ERROR; |
518b5d2f VZ |
1483 | } |
1484 | ||
1485 | wxThreadError wxThread::Kill() | |
1486 | { | |
9fc3ad34 | 1487 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, |
9a83f860 | 1488 | wxT("a thread can't kill itself") ); |
9fc3ad34 VZ |
1489 | |
1490 | switch ( m_internal->GetState() ) | |
518b5d2f VZ |
1491 | { |
1492 | case STATE_NEW: | |
1493 | case STATE_EXITED: | |
1494 | return wxTHREAD_NOT_RUNNING; | |
1495 | ||
9fc3ad34 VZ |
1496 | case STATE_PAUSED: |
1497 | // resume the thread first | |
1498 | Resume(); | |
1499 | ||
1500 | // fall through | |
1501 | ||
518b5d2f | 1502 | default: |
9fc3ad34 VZ |
1503 | #ifdef HAVE_PTHREAD_CANCEL |
1504 | if ( pthread_cancel(m_internal->GetId()) != 0 ) | |
741d91c5 | 1505 | #endif // HAVE_PTHREAD_CANCEL |
518b5d2f VZ |
1506 | { |
1507 | wxLogError(_("Failed to terminate a thread.")); | |
1508 | ||
1509 | return wxTHREAD_MISC_ERROR; | |
1510 | } | |
9fc3ad34 | 1511 | |
741d91c5 | 1512 | #ifdef HAVE_PTHREAD_CANCEL |
9fc3ad34 VZ |
1513 | if ( m_isDetached ) |
1514 | { | |
1515 | // if we use cleanup function, this will be done from | |
90350682 | 1516 | // wxPthreadCleanup() |
816a7358 | 1517 | #ifndef wxHAVE_PTHREAD_CLEANUP |
9fc3ad34 VZ |
1518 | ScheduleThreadForDeletion(); |
1519 | ||
b18cfdd9 VZ |
1520 | // don't call OnExit() here, it can only be called in the |
1521 | // threads context and we're in the context of another thread | |
9fc3ad34 VZ |
1522 | |
1523 | DeleteThread(this); | |
816a7358 | 1524 | #endif // wxHAVE_PTHREAD_CLEANUP |
9fc3ad34 VZ |
1525 | } |
1526 | else | |
1527 | { | |
1528 | m_internal->SetExitCode(EXITCODE_CANCELLED); | |
1529 | } | |
518b5d2f VZ |
1530 | |
1531 | return wxTHREAD_NO_ERROR; | |
741d91c5 | 1532 | #endif // HAVE_PTHREAD_CANCEL |
518b5d2f VZ |
1533 | } |
1534 | } | |
1535 | ||
b568d04f | 1536 | void wxThread::Exit(ExitCode status) |
518b5d2f | 1537 | { |
4c460b34 | 1538 | wxASSERT_MSG( This() == this, |
9a83f860 | 1539 | wxT("wxThread::Exit() can only be called in the context of the same thread") ); |
4c460b34 | 1540 | |
9e84b847 VZ |
1541 | if ( m_isDetached ) |
1542 | { | |
1543 | // from the moment we call OnExit(), the main program may terminate at | |
1544 | // any moment, so mark this thread as being already in process of being | |
1545 | // deleted or wxThreadModule::OnExit() will try to delete it again | |
1546 | ScheduleThreadForDeletion(); | |
1547 | } | |
9fc3ad34 VZ |
1548 | |
1549 | // don't enter m_critsect before calling OnExit() because the user code | |
1550 | // might deadlock if, for example, it signals a condition in OnExit() (a | |
1551 | // common case) while the main thread calls any of functions entering | |
1552 | // m_critsect on us (almost all of them do) | |
79b7b95a VS |
1553 | wxTRY |
1554 | { | |
1555 | OnExit(); | |
1556 | } | |
1557 | wxCATCH_ALL( wxTheApp->OnUnhandledException(); ) | |
518b5d2f | 1558 | |
9fc3ad34 VZ |
1559 | // delete C++ thread object if this is a detached thread - user is |
1560 | // responsible for doing this for joinable ones | |
1561 | if ( m_isDetached ) | |
1562 | { | |
1563 | // FIXME I'm feeling bad about it - what if another thread function is | |
1564 | // called (in another thread context) now? It will try to access | |
1565 | // half destroyed object which will probably result in something | |
1566 | // very bad - but we can't protect this by a crit section unless | |
1567 | // we make it a global object, but this would mean that we can | |
1568 | // only call one thread function at a time :-( | |
1569 | DeleteThread(this); | |
b4866582 | 1570 | pthread_setspecific(gs_keySelf, 0); |
9fc3ad34 | 1571 | } |
343b1669 RR |
1572 | else |
1573 | { | |
1574 | m_critsect.Enter(); | |
1575 | m_internal->SetState(STATE_EXITED); | |
1576 | m_critsect.Leave(); | |
1577 | } | |
9fc3ad34 VZ |
1578 | |
1579 | // terminate the thread (pthread_exit() never returns) | |
518b5d2f | 1580 | pthread_exit(status); |
9fc3ad34 | 1581 | |
9a83f860 | 1582 | wxFAIL_MSG(wxT("pthread_exit() failed")); |
518b5d2f VZ |
1583 | } |
1584 | ||
1585 | // also test whether we were paused | |
1586 | bool wxThread::TestDestroy() | |
1587 | { | |
4c460b34 | 1588 | wxASSERT_MSG( This() == this, |
9a83f860 | 1589 | wxT("wxThread::TestDestroy() can only be called in the context of the same thread") ); |
4c460b34 | 1590 | |
9fc3ad34 | 1591 | m_critsect.Enter(); |
518b5d2f | 1592 | |
9fc3ad34 | 1593 | if ( m_internal->GetState() == STATE_PAUSED ) |
518b5d2f | 1594 | { |
ad9835c9 | 1595 | m_internal->SetReallyPaused(true); |
4c460b34 | 1596 | |
9fc3ad34 VZ |
1597 | // leave the crit section or the other threads will stop too if they |
1598 | // try to call any of (seemingly harmless) IsXXX() functions while we | |
1599 | // sleep | |
518b5d2f VZ |
1600 | m_critsect.Leave(); |
1601 | ||
9fc3ad34 VZ |
1602 | m_internal->Pause(); |
1603 | } | |
1604 | else | |
1605 | { | |
1606 | // thread wasn't requested to pause, nothing to do | |
1607 | m_critsect.Leave(); | |
518b5d2f VZ |
1608 | } |
1609 | ||
9fc3ad34 | 1610 | return m_internal->WasCancelled(); |
518b5d2f VZ |
1611 | } |
1612 | ||
1613 | wxThread::~wxThread() | |
1614 | { | |
062c4861 | 1615 | m_critsect.Enter(); |
9fc3ad34 VZ |
1616 | |
1617 | // check that the thread either exited or couldn't be created | |
1618 | if ( m_internal->GetState() != STATE_EXITED && | |
1619 | m_internal->GetState() != STATE_NEW ) | |
bbfa0322 | 1620 | { |
35e9c131 VS |
1621 | wxLogDebug(wxT("The thread %p is being destroyed although it is still running! The application may crash."), |
1622 | THR_ID(this)); | |
bbfa0322 | 1623 | } |
062c4861 GL |
1624 | |
1625 | m_critsect.Leave(); | |
1626 | ||
9fc3ad34 | 1627 | delete m_internal; |
bbfa0322 | 1628 | |
518b5d2f | 1629 | // remove this thread from the global array |
25b34b26 VZ |
1630 | { |
1631 | wxMutexLocker lock(*gs_mutexAllThreads); | |
1632 | ||
1633 | gs_allThreads.Remove(this); | |
1634 | } | |
518b5d2f VZ |
1635 | } |
1636 | ||
1637 | // ----------------------------------------------------------------------------- | |
1638 | // state tests | |
1639 | // ----------------------------------------------------------------------------- | |
1640 | ||
1641 | bool wxThread::IsRunning() const | |
1642 | { | |
1643 | wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); | |
1644 | ||
9fc3ad34 | 1645 | return m_internal->GetState() == STATE_RUNNING; |
518b5d2f VZ |
1646 | } |
1647 | ||
1648 | bool wxThread::IsAlive() const | |
1649 | { | |
1650 | wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect); | |
1651 | ||
9fc3ad34 | 1652 | switch ( m_internal->GetState() ) |
518b5d2f VZ |
1653 | { |
1654 | case STATE_RUNNING: | |
1655 | case STATE_PAUSED: | |
ad9835c9 | 1656 | return true; |
518b5d2f VZ |
1657 | |
1658 | default: | |
ad9835c9 | 1659 | return false; |
518b5d2f VZ |
1660 | } |
1661 | } | |
1662 | ||
a737331d GL |
1663 | bool wxThread::IsPaused() const |
1664 | { | |
1665 | wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect); | |
1666 | ||
9fc3ad34 | 1667 | return (m_internal->GetState() == STATE_PAUSED); |
a737331d GL |
1668 | } |
1669 | ||
518b5d2f VZ |
1670 | //-------------------------------------------------------------------- |
1671 | // wxThreadModule | |
1672 | //-------------------------------------------------------------------- | |
1673 | ||
1674 | class wxThreadModule : public wxModule | |
1675 | { | |
1676 | public: | |
1677 | virtual bool OnInit(); | |
1678 | virtual void OnExit(); | |
1679 | ||
1680 | private: | |
1681 | DECLARE_DYNAMIC_CLASS(wxThreadModule) | |
1682 | }; | |
1683 | ||
1684 | IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule) | |
1685 | ||
1686 | bool wxThreadModule::OnInit() | |
1687 | { | |
58230fb1 VZ |
1688 | int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */); |
1689 | if ( rc != 0 ) | |
518b5d2f | 1690 | { |
76a6e803 | 1691 | wxLogSysError(rc, _("Thread module initialization failed: failed to create thread key")); |
518b5d2f | 1692 | |
ad9835c9 | 1693 | return false; |
518b5d2f VZ |
1694 | } |
1695 | ||
f9226383 | 1696 | wxThread::ms_idMainThread = wxThread::GetCurrentId(); |
19da4326 | 1697 | |
25b34b26 VZ |
1698 | gs_mutexAllThreads = new wxMutex(); |
1699 | ||
9fc3ad34 | 1700 | gs_mutexGui = new wxMutex(); |
518b5d2f VZ |
1701 | gs_mutexGui->Lock(); |
1702 | ||
be809868 | 1703 | gs_mutexDeleteThread = new wxMutex(); |
25b34b26 | 1704 | gs_condAllDeleted = new wxCondition(*gs_mutexDeleteThread); |
88e243b2 | 1705 | |
ad9835c9 | 1706 | return true; |
518b5d2f VZ |
1707 | } |
1708 | ||
1709 | void wxThreadModule::OnExit() | |
1710 | { | |
223d09f6 | 1711 | wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") ); |
518b5d2f | 1712 | |
9fc3ad34 VZ |
1713 | // are there any threads left which are being deleted right now? |
1714 | size_t nThreadsBeingDeleted; | |
be809868 | 1715 | |
9fc3ad34 | 1716 | { |
be809868 | 1717 | wxMutexLocker lock( *gs_mutexDeleteThread ); |
9fc3ad34 | 1718 | nThreadsBeingDeleted = gs_nThreadsBeingDeleted; |
9fc3ad34 | 1719 | |
be809868 | 1720 | if ( nThreadsBeingDeleted > 0 ) |
9e84b847 | 1721 | { |
2b5f62a0 | 1722 | wxLogTrace(TRACE_THREADS, |
9a83f860 | 1723 | wxT("Waiting for %lu threads to disappear"), |
2b5f62a0 | 1724 | (unsigned long)nThreadsBeingDeleted); |
9fc3ad34 | 1725 | |
be809868 VZ |
1726 | // have to wait until all of them disappear |
1727 | gs_condAllDeleted->Wait(); | |
1728 | } | |
9fc3ad34 VZ |
1729 | } |
1730 | ||
25b34b26 VZ |
1731 | size_t count; |
1732 | ||
4c460b34 | 1733 | { |
25b34b26 VZ |
1734 | wxMutexLocker lock(*gs_mutexAllThreads); |
1735 | ||
1736 | // terminate any threads left | |
1737 | count = gs_allThreads.GetCount(); | |
1738 | if ( count != 0u ) | |
1739 | { | |
1740 | wxLogDebug(wxT("%lu threads were not terminated by the application."), | |
1741 | (unsigned long)count); | |
1742 | } | |
1743 | } // unlock mutex before deleting the threads as they lock it in their dtor | |
518b5d2f VZ |
1744 | |
1745 | for ( size_t n = 0u; n < count; n++ ) | |
1746 | { | |
bbfa0322 VZ |
1747 | // Delete calls the destructor which removes the current entry. We |
1748 | // should only delete the first one each time. | |
0ac77ef5 | 1749 | gs_allThreads[0]->Delete(); |
518b5d2f VZ |
1750 | } |
1751 | ||
25b34b26 VZ |
1752 | delete gs_mutexAllThreads; |
1753 | ||
518b5d2f VZ |
1754 | // destroy GUI mutex |
1755 | gs_mutexGui->Unlock(); | |
518b5d2f VZ |
1756 | delete gs_mutexGui; |
1757 | ||
1758 | // and free TLD slot | |
1759 | (void)pthread_key_delete(gs_keySelf); | |
be809868 VZ |
1760 | |
1761 | delete gs_condAllDeleted; | |
1762 | delete gs_mutexDeleteThread; | |
518b5d2f VZ |
1763 | } |
1764 | ||
1765 | // ---------------------------------------------------------------------------- | |
1766 | // global functions | |
1767 | // ---------------------------------------------------------------------------- | |
1768 | ||
9fc3ad34 VZ |
1769 | static void ScheduleThreadForDeletion() |
1770 | { | |
be809868 | 1771 | wxMutexLocker lock( *gs_mutexDeleteThread ); |
9fc3ad34 VZ |
1772 | |
1773 | gs_nThreadsBeingDeleted++; | |
1774 | ||
9a83f860 | 1775 | wxLogTrace(TRACE_THREADS, wxT("%lu thread%s waiting to be deleted"), |
2b5f62a0 | 1776 | (unsigned long)gs_nThreadsBeingDeleted, |
9a83f860 | 1777 | gs_nThreadsBeingDeleted == 1 ? wxT("") : wxT("s")); |
9fc3ad34 VZ |
1778 | } |
1779 | ||
1780 | static void DeleteThread(wxThread *This) | |
1781 | { | |
35e9c131 | 1782 | wxLogTrace(TRACE_THREADS, wxT("Thread %p auto deletes."), THR_ID(This)); |
9fc3ad34 | 1783 | |
be809868 | 1784 | delete This; |
9fc3ad34 | 1785 | |
2450225e VZ |
1786 | // only lock gs_mutexDeleteThread after deleting the thread to avoid |
1787 | // calling out into user code with it locked as this may result in | |
1788 | // deadlocks if the thread dtor deletes another thread (see #11501) | |
1789 | wxMutexLocker locker( *gs_mutexDeleteThread ); | |
1790 | ||
be809868 | 1791 | wxCHECK_RET( gs_nThreadsBeingDeleted > 0, |
9a83f860 | 1792 | wxT("no threads scheduled for deletion, yet we delete one?") ); |
9fc3ad34 | 1793 | |
9a83f860 | 1794 | wxLogTrace(TRACE_THREADS, wxT("%lu threads remain scheduled for deletion."), |
2b5f62a0 | 1795 | (unsigned long)gs_nThreadsBeingDeleted - 1); |
4c460b34 | 1796 | |
9fc3ad34 VZ |
1797 | if ( !--gs_nThreadsBeingDeleted ) |
1798 | { | |
1799 | // no more threads left, signal it | |
1800 | gs_condAllDeleted->Signal(); | |
9fc3ad34 VZ |
1801 | } |
1802 | } | |
1803 | ||
d254213e | 1804 | void wxMutexGuiEnterImpl() |
518b5d2f | 1805 | { |
9fc3ad34 | 1806 | gs_mutexGui->Lock(); |
518b5d2f VZ |
1807 | } |
1808 | ||
d254213e | 1809 | void wxMutexGuiLeaveImpl() |
518b5d2f | 1810 | { |
9fc3ad34 | 1811 | gs_mutexGui->Unlock(); |
518b5d2f | 1812 | } |
80cb83be | 1813 | |
9e84b847 VZ |
1814 | // ---------------------------------------------------------------------------- |
1815 | // include common implementation code | |
1816 | // ---------------------------------------------------------------------------- | |
1817 | ||
1818 | #include "wx/thrimpl.cpp" | |
1819 | ||
1820 | #endif // wxUSE_THREADS |