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