]> git.saurik.com Git - wxWidgets.git/blame - src/unix/threadpsx.cpp
- Added wxAddProcessCallbackForPid function
[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)
518b5d2f
VZ
13// Licence: wxWindows licence
14/////////////////////////////////////////////////////////////////////////////
15
16// ============================================================================
17// declaration
18// ============================================================================
19
20// ----------------------------------------------------------------------------
21// headers
22// ----------------------------------------------------------------------------
23
24#ifdef __GNUG__
25 #pragma implementation "thread.h"
26#endif
27
fcc3d7cb 28#include "wx/defs.h"
518b5d2f 29
7bcb11d3 30#if wxUSE_THREADS
518b5d2f 31
7bcb11d3 32#include "wx/thread.h"
518b5d2f
VZ
33#include "wx/module.h"
34#include "wx/utils.h"
35#include "wx/log.h"
36#include "wx/intl.h"
37#include "wx/dynarray.h"
be809868 38#include "wx/timer.h"
518b5d2f
VZ
39
40#include <stdio.h>
41#include <unistd.h>
42#include <pthread.h>
43#include <errno.h>
44#include <time.h>
7bcb11d3 45#if HAVE_SCHED_H
518b5d2f
VZ
46 #include <sched.h>
47#endif
48
ef8d96c2
VZ
49#ifdef HAVE_THR_SETCONCURRENCY
50 #include <thread.h>
51#endif
52
53// we use wxFFile under Linux in GetCPUCount()
54#ifdef __LINUX__
55 #include "wx/ffile.h"
7bfe6a32
JS
56 // For setpriority.
57 #include <sys/time.h>
58 #include <sys/resource.h>
ef8d96c2
VZ
59#endif
60
518b5d2f
VZ
61// ----------------------------------------------------------------------------
62// constants
63// ----------------------------------------------------------------------------
64
882eefb1
VZ
65// the possible states of the thread and transitions from them
66enum wxThreadState
518b5d2f
VZ
67{
68 STATE_NEW, // didn't start execution yet (=> RUNNING)
882eefb1
VZ
69 STATE_RUNNING, // running (=> PAUSED or EXITED)
70 STATE_PAUSED, // suspended (=> RUNNING or EXITED)
71 STATE_EXITED // thread doesn't exist any more
518b5d2f
VZ
72};
73
9fc3ad34
VZ
74// the exit value of a thread which has been cancelled
75static const wxThread::ExitCode EXITCODE_CANCELLED = (wxThread::ExitCode)-1;
76
9e84b847 77// trace mask for wxThread operations
9fc3ad34
VZ
78#define TRACE_THREADS _T("thread")
79
9e84b847
VZ
80// you can get additional debugging messages for the semaphore operations
81#define TRACE_SEMA _T("semaphore")
82
9fc3ad34
VZ
83// ----------------------------------------------------------------------------
84// private functions
85// ----------------------------------------------------------------------------
86
87static void ScheduleThreadForDeletion();
88static void DeleteThread(wxThread *This);
89
882eefb1 90// ----------------------------------------------------------------------------
9e84b847 91// private classes
882eefb1
VZ
92// ----------------------------------------------------------------------------
93
9e84b847 94// an (non owning) array of pointers to threads
518b5d2f
VZ
95WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
96
9e84b847
VZ
97// an entry for a thread we can wait for
98
518b5d2f
VZ
99// -----------------------------------------------------------------------------
100// global data
101// -----------------------------------------------------------------------------
102
103// we keep the list of all threads created by the application to be able to
104// terminate them on exit if there are some left - otherwise the process would
105// be left in memory
106static wxArrayThread gs_allThreads;
107
108// the id of the main thread
109static pthread_t gs_tidMain;
110
111// the key for the pointer to the associated wxThread object
112static pthread_key_t gs_keySelf;
113
9fc3ad34
VZ
114// the number of threads which are being deleted - the program won't exit
115// until there are any left
116static size_t gs_nThreadsBeingDeleted = 0;
117
118// a mutex to protect gs_nThreadsBeingDeleted
be809868 119static wxMutex *gs_mutexDeleteThread = (wxMutex *)NULL;
9fc3ad34
VZ
120
121// and a condition variable which will be signaled when all
122// gs_nThreadsBeingDeleted will have been deleted
123static wxCondition *gs_condAllDeleted = (wxCondition *)NULL;
124
125#if wxUSE_GUI
126 // this mutex must be acquired before any call to a GUI function
127 static wxMutex *gs_mutexGui;
128#endif // wxUSE_GUI
518b5d2f 129
9e84b847
VZ
130// when we wait for a thread to exit, we're blocking on a condition which the
131// thread signals in its SignalExit() method -- but this condition can't be a
132// member of the thread itself as a detached thread may delete itself at any
133// moment and accessing the condition member of the thread after this would
134// result in a disaster
135//
136// so instead we maintain a global list of the structs below for the threads
137// we're interested in waiting on
138
518b5d2f 139// ============================================================================
8d5eff60 140// wxMutex implementation
518b5d2f
VZ
141// ============================================================================
142
8d5eff60
VZ
143// ----------------------------------------------------------------------------
144// wxMutexInternal
145// ----------------------------------------------------------------------------
518b5d2f 146
9e84b847
VZ
147// this is a simple wrapper around pthread_mutex_t which provides error
148// checking
518b5d2f
VZ
149class wxMutexInternal
150{
151public:
9e84b847 152 wxMutexInternal(wxMutexType mutexType);
8d5eff60
VZ
153 ~wxMutexInternal();
154
155 wxMutexError Lock();
156 wxMutexError TryLock();
157 wxMutexError Unlock();
158
9e84b847
VZ
159 bool IsOk() const { return m_isOk; }
160
8d5eff60 161private:
9fc3ad34 162 pthread_mutex_t m_mutex;
9e84b847 163 bool m_isOk;
be809868 164
9e84b847 165 // wxConditionInternal uses our m_mutex
be809868 166 friend class wxConditionInternal;
518b5d2f
VZ
167};
168
9e84b847 169wxMutexInternal::wxMutexInternal(wxMutexType mutexType)
518b5d2f 170{
9e84b847
VZ
171 int err;
172 switch ( mutexType )
173 {
174 case wxMUTEX_RECURSIVE:
175 // support recursive locks like Win32, i.e. a thread can lock a
176 // mutex which it had itself already locked
177 //
178 // unfortunately initialization of recursive mutexes is non
179 // portable, so try several methods
d9b9876f 180#ifdef HAVE_PTHREAD_MUTEXATTR_T
9e84b847
VZ
181 {
182 pthread_mutexattr_t attr;
183 pthread_mutexattr_init(&attr);
184 pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
d9b9876f 185
9e84b847
VZ
186 err = pthread_mutex_init(&m_mutex, &attr);
187 }
d9b9876f 188#elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
9e84b847
VZ
189 // we can use this only as initializer so we have to assign it
190 // first to a temp var - assigning directly to m_mutex wouldn't
191 // even compile
192 {
193 pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
194 m_mutex = mutex;
195 }
d9b9876f 196#else // no recursive mutexes
9e84b847 197 err = EINVAL;
d9b9876f 198#endif // HAVE_PTHREAD_MUTEXATTR_T/...
9e84b847
VZ
199 break;
200
201 default:
202 wxFAIL_MSG( _T("unknown mutex type") );
203 // fall through
204
205 case wxMUTEX_DEFAULT:
206 err = pthread_mutex_init(&m_mutex, NULL);
207 break;
208 }
209
210 m_isOk = err == 0;
211 if ( !m_isOk )
212 {
401eb3de 213 wxLogApiError( wxT("pthread_mutex_init()"), err);
9e84b847 214 }
8d5eff60
VZ
215}
216
217wxMutexInternal::~wxMutexInternal()
218{
9e84b847
VZ
219 if ( m_isOk )
220 {
221 int err = pthread_mutex_destroy(&m_mutex);
222 if ( err != 0 )
223 {
401eb3de 224 wxLogApiError( wxT("pthread_mutex_destroy()"), err);
9e84b847
VZ
225 }
226 }
8d5eff60
VZ
227}
228
229wxMutexError wxMutexInternal::Lock()
230{
231 int err = pthread_mutex_lock(&m_mutex);
232 switch ( err )
233 {
234 case EDEADLK:
9e84b847
VZ
235 // only error checking mutexes return this value and so it's an
236 // unexpected situation -- hence use assert, not wxLogDebug
237 wxFAIL_MSG( _T("mutex deadlock prevented") );
8d5eff60
VZ
238 return wxMUTEX_DEAD_LOCK;
239
8d5eff60 240 case EINVAL:
9e84b847
VZ
241 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
242 break;
8d5eff60
VZ
243
244 case 0:
245 return wxMUTEX_NO_ERROR;
9e84b847
VZ
246
247 default:
248 wxLogApiError(_T("pthread_mutex_lock()"), err);
8d5eff60 249 }
9e84b847
VZ
250
251 return wxMUTEX_MISC_ERROR;
8d5eff60
VZ
252}
253
254wxMutexError wxMutexInternal::TryLock()
255{
256 int err = pthread_mutex_trylock(&m_mutex);
257 switch ( err )
258 {
259 case EBUSY:
9e84b847
VZ
260 // not an error: mutex is already locked, but we're prepared for
261 // this
8d5eff60
VZ
262 return wxMUTEX_BUSY;
263
8d5eff60 264 case EINVAL:
9e84b847
VZ
265 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
266 break;
8d5eff60
VZ
267
268 case 0:
269 return wxMUTEX_NO_ERROR;
9e84b847
VZ
270
271 default:
272 wxLogApiError(_T("pthread_mutex_trylock()"), err);
8d5eff60 273 }
9e84b847
VZ
274
275 return wxMUTEX_MISC_ERROR;
8d5eff60
VZ
276}
277
278wxMutexError wxMutexInternal::Unlock()
279{
280 int err = pthread_mutex_unlock(&m_mutex);
281 switch ( err )
282 {
283 case EPERM:
284 // we don't own the mutex
285 return wxMUTEX_UNLOCKED;
286
8d5eff60 287 case EINVAL:
9e84b847
VZ
288 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
289 break;
8d5eff60
VZ
290
291 case 0:
292 return wxMUTEX_NO_ERROR;
518b5d2f 293
9e84b847
VZ
294 default:
295 wxLogApiError(_T("pthread_mutex_unlock()"), err);
518b5d2f
VZ
296 }
297
9e84b847 298 return wxMUTEX_MISC_ERROR;
518b5d2f
VZ
299}
300
be809868 301// ===========================================================================
8d5eff60 302// wxCondition implementation
be809868 303// ===========================================================================
8d5eff60 304
be809868 305// ---------------------------------------------------------------------------
8d5eff60 306// wxConditionInternal
be809868 307// ---------------------------------------------------------------------------
518b5d2f 308
9e84b847
VZ
309// this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
310// with a pthread_mutex_t)
518b5d2f
VZ
311class wxConditionInternal
312{
313public:
c112e100 314 wxConditionInternal(wxMutex& mutex);
9fc3ad34
VZ
315 ~wxConditionInternal();
316
9e84b847 317 bool IsOk() const { return m_isOk && m_mutex.IsOk(); }
4c460b34 318
9e84b847
VZ
319 wxCondError Wait();
320 wxCondError WaitTimeout(unsigned long milliseconds);
547b93ab 321
9e84b847
VZ
322 wxCondError Signal();
323 wxCondError Broadcast();
4c460b34 324
be809868 325private:
c112e100 326 // get the POSIX mutex associated with us
9e84b847 327 pthread_mutex_t *GetPMutex() const { return &m_mutex.m_internal->m_mutex; }
518b5d2f 328
c112e100 329 wxMutex& m_mutex;
be809868 330 pthread_cond_t m_cond;
9e84b847
VZ
331
332 bool m_isOk;
8d5eff60 333};
547b93ab 334
c112e100
VZ
335wxConditionInternal::wxConditionInternal(wxMutex& mutex)
336 : m_mutex(mutex)
9fc3ad34 337{
9e84b847 338 int err = pthread_cond_init(&m_cond, NULL /* default attributes */);
9fc3ad34 339
9e84b847 340 m_isOk = err == 0;
9fc3ad34 341
9e84b847 342 if ( !m_isOk )
9fc3ad34 343 {
9e84b847 344 wxLogApiError(_T("pthread_cond_init()"), err);
9fc3ad34
VZ
345 }
346}
347
9e84b847 348wxConditionInternal::~wxConditionInternal()
4c460b34 349{
9e84b847 350 if ( m_isOk )
c112e100 351 {
9e84b847
VZ
352 int err = pthread_cond_destroy(&m_cond);
353 if ( err != 0 )
354 {
355 wxLogApiError(_T("pthread_cond_destroy()"), err);
356 }
c112e100 357 }
be809868 358}
4c460b34 359
9e84b847 360wxCondError wxConditionInternal::Wait()
be809868 361{
9e84b847
VZ
362 int err = pthread_cond_wait(&m_cond, GetPMutex());
363 if ( err != 0 )
364 {
365 wxLogApiError(_T("pthread_cond_wait()"), err);
4c460b34 366
9e84b847 367 return wxCOND_MISC_ERROR;
be809868 368 }
4c460b34 369
9e84b847 370 return wxCOND_NO_ERROR;
be809868 371}
60ce696e 372
9e84b847 373wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds)
be809868 374{
be809868 375 wxLongLong curtime = wxGetLocalTimeMillis();
9e84b847 376 curtime += milliseconds;
be809868
VZ
377 wxLongLong temp = curtime / 1000;
378 int sec = temp.GetLo();
9e84b847 379 temp *= 1000;
be809868
VZ
380 temp = curtime - temp;
381 int millis = temp.GetLo();
382
383 timespec tspec;
384
385 tspec.tv_sec = sec;
386 tspec.tv_nsec = millis * 1000L * 1000L;
4c460b34 387
9e84b847
VZ
388 int err = pthread_cond_timedwait( &m_cond, GetPMutex(), &tspec );
389 switch ( err )
390 {
391 case ETIMEDOUT:
392 return wxCOND_TIMEOUT;
393
394 case 0:
395 return wxCOND_NO_ERROR;
396
397 default:
398 wxLogApiError(_T("pthread_cond_timedwait()"), err);
399 }
400
401 return wxCOND_MISC_ERROR;
9fc3ad34
VZ
402}
403
9e84b847 404wxCondError wxConditionInternal::Signal()
9fc3ad34 405{
9e84b847
VZ
406 int err = pthread_cond_signal(&m_cond);
407 if ( err != 0 )
408 {
409 wxLogApiError(_T("pthread_cond_signal()"), err);
410
411 return wxCOND_MISC_ERROR;
412 }
413
414 return wxCOND_NO_ERROR;
be809868 415}
547b93ab 416
9e84b847 417wxCondError wxConditionInternal::Broadcast()
be809868 418{
9e84b847
VZ
419 int err = pthread_cond_broadcast(&m_cond);
420 if ( err != 0 )
421 {
422 wxLogApiError(_T("pthread_cond_broadcast()"), err);
423
424 return wxCOND_MISC_ERROR;
425 }
426
427 return wxCOND_NO_ERROR;
be809868
VZ
428}
429
430// ===========================================================================
431// wxSemaphore implementation
432// ===========================================================================
9fc3ad34 433
be809868
VZ
434// ---------------------------------------------------------------------------
435// wxSemaphoreInternal
436// ---------------------------------------------------------------------------
437
9e84b847
VZ
438// we implement the semaphores using mutexes and conditions instead of using
439// the sem_xxx() POSIX functions because they're not widely available and also
440// because it's impossible to implement WaitTimeout() using them
be809868
VZ
441class wxSemaphoreInternal
442{
443public:
9e84b847 444 wxSemaphoreInternal(int initialcount, int maxcount);
be809868 445
9e84b847 446 bool IsOk() const { return m_isOk; }
be809868 447
9e84b847
VZ
448 wxSemaError Wait();
449 wxSemaError TryWait();
450 wxSemaError WaitTimeout(unsigned long milliseconds);
be809868 451
9e84b847 452 wxSemaError Post();
be809868
VZ
453
454private:
455 wxMutex m_mutex;
456 wxCondition m_cond;
457
9e84b847
VZ
458 size_t m_count,
459 m_maxcount;
460
461 bool m_isOk;
be809868
VZ
462};
463
9e84b847 464wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
c112e100 465 : m_cond(m_mutex)
be809868
VZ
466{
467
9e84b847
VZ
468 if ( (initialcount < 0 || maxcount < 0) ||
469 ((maxcount > 0) && (initialcount > maxcount)) )
470 {
471 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
472
473 m_isOk = FALSE;
474 }
475 else
be809868 476 {
9e84b847
VZ
477 m_maxcount = (size_t)maxcount;
478 m_count = (size_t)initialcount;
547b93ab 479 }
547b93ab 480
9e84b847 481 m_isOk = m_mutex.IsOk() && m_cond.IsOk();
be809868 482}
547b93ab 483
9e84b847 484wxSemaError wxSemaphoreInternal::Wait()
be809868 485{
cd10339a 486 wxMutexLocker locker(m_mutex);
60ce696e 487
9e84b847 488 while ( m_count == 0 )
9fc3ad34 489 {
9e84b847
VZ
490 wxLogTrace(TRACE_SEMA,
491 "Thread %ld waiting for semaphore to become signalled",
492 wxThread::GetCurrentId());
493
494 if ( m_cond.Wait() != wxCOND_NO_ERROR )
495 return wxSEMA_MISC_ERROR;
496
497 wxLogTrace(TRACE_SEMA,
2b5f62a0
VZ
498 "Thread %ld finished waiting for semaphore, count = %lu",
499 wxThread::GetCurrentId(), (unsigned long)m_count);
9fc3ad34 500 }
be809868 501
9e84b847
VZ
502 m_count--;
503
504 return wxSEMA_NO_ERROR;
be809868
VZ
505}
506
9e84b847 507wxSemaError wxSemaphoreInternal::TryWait()
be809868 508{
cd10339a 509 wxMutexLocker locker(m_mutex);
be809868 510
9e84b847
VZ
511 if ( m_count == 0 )
512 return wxSEMA_BUSY;
be809868 513
9e84b847 514 m_count--;
be809868 515
9e84b847 516 return wxSEMA_NO_ERROR;
be809868
VZ
517}
518
9e84b847 519wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds)
be809868 520{
cd10339a 521 wxMutexLocker locker(m_mutex);
be809868
VZ
522
523 wxLongLong startTime = wxGetLocalTimeMillis();
524
9e84b847 525 while ( m_count == 0 )
9fc3ad34 526 {
be809868 527 wxLongLong elapsed = wxGetLocalTimeMillis() - startTime;
9e84b847 528 long remainingTime = (long)milliseconds - (long)elapsed.GetLo();
be809868 529 if ( remainingTime <= 0 )
9e84b847
VZ
530 {
531 // timeout
532 return wxSEMA_TIMEOUT;
533 }
be809868 534
de628f98 535 if ( m_cond.WaitTimeout(remainingTime) != wxCOND_NO_ERROR )
9e84b847 536 return wxSEMA_MISC_ERROR;
9fc3ad34 537 }
8d5eff60 538
9e84b847 539 m_count--;
be809868 540
9e84b847 541 return wxSEMA_NO_ERROR;
be809868
VZ
542}
543
9e84b847 544wxSemaError wxSemaphoreInternal::Post()
be809868 545{
cd10339a 546 wxMutexLocker locker(m_mutex);
be809868 547
9e84b847 548 if ( m_maxcount > 0 && m_count == m_maxcount )
60ce696e 549 {
9e84b847 550 return wxSEMA_OVERFLOW;
60ce696e 551 }
be809868 552
9e84b847 553 m_count++;
518b5d2f 554
9e84b847 555 wxLogTrace(TRACE_SEMA,
2b5f62a0
VZ
556 "Thread %ld about to signal semaphore, count = %lu",
557 wxThread::GetCurrentId(), (unsigned long)m_count);
558
9e84b847
VZ
559 return m_cond.Signal() == wxCOND_NO_ERROR ? wxSEMA_NO_ERROR
560 : wxSEMA_MISC_ERROR;
518b5d2f
VZ
561}
562
be809868 563// ===========================================================================
8d5eff60 564// wxThread implementation
be809868 565// ===========================================================================
518b5d2f 566
295272bd
VZ
567// the thread callback functions must have the C linkage
568extern "C"
569{
570
90350682 571#if HAVE_THREAD_CLEANUP_FUNCTIONS
295272bd
VZ
572 // thread exit function
573 void wxPthreadCleanup(void *ptr);
574#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
90350682 575
295272bd 576void *wxPthreadStart(void *ptr);
90350682 577
295272bd 578} // extern "C"
90350682 579
8d5eff60
VZ
580// ----------------------------------------------------------------------------
581// wxThreadInternal
582// ----------------------------------------------------------------------------
583
518b5d2f
VZ
584class wxThreadInternal
585{
586public:
587 wxThreadInternal();
588 ~wxThreadInternal();
589
590 // thread entry function
295272bd 591 static void *PthreadStart(wxThread *thread);
518b5d2f
VZ
592
593 // thread actions
594 // start the thread
595 wxThreadError Run();
9e84b847
VZ
596 // unblock the thread allowing it to run
597 void SignalRun() { m_semRun.Post(); }
518b5d2f 598 // ask the thread to terminate
882eefb1 599 void Wait();
518b5d2f
VZ
600 // go to sleep until Resume() is called
601 void Pause();
602 // resume the thread
603 void Resume();
604
605 // accessors
606 // priority
607 int GetPriority() const { return m_prio; }
608 void SetPriority(int prio) { m_prio = prio; }
609 // state
882eefb1 610 wxThreadState GetState() const { return m_state; }
9e84b847
VZ
611 void SetState(wxThreadState state)
612 {
613#ifdef __WXDEBUG__
614 static const wxChar *stateNames[] =
615 {
616 _T("NEW"),
617 _T("RUNNING"),
618 _T("PAUSED"),
619 _T("EXITED"),
620 };
621
622 wxLogTrace(TRACE_THREADS, _T("Thread %ld: %s => %s."),
2b5f62a0 623 (long)GetId(), stateNames[m_state], stateNames[state]);
9e84b847
VZ
624#endif // __WXDEBUG__
625
626 m_state = state;
627 }
518b5d2f 628 // id
882eefb1
VZ
629 pthread_t GetId() const { return m_threadId; }
630 pthread_t *GetIdPtr() { return &m_threadId; }
518b5d2f 631 // "cancelled" flag
882eefb1 632 void SetCancelFlag() { m_cancelled = TRUE; }
518b5d2f 633 bool WasCancelled() const { return m_cancelled; }
9fc3ad34
VZ
634 // exit code
635 void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }
636 wxThread::ExitCode GetExitCode() const { return m_exitcode; }
637
4c460b34
VZ
638 // the pause flag
639 void SetReallyPaused(bool paused) { m_isPaused = paused; }
640 bool IsReallyPaused() const { return m_isPaused; }
641
9fc3ad34 642 // tell the thread that it is a detached one
4c460b34
VZ
643 void Detach()
644 {
9e84b847
VZ
645 wxCriticalSectionLocker lock(m_csJoinFlag);
646
647 m_shouldBeJoined = FALSE;
4c460b34
VZ
648 m_isDetached = TRUE;
649 }
518b5d2f 650
90350682
VZ
651#if HAVE_THREAD_CLEANUP_FUNCTIONS
652 // this is used by wxPthreadCleanup() only
653 static void Cleanup(wxThread *thread);
654#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
655
518b5d2f 656private:
882eefb1
VZ
657 pthread_t m_threadId; // id of the thread
658 wxThreadState m_state; // see wxThreadState enum
659 int m_prio; // in wxWindows units: from 0 to 100
518b5d2f 660
9fc3ad34 661 // this flag is set when the thread should terminate
518b5d2f
VZ
662 bool m_cancelled;
663
be809868 664 // this flag is set when the thread is blocking on m_semSuspend
4c460b34
VZ
665 bool m_isPaused;
666
9fc3ad34
VZ
667 // the thread exit code - only used for joinable (!detached) threads and
668 // is only valid after the thread termination
669 wxThread::ExitCode m_exitcode;
670
671 // many threads may call Wait(), but only one of them should call
672 // pthread_join(), so we have to keep track of this
673 wxCriticalSection m_csJoinFlag;
674 bool m_shouldBeJoined;
4c460b34 675 bool m_isDetached;
9fc3ad34 676
be809868 677 // this semaphore is posted by Run() and the threads Entry() is not
9fc3ad34 678 // called before it is done
be809868 679 wxSemaphore m_semRun;
9fc3ad34
VZ
680
681 // this one is signaled when the thread should resume after having been
682 // Pause()d
be809868 683 wxSemaphore m_semSuspend;
518b5d2f
VZ
684};
685
9fc3ad34
VZ
686// ----------------------------------------------------------------------------
687// thread startup and exit functions
688// ----------------------------------------------------------------------------
689
295272bd
VZ
690void *wxPthreadStart(void *ptr)
691{
692 return wxThreadInternal::PthreadStart((wxThread *)ptr);
693}
694
695void *wxThreadInternal::PthreadStart(wxThread *thread)
518b5d2f 696{
9fc3ad34 697 wxThreadInternal *pthread = thread->m_internal;
518b5d2f 698
2b5f62a0
VZ
699#ifdef __VMS
700 wxLogTrace(TRACE_THREADS, _T("Thread %ld started."), (long long)pthread->GetId());
701#else
702 wxLogTrace(TRACE_THREADS, _T("Thread %ld started."), (long)pthread->GetId());
703#endif
704
9fc3ad34
VZ
705 // associate the thread pointer with the newly created thread so that
706 // wxThread::This() will work
862cc6f9
VZ
707 int rc = pthread_setspecific(gs_keySelf, thread);
708 if ( rc != 0 )
518b5d2f 709 {
58230fb1 710 wxLogSysError(rc, _("Cannot start thread: error writing TLS"));
518b5d2f
VZ
711
712 return (void *)-1;
713 }
9fc3ad34 714
4c460b34
VZ
715 // have to declare this before pthread_cleanup_push() which defines a
716 // block!
717 bool dontRunAtAll;
718
5092b3ad 719#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34
VZ
720 // install the cleanup handler which will be called if the thread is
721 // cancelled
295272bd 722 pthread_cleanup_push(wxPthreadCleanup, thread);
9fc3ad34 723#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f 724
be809868
VZ
725 // wait for the semaphore to be posted from Run()
726 pthread->m_semRun.Wait();
518b5d2f 727
4c460b34
VZ
728 // test whether we should run the run at all - may be it was deleted
729 // before it started to Run()?
730 {
731 wxCriticalSectionLocker lock(thread->m_critsect);
9fc3ad34 732
4c460b34
VZ
733 dontRunAtAll = pthread->GetState() == STATE_NEW &&
734 pthread->WasCancelled();
735 }
9fc3ad34 736
4c460b34 737 if ( !dontRunAtAll )
9fc3ad34 738 {
4c460b34 739 // call the main entry
9e84b847 740 wxLogTrace(TRACE_THREADS, _T("Thread %ld about to enter its Entry()."),
2b5f62a0
VZ
741#ifdef __VMS
742 (long long)pthread->GetId());
743#else
744 (long)pthread->GetId());
745#endif
746
4c460b34 747 pthread->m_exitcode = thread->Entry();
5092b3ad 748
9e84b847 749 wxLogTrace(TRACE_THREADS, _T("Thread %ld Entry() returned %lu."),
2b5f62a0
VZ
750#ifdef __VMS
751 (long long)pthread->GetId(), (unsigned long)pthread->m_exitcode);
752#else
753 (long)pthread->GetId(), (unsigned long)pthread->m_exitcode);
754#endif
755
4c460b34
VZ
756 {
757 wxCriticalSectionLocker lock(thread->m_critsect);
758
4c460b34 759 // change the state of the thread to "exited" so that
90350682 760 // wxPthreadCleanup handler won't do anything from now (if it's
4c460b34
VZ
761 // called before we do pthread_cleanup_pop below)
762 pthread->SetState(STATE_EXITED);
763 }
9fc3ad34
VZ
764 }
765
766 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
767 // contains the matching '}' for the '{' in push, so they must be used
768 // in the same block!
5092b3ad 769#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34 770 // remove the cleanup handler without executing it
062c4861 771 pthread_cleanup_pop(FALSE);
9fc3ad34 772#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f 773
4c460b34
VZ
774 if ( dontRunAtAll )
775 {
9e84b847 776 // FIXME: deleting a possibly joinable thread here???
4c460b34 777 delete thread;
518b5d2f 778
4c460b34
VZ
779 return EXITCODE_CANCELLED;
780 }
781 else
782 {
783 // terminate the thread
784 thread->Exit(pthread->m_exitcode);
785
786 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
518b5d2f 787
4c460b34
VZ
788 return NULL;
789 }
518b5d2f
VZ
790}
791
5092b3ad 792#if HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 793
9fc3ad34 794// this handler is called when the thread is cancelled
90350682 795extern "C" void wxPthreadCleanup(void *ptr)
5092b3ad 796{
90350682
VZ
797 wxThreadInternal::Cleanup((wxThread *)ptr);
798}
5092b3ad 799
90350682
VZ
800void wxThreadInternal::Cleanup(wxThread *thread)
801{
9fc3ad34
VZ
802 {
803 wxCriticalSectionLocker lock(thread->m_critsect);
804 if ( thread->m_internal->GetState() == STATE_EXITED )
805 {
806 // thread is already considered as finished.
807 return;
808 }
809 }
5092b3ad 810
9fc3ad34
VZ
811 // exit the thread gracefully
812 thread->Exit(EXITCODE_CANCELLED);
813}
5092b3ad 814
9fc3ad34 815#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 816
9fc3ad34
VZ
817// ----------------------------------------------------------------------------
818// wxThreadInternal
819// ----------------------------------------------------------------------------
5092b3ad 820
518b5d2f
VZ
821wxThreadInternal::wxThreadInternal()
822{
823 m_state = STATE_NEW;
824 m_cancelled = FALSE;
bbfa0322
VZ
825 m_prio = WXTHREAD_DEFAULT_PRIORITY;
826 m_threadId = 0;
9fc3ad34 827 m_exitcode = 0;
518b5d2f 828
be809868 829 // set to TRUE only when the thread starts waiting on m_semSuspend
4c460b34
VZ
830 m_isPaused = FALSE;
831
9fc3ad34
VZ
832 // defaults for joinable threads
833 m_shouldBeJoined = TRUE;
4c460b34 834 m_isDetached = FALSE;
518b5d2f
VZ
835}
836
837wxThreadInternal::~wxThreadInternal()
838{
518b5d2f
VZ
839}
840
841wxThreadError wxThreadInternal::Run()
842{
843 wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
9fc3ad34 844 wxT("thread may only be started once after Create()") );
518b5d2f 845
9fc3ad34 846 SetState(STATE_RUNNING);
518b5d2f 847
9e84b847
VZ
848 // wake up threads waiting for our start
849 SignalRun();
850
518b5d2f 851 return wxTHREAD_NO_ERROR;
518b5d2f
VZ
852}
853
882eefb1 854void wxThreadInternal::Wait()
518b5d2f 855{
9e84b847
VZ
856 wxCHECK_RET( !m_isDetached, _T("can't wait for a detached thread") );
857
518b5d2f
VZ
858 // if the thread we're waiting for is waiting for the GUI mutex, we will
859 // deadlock so make sure we release it temporarily
860 if ( wxThread::IsMain() )
861 wxMutexGuiLeave();
862
547b93ab 863 wxLogTrace(TRACE_THREADS,
2b5f62a0
VZ
864#ifdef __VMS
865 _T("Starting to wait for thread %ld to exit."), (long long)GetId());
866#else
867 _T("Starting to wait for thread %ld to exit."), (long)GetId());
868#endif
869
9e84b847
VZ
870 // to avoid memory leaks we should call pthread_join(), but it must only be
871 // done once so use a critical section to serialize the code below
9fc3ad34 872 {
4c460b34
VZ
873 wxCriticalSectionLocker lock(m_csJoinFlag);
874
875 if ( m_shouldBeJoined )
9fc3ad34 876 {
4c460b34
VZ
877 // FIXME shouldn't we set cancellation type to DISABLED here? If
878 // we're cancelled inside pthread_join(), things will almost
879 // certainly break - but if we disable the cancellation, we
880 // might deadlock
2b5f62a0 881 if ( pthread_join(GetId(), &m_exitcode) != 0 )
4c460b34 882 {
9e84b847
VZ
883 // this is a serious problem, so use wxLogError and not
884 // wxLogDebug: it is possible to bring the system to its knees
885 // by creating too many threads and not joining them quite
886 // easily
4c460b34
VZ
887 wxLogError(_("Failed to join a thread, potential memory leak "
888 "detected - please restart the program"));
889 }
9fc3ad34 890
4c460b34
VZ
891 m_shouldBeJoined = FALSE;
892 }
9fc3ad34 893 }
9111db68 894
518b5d2f
VZ
895 // reacquire GUI mutex
896 if ( wxThread::IsMain() )
897 wxMutexGuiEnter();
898}
899
518b5d2f
VZ
900void wxThreadInternal::Pause()
901{
882eefb1
VZ
902 // the state is set from the thread which pauses us first, this function
903 // is called later so the state should have been already set
518b5d2f 904 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 905 wxT("thread must first be paused with wxThread::Pause().") );
518b5d2f 906
2b5f62a0
VZ
907#ifdef __VMS
908 wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), (long long)GetId());
909#else
910 wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), (long)GetId());
911#endif
912
be809868
VZ
913 // wait until the semaphore is Post()ed from Resume()
914 m_semSuspend.Wait();
518b5d2f
VZ
915}
916
917void wxThreadInternal::Resume()
918{
919 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 920 wxT("can't resume thread which is not suspended.") );
518b5d2f 921
4c460b34
VZ
922 // the thread might be not actually paused yet - if there were no call to
923 // TestDestroy() since the last call to Pause() for example
924 if ( IsReallyPaused() )
925 {
2b5f62a0
VZ
926#ifdef __VMS
927 wxLogTrace(TRACE_THREADS, _T("Waking up thread %ld"), (long long)GetId());
928#else
929 wxLogTrace(TRACE_THREADS, _T("Waking up thread %ld"), (long)GetId());
930#endif
931
4c460b34 932 // wake up Pause()
be809868 933 m_semSuspend.Post();
4c460b34
VZ
934
935 // reset the flag
936 SetReallyPaused(FALSE);
937 }
938 else
939 {
940 wxLogTrace(TRACE_THREADS, _T("Thread %ld is not yet really paused"),
2b5f62a0
VZ
941#ifdef __VMS
942 (long long)GetId());
943#else
944 (long)GetId());
945#endif
4c460b34 946 }
518b5d2f
VZ
947
948 SetState(STATE_RUNNING);
949}
950
951// -----------------------------------------------------------------------------
9fc3ad34 952// wxThread static functions
518b5d2f
VZ
953// -----------------------------------------------------------------------------
954
955wxThread *wxThread::This()
956{
957 return (wxThread *)pthread_getspecific(gs_keySelf);
958}
959
960bool wxThread::IsMain()
961{
962 return (bool)pthread_equal(pthread_self(), gs_tidMain);
963}
964
965void wxThread::Yield()
966{
6f837e5c 967#ifdef HAVE_SCHED_YIELD
518b5d2f 968 sched_yield();
6f837e5c 969#endif
518b5d2f
VZ
970}
971
972void wxThread::Sleep(unsigned long milliseconds)
973{
974 wxUsleep(milliseconds);
975}
976
ef8d96c2
VZ
977int wxThread::GetCPUCount()
978{
1e6feb95 979#if defined(__LINUX__) && wxUSE_FFILE
ef8d96c2
VZ
980 // read from proc (can't use wxTextFile here because it's a special file:
981 // it has 0 size but still can be read from)
982 wxLogNull nolog;
983
984 wxFFile file(_T("/proc/cpuinfo"));
985 if ( file.IsOpened() )
986 {
987 // slurp the whole file
988 wxString s;
989 if ( file.ReadAll(&s) )
990 {
991 // (ab)use Replace() to find the number of "processor" strings
992 size_t count = s.Replace(_T("processor"), _T(""));
993 if ( count > 0 )
994 {
995 return count;
996 }
997
998 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
999 }
1000 else
1001 {
1002 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1003 }
1004 }
1005#elif defined(_SC_NPROCESSORS_ONLN)
1006 // this works for Solaris
1007 int rc = sysconf(_SC_NPROCESSORS_ONLN);
1008 if ( rc != -1 )
1009 {
1010 return rc;
1011 }
1012#endif // different ways to get number of CPUs
1013
1014 // unknown
1015 return -1;
1016}
1017
a7aef4a9
JJ
1018#ifdef __VMS
1019 // VMS is a 64 bit system and threads have 64 bit pointers.
1020 // ??? also needed for other systems????
1021unsigned long long wxThread::GetCurrentId()
1022{
1023 return (unsigned long long)pthread_self();
1024#else
1fcfb40d
RD
1025unsigned long wxThread::GetCurrentId()
1026{
1027 return (unsigned long)pthread_self();
a7aef4a9 1028#endif
1fcfb40d
RD
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()
9fc3ad34
VZ
1434#if !HAVE_THREAD_CLEANUP_FUNCTIONS
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);
1441#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
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
VZ
1454 wxASSERT_MSG( This() == this,
1455 _T("wxThread::Exit() can only be called in the "
1456 "context of the same thread") );
1457
9e84b847
VZ
1458 if ( m_isDetached )
1459 {
1460 // from the moment we call OnExit(), the main program may terminate at
1461 // any moment, so mark this thread as being already in process of being
1462 // deleted or wxThreadModule::OnExit() will try to delete it again
1463 ScheduleThreadForDeletion();
1464 }
9fc3ad34
VZ
1465
1466 // don't enter m_critsect before calling OnExit() because the user code
1467 // might deadlock if, for example, it signals a condition in OnExit() (a
1468 // common case) while the main thread calls any of functions entering
1469 // m_critsect on us (almost all of them do)
518b5d2f
VZ
1470 OnExit();
1471
9fc3ad34
VZ
1472 // delete C++ thread object if this is a detached thread - user is
1473 // responsible for doing this for joinable ones
1474 if ( m_isDetached )
1475 {
1476 // FIXME I'm feeling bad about it - what if another thread function is
1477 // called (in another thread context) now? It will try to access
1478 // half destroyed object which will probably result in something
1479 // very bad - but we can't protect this by a crit section unless
1480 // we make it a global object, but this would mean that we can
1481 // only call one thread function at a time :-(
1482 DeleteThread(this);
1483 }
1484
1485 // terminate the thread (pthread_exit() never returns)
518b5d2f 1486 pthread_exit(status);
9fc3ad34
VZ
1487
1488 wxFAIL_MSG(_T("pthread_exit() failed"));
518b5d2f
VZ
1489}
1490
1491// also test whether we were paused
1492bool wxThread::TestDestroy()
1493{
4c460b34
VZ
1494 wxASSERT_MSG( This() == this,
1495 _T("wxThread::TestDestroy() can only be called in the "
1496 "context of the same thread") );
1497
9fc3ad34 1498 m_critsect.Enter();
518b5d2f 1499
9fc3ad34 1500 if ( m_internal->GetState() == STATE_PAUSED )
518b5d2f 1501 {
4c460b34
VZ
1502 m_internal->SetReallyPaused(TRUE);
1503
9fc3ad34
VZ
1504 // leave the crit section or the other threads will stop too if they
1505 // try to call any of (seemingly harmless) IsXXX() functions while we
1506 // sleep
518b5d2f
VZ
1507 m_critsect.Leave();
1508
9fc3ad34
VZ
1509 m_internal->Pause();
1510 }
1511 else
1512 {
1513 // thread wasn't requested to pause, nothing to do
1514 m_critsect.Leave();
518b5d2f
VZ
1515 }
1516
9fc3ad34 1517 return m_internal->WasCancelled();
518b5d2f
VZ
1518}
1519
1520wxThread::~wxThread()
1521{
9fc3ad34 1522#ifdef __WXDEBUG__
062c4861 1523 m_critsect.Enter();
9fc3ad34
VZ
1524
1525 // check that the thread either exited or couldn't be created
1526 if ( m_internal->GetState() != STATE_EXITED &&
1527 m_internal->GetState() != STATE_NEW )
bbfa0322 1528 {
4c460b34
VZ
1529 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1530 "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 {
58230fb1
VZ
1596 wxLogSysError(rc, _("Thread module initialization failed: "
1597 "failed to create thread key"));
518b5d2f
VZ
1598
1599 return FALSE;
1600 }
1601
518b5d2f 1602 gs_tidMain = pthread_self();
19da4326 1603
9fc3ad34
VZ
1604#if wxUSE_GUI
1605 gs_mutexGui = new wxMutex();
1606
518b5d2f 1607 gs_mutexGui->Lock();
9fc3ad34 1608#endif // wxUSE_GUI
518b5d2f 1609
be809868 1610 gs_mutexDeleteThread = new wxMutex();
c112e100 1611 gs_condAllDeleted = new wxCondition( *gs_mutexDeleteThread );
88e243b2 1612
518b5d2f
VZ
1613 return TRUE;
1614}
1615
1616void wxThreadModule::OnExit()
1617{
223d09f6 1618 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
518b5d2f 1619
9fc3ad34
VZ
1620 // are there any threads left which are being deleted right now?
1621 size_t nThreadsBeingDeleted;
be809868 1622
9fc3ad34 1623 {
be809868 1624 wxMutexLocker lock( *gs_mutexDeleteThread );
9fc3ad34 1625 nThreadsBeingDeleted = gs_nThreadsBeingDeleted;
9fc3ad34 1626
be809868 1627 if ( nThreadsBeingDeleted > 0 )
9e84b847 1628 {
2b5f62a0
VZ
1629 wxLogTrace(TRACE_THREADS,
1630 _T("Waiting for %lu threads to disappear"),
1631 (unsigned long)nThreadsBeingDeleted);
9fc3ad34 1632
be809868
VZ
1633 // have to wait until all of them disappear
1634 gs_condAllDeleted->Wait();
1635 }
9fc3ad34
VZ
1636 }
1637
518b5d2f
VZ
1638 // terminate any threads left
1639 size_t count = gs_allThreads.GetCount();
1640 if ( count != 0u )
4c460b34 1641 {
2b5f62a0
VZ
1642 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1643 (unsigned long)count);
4c460b34 1644 }
518b5d2f
VZ
1645
1646 for ( size_t n = 0u; n < count; n++ )
1647 {
bbfa0322
VZ
1648 // Delete calls the destructor which removes the current entry. We
1649 // should only delete the first one each time.
0ac77ef5 1650 gs_allThreads[0]->Delete();
518b5d2f
VZ
1651 }
1652
9fc3ad34 1653#if wxUSE_GUI
518b5d2f
VZ
1654 // destroy GUI mutex
1655 gs_mutexGui->Unlock();
1656
518b5d2f 1657 delete gs_mutexGui;
9fc3ad34 1658#endif // wxUSE_GUI
518b5d2f
VZ
1659
1660 // and free TLD slot
1661 (void)pthread_key_delete(gs_keySelf);
be809868
VZ
1662
1663 delete gs_condAllDeleted;
1664 delete gs_mutexDeleteThread;
518b5d2f
VZ
1665}
1666
1667// ----------------------------------------------------------------------------
1668// global functions
1669// ----------------------------------------------------------------------------
1670
9fc3ad34
VZ
1671static void ScheduleThreadForDeletion()
1672{
be809868 1673 wxMutexLocker lock( *gs_mutexDeleteThread );
9fc3ad34
VZ
1674
1675 gs_nThreadsBeingDeleted++;
1676
2b5f62a0
VZ
1677 wxLogTrace(TRACE_THREADS, _T("%lu thread%s waiting to be deleted"),
1678 (unsigned long)gs_nThreadsBeingDeleted,
fcc3d7cb 1679 gs_nThreadsBeingDeleted == 1 ? "" : "s");
9fc3ad34
VZ
1680}
1681
1682static void DeleteThread(wxThread *This)
1683{
1684 // gs_mutexDeleteThread should be unlocked before signalling the condition
1685 // or wxThreadModule::OnExit() would deadlock
be809868 1686 wxMutexLocker locker( *gs_mutexDeleteThread );
9fc3ad34 1687
be809868 1688 wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId());
9fc3ad34 1689
be809868 1690 delete This;
9fc3ad34 1691
be809868 1692 wxCHECK_RET( gs_nThreadsBeingDeleted > 0,
9e84b847 1693 _T("no threads scheduled for deletion, yet we delete one?") );
9fc3ad34 1694
2b5f62a0
VZ
1695 wxLogTrace(TRACE_THREADS, _T("%lu scheduled for deletion threads left."),
1696 (unsigned long)gs_nThreadsBeingDeleted - 1);
4c460b34 1697
9fc3ad34
VZ
1698 if ( !--gs_nThreadsBeingDeleted )
1699 {
1700 // no more threads left, signal it
1701 gs_condAllDeleted->Signal();
9fc3ad34
VZ
1702 }
1703}
1704
518b5d2f
VZ
1705void wxMutexGuiEnter()
1706{
9fc3ad34
VZ
1707#if wxUSE_GUI
1708 gs_mutexGui->Lock();
1709#endif // wxUSE_GUI
518b5d2f
VZ
1710}
1711
1712void wxMutexGuiLeave()
1713{
9fc3ad34
VZ
1714#if wxUSE_GUI
1715 gs_mutexGui->Unlock();
1716#endif // wxUSE_GUI
518b5d2f 1717}
80cb83be 1718
9e84b847
VZ
1719// ----------------------------------------------------------------------------
1720// include common implementation code
1721// ----------------------------------------------------------------------------
1722
1723#include "wx/thrimpl.cpp"
1724
1725#endif // wxUSE_THREADS
1726