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