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