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