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