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