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