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