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