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