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