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