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