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