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