1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999)
11 // Robert Roebling (1999)
12 // Licence: wxWindows licence
13 /////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
24 #pragma implementation "thread.h"
31 #include "wx/thread.h"
32 #include "wx/module.h"
36 #include "wx/dynarray.h"
48 // ----------------------------------------------------------------------------
50 // ----------------------------------------------------------------------------
52 // the possible states of the thread and transitions from them
55 STATE_NEW
, // didn't start execution yet (=> RUNNING)
56 STATE_RUNNING
, // running (=> PAUSED or EXITED)
57 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
58 STATE_EXITED
// thread doesn't exist any more
61 // the exit value of a thread which has been cancelled
62 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
65 #define TRACE_THREADS _T("thread")
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
71 static void ScheduleThreadForDeletion();
72 static void DeleteThread(wxThread
*This
);
74 // ----------------------------------------------------------------------------
76 // ----------------------------------------------------------------------------
78 // same as wxMutexLocker but for "native" mutex
82 MutexLock(pthread_mutex_t
& mutex
)
85 if ( pthread_mutex_lock(m_mutex
) != 0 )
87 wxLogDebug(_T("pthread_mutex_lock() failed"));
93 if ( pthread_mutex_unlock(m_mutex
) != 0 )
95 wxLogDebug(_T("pthread_mutex_unlock() failed"));
100 pthread_mutex_t
*m_mutex
;
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
109 // -----------------------------------------------------------------------------
111 // -----------------------------------------------------------------------------
113 // we keep the list of all threads created by the application to be able to
114 // terminate them on exit if there are some left - otherwise the process would
116 static wxArrayThread gs_allThreads
;
118 // the id of the main thread
119 static pthread_t gs_tidMain
;
121 // the key for the pointer to the associated wxThread object
122 static pthread_key_t gs_keySelf
;
124 // the number of threads which are being deleted - the program won't exit
125 // until there are any left
126 static size_t gs_nThreadsBeingDeleted
= 0;
128 // a mutex to protect gs_nThreadsBeingDeleted
129 static pthread_mutex_t gs_mutexDeleteThread
= PTHREAD_MUTEX_INITIALIZER
;
131 // and a condition variable which will be signaled when all
132 // gs_nThreadsBeingDeleted will have been deleted
133 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
136 // this mutex must be acquired before any call to a GUI function
137 static wxMutex
*gs_mutexGui
;
140 // ============================================================================
142 // ============================================================================
144 //--------------------------------------------------------------------
145 // wxMutex (Posix implementation)
146 //--------------------------------------------------------------------
148 class wxMutexInternal
151 pthread_mutex_t m_mutex
;
156 m_internal
= new wxMutexInternal
;
158 pthread_mutex_init(&(m_internal
->m_mutex
),
159 (pthread_mutexattr_t
*) NULL
);
166 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
168 pthread_mutex_destroy( &(m_internal
->m_mutex
) );
172 wxMutexError
wxMutex::Lock()
174 int err
= pthread_mutex_lock( &(m_internal
->m_mutex
) );
177 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
179 return wxMUTEX_DEAD_LOCK
;
184 return wxMUTEX_NO_ERROR
;
187 wxMutexError
wxMutex::TryLock()
194 int err
= pthread_mutex_trylock( &(m_internal
->m_mutex
) );
197 case EBUSY
: return wxMUTEX_BUSY
;
202 return wxMUTEX_NO_ERROR
;
205 wxMutexError
wxMutex::Unlock()
213 wxLogDebug(wxT("Unlocking not locked mutex."));
215 return wxMUTEX_UNLOCKED
;
218 pthread_mutex_unlock( &(m_internal
->m_mutex
) );
220 return wxMUTEX_NO_ERROR
;
223 //--------------------------------------------------------------------
224 // wxCondition (Posix implementation)
225 //--------------------------------------------------------------------
227 // notice that we must use a mutex with POSIX condition variables to ensure
228 // that the worker thread doesn't signal condition before the waiting thread
229 // starts to wait for it
230 class wxConditionInternal
233 wxConditionInternal();
234 ~wxConditionInternal();
237 bool WaitWithTimeout(const timespec
* ts
);
243 pthread_mutex_t m_mutex
;
244 pthread_cond_t m_condition
;
247 wxConditionInternal::wxConditionInternal()
249 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
251 // this is supposed to never happen
252 wxFAIL_MSG( _T("pthread_cond_init() failed") );
255 if ( pthread_mutex_init(&m_mutex
, (pthread_mutexattr_t
*)NULL
) != 0 )
258 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
261 // initially the mutex is locked, so no thread can Signal() or Broadcast()
262 // until another thread starts to Wait()
263 if ( pthread_mutex_lock(&m_mutex
) != 0 )
265 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
269 wxConditionInternal::~wxConditionInternal()
271 if ( pthread_cond_destroy( &m_condition
) != 0 )
273 wxLogDebug(_T("Failed to destroy condition variable (some "
274 "threads are probably still waiting on it?)"));
277 if ( pthread_mutex_unlock( &m_mutex
) != 0 )
279 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
282 if ( pthread_mutex_destroy( &m_mutex
) != 0 )
284 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
288 void wxConditionInternal::Wait()
290 if ( pthread_cond_wait( &m_condition
, &m_mutex
) != 0 )
292 // not supposed to ever happen
293 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
297 bool wxConditionInternal::WaitWithTimeout(const timespec
* ts
)
299 switch ( pthread_cond_timedwait( &m_condition
, &m_mutex
, ts
) )
302 // condition signaled
306 wxLogDebug(_T("pthread_cond_timedwait() failed"));
312 // wait interrupted or timeout elapsed
317 void wxConditionInternal::Signal()
319 MutexLock
lock(m_mutex
);
321 if ( pthread_cond_signal( &m_condition
) != 0 )
323 // shouldn't ever happen
324 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
328 void wxConditionInternal::Broadcast()
330 MutexLock
lock(m_mutex
);
332 if ( pthread_cond_broadcast( &m_condition
) != 0 )
334 // shouldn't ever happen
335 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
339 wxCondition::wxCondition()
341 m_internal
= new wxConditionInternal
;
344 wxCondition::~wxCondition()
349 void wxCondition::Wait()
354 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
358 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
359 tspec
.tv_nsec
= nsec
;
361 return m_internal
->WaitWithTimeout(&tspec
);
364 void wxCondition::Signal()
366 m_internal
->Signal();
369 void wxCondition::Broadcast()
371 m_internal
->Broadcast();
374 //--------------------------------------------------------------------
375 // wxThread (Posix implementation)
376 //--------------------------------------------------------------------
378 class wxThreadInternal
384 // thread entry function
385 static void *PthreadStart(void *ptr
);
387 #if HAVE_THREAD_CLEANUP_FUNCTIONS
388 // thread exit function
389 static void PthreadCleanup(void *ptr
);
395 // ask the thread to terminate
397 // wake up threads waiting for our termination
399 // go to sleep until Resume() is called
406 int GetPriority() const { return m_prio
; }
407 void SetPriority(int prio
) { m_prio
= prio
; }
409 wxThreadState
GetState() const { return m_state
; }
410 void SetState(wxThreadState state
) { m_state
= state
; }
412 pthread_t
GetId() const { return m_threadId
; }
413 pthread_t
*GetIdPtr() { return &m_threadId
; }
415 void SetCancelFlag() { m_cancelled
= TRUE
; }
416 bool WasCancelled() const { return m_cancelled
; }
418 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
419 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
421 // tell the thread that it is a detached one
422 void Detach() { m_shouldBeJoined
= m_shouldBroadcast
= FALSE
; }
423 // but even detached threads need to notifyus about their termination
424 // sometimes - tell the thread that it should do it
425 void Notify() { m_shouldBroadcast
= TRUE
; }
428 pthread_t m_threadId
; // id of the thread
429 wxThreadState m_state
; // see wxThreadState enum
430 int m_prio
; // in wxWindows units: from 0 to 100
432 // this flag is set when the thread should terminate
435 // the thread exit code - only used for joinable (!detached) threads and
436 // is only valid after the thread termination
437 wxThread::ExitCode m_exitcode
;
439 // many threads may call Wait(), but only one of them should call
440 // pthread_join(), so we have to keep track of this
441 wxCriticalSection m_csJoinFlag
;
442 bool m_shouldBeJoined
;
443 bool m_shouldBroadcast
;
445 // VZ: it's possible that we might do with less than three different
446 // condition objects - for example, m_condRun and m_condEnd a priori
447 // won't be used in the same time. But for now I prefer this may be a
448 // bit less efficient but safer solution of having distinct condition
449 // variables for each purpose.
451 // this condition is signaled by Run() and the threads Entry() is not
452 // called before it is done
453 wxCondition m_condRun
;
455 // this one is signaled when the thread should resume after having been
457 wxCondition m_condSuspend
;
459 // finally this one is signalled when the thread exits
460 wxCondition m_condEnd
;
463 // ----------------------------------------------------------------------------
464 // thread startup and exit functions
465 // ----------------------------------------------------------------------------
467 void *wxThreadInternal::PthreadStart(void *ptr
)
469 wxThread
*thread
= (wxThread
*)ptr
;
470 wxThreadInternal
*pthread
= thread
->m_internal
;
472 // associate the thread pointer with the newly created thread so that
473 // wxThread::This() will work
474 int rc
= pthread_setspecific(gs_keySelf
, thread
);
477 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
482 #if HAVE_THREAD_CLEANUP_FUNCTIONS
483 // install the cleanup handler which will be called if the thread is
485 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
486 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
488 // wait for the condition to be signaled from Run()
489 pthread
->m_condRun
.Wait();
491 // call the main entry
492 pthread
->m_exitcode
= thread
->Entry();
494 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
498 wxCriticalSectionLocker
lock(thread
->m_critsect
);
500 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
503 // change the state of the thread to "exited" so that PthreadCleanup
504 // handler won't do anything from now (if it's called before we do
505 // pthread_cleanup_pop below)
506 pthread
->SetState(STATE_EXITED
);
509 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
510 // contains the matching '}' for the '{' in push, so they must be used
511 // in the same block!
512 #if HAVE_THREAD_CLEANUP_FUNCTIONS
513 // remove the cleanup handler without executing it
514 pthread_cleanup_pop(FALSE
);
515 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
517 // terminate the thread
518 thread
->Exit(pthread
->m_exitcode
);
520 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
525 #if HAVE_THREAD_CLEANUP_FUNCTIONS
527 // this handler is called when the thread is cancelled
528 void wxThreadInternal::PthreadCleanup(void *ptr
)
530 wxThread
*thread
= (wxThread
*) ptr
;
533 wxCriticalSectionLocker
lock(thread
->m_critsect
);
534 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
536 // thread is already considered as finished.
541 // exit the thread gracefully
542 thread
->Exit(EXITCODE_CANCELLED
);
545 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
547 // ----------------------------------------------------------------------------
549 // ----------------------------------------------------------------------------
551 wxThreadInternal::wxThreadInternal()
555 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
559 // defaults for joinable threads
560 m_shouldBeJoined
= TRUE
;
561 m_shouldBroadcast
= TRUE
;
564 wxThreadInternal::~wxThreadInternal()
568 wxThreadError
wxThreadInternal::Run()
570 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
571 wxT("thread may only be started once after Create()") );
575 SetState(STATE_RUNNING
);
577 return wxTHREAD_NO_ERROR
;
580 void wxThreadInternal::Wait()
582 // if the thread we're waiting for is waiting for the GUI mutex, we will
583 // deadlock so make sure we release it temporarily
584 if ( wxThread::IsMain() )
587 wxLogTrace(TRACE_THREADS
, _T("Starting to wait for thread %ld to exit."),
590 // wait until the thread terminates (we're blocking in _another_ thread,
594 // to avoid memory leaks we should call pthread_join(), but it must only
596 wxCriticalSectionLocker
lock(m_csJoinFlag
);
598 if ( m_shouldBeJoined
)
600 // FIXME shouldn't we set cancellation type to DISABLED here? If we're
601 // cancelled inside pthread_join(), things will almost certainly
602 // break - but if we disable the cancellation, we might deadlock
603 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
605 wxLogError(_T("Failed to join a thread, potential memory leak "
606 "detected - please restart the program"));
609 m_shouldBeJoined
= FALSE
;
612 // reacquire GUI mutex
613 if ( wxThread::IsMain() )
617 void wxThreadInternal::SignalExit()
619 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
621 SetState(STATE_EXITED
);
623 // wake up all the threads waiting for our termination - if there are any
624 if ( m_shouldBroadcast
)
626 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
629 m_condEnd
.Broadcast();
633 void wxThreadInternal::Pause()
635 // the state is set from the thread which pauses us first, this function
636 // is called later so the state should have been already set
637 wxCHECK_RET( m_state
== STATE_PAUSED
,
638 wxT("thread must first be paused with wxThread::Pause().") );
640 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
642 // wait until the condition is signaled from Resume()
643 m_condSuspend
.Wait();
646 void wxThreadInternal::Resume()
648 wxCHECK_RET( m_state
== STATE_PAUSED
,
649 wxT("can't resume thread which is not suspended.") );
651 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
654 m_condSuspend
.Signal();
656 SetState(STATE_RUNNING
);
659 // -----------------------------------------------------------------------------
660 // wxThread static functions
661 // -----------------------------------------------------------------------------
663 wxThread
*wxThread::This()
665 return (wxThread
*)pthread_getspecific(gs_keySelf
);
668 bool wxThread::IsMain()
670 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
673 void wxThread::Yield()
678 void wxThread::Sleep(unsigned long milliseconds
)
680 wxUsleep(milliseconds
);
683 // -----------------------------------------------------------------------------
685 // -----------------------------------------------------------------------------
687 wxThread::wxThread(wxThreadKind kind
)
689 // add this thread to the global list of all threads
690 gs_allThreads
.Add(this);
692 m_internal
= new wxThreadInternal();
694 m_isDetached
= kind
== wxTHREAD_DETACHED
;
697 wxThreadError
wxThread::Create()
699 if ( m_internal
->GetState() != STATE_NEW
)
701 // don't recreate thread
702 return wxTHREAD_RUNNING
;
705 // set up the thread attribute: right now, we only set thread priority
707 pthread_attr_init(&attr
);
709 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
711 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
713 wxLogError(_("Cannot retrieve thread scheduling policy."));
716 int min_prio
= sched_get_priority_min(policy
),
717 max_prio
= sched_get_priority_max(policy
),
718 prio
= m_internal
->GetPriority();
720 if ( min_prio
== -1 || max_prio
== -1 )
722 wxLogError(_("Cannot get priority range for scheduling policy %d."),
725 else if ( max_prio
== min_prio
)
727 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
729 // notify the programmer that this doesn't work here
730 wxLogWarning(_("Thread priority setting is ignored."));
732 //else: we have default priority, so don't complain
734 // anyhow, don't do anything because priority is just ignored
738 struct sched_param sp
;
739 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
741 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
744 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
746 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
748 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
751 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
753 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
754 // this will make the threads created by this process really concurrent
755 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
757 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
759 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
761 // VZ: assume that this one is always available (it's rather fundamental),
762 // if this function is ever missing we should try to use
763 // pthread_detach() instead (after thread creation)
766 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
768 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
771 // never try to join detached threads
772 m_internal
->Detach();
774 //else: threads are created joinable by default, it's ok
776 // create the new OS thread object
777 int rc
= pthread_create
779 m_internal
->GetIdPtr(),
781 wxThreadInternal::PthreadStart
,
785 if ( pthread_attr_destroy(&attr
) != 0 )
787 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
792 m_internal
->SetState(STATE_EXITED
);
794 return wxTHREAD_NO_RESOURCE
;
797 return wxTHREAD_NO_ERROR
;
800 wxThreadError
wxThread::Run()
802 wxCriticalSectionLocker
lock(m_critsect
);
804 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
805 wxT("must call wxThread::Create() first") );
807 return m_internal
->Run();
810 // -----------------------------------------------------------------------------
812 // -----------------------------------------------------------------------------
814 void wxThread::SetPriority(unsigned int prio
)
816 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
817 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
818 wxT("invalid thread priority") );
820 wxCriticalSectionLocker
lock(m_critsect
);
822 switch ( m_internal
->GetState() )
825 // thread not yet started, priority will be set when it is
826 m_internal
->SetPriority(prio
);
831 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
833 struct sched_param sparam
;
834 sparam
.sched_priority
= prio
;
836 if ( pthread_setschedparam(m_internal
->GetId(),
837 SCHED_OTHER
, &sparam
) != 0 )
839 wxLogError(_("Failed to set thread priority %d."), prio
);
842 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
847 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
851 unsigned int wxThread::GetPriority() const
853 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
855 return m_internal
->GetPriority();
858 unsigned long wxThread::GetId() const
860 return (unsigned long)m_internal
->GetId();
863 // -----------------------------------------------------------------------------
865 // -----------------------------------------------------------------------------
867 wxThreadError
wxThread::Pause()
869 wxCriticalSectionLocker
lock(m_critsect
);
871 if ( m_internal
->GetState() != STATE_RUNNING
)
873 wxLogDebug(wxT("Can't pause thread which is not running."));
875 return wxTHREAD_NOT_RUNNING
;
878 // just set a flag, the thread will be really paused only during the next
879 // call to TestDestroy()
880 m_internal
->SetState(STATE_PAUSED
);
882 return wxTHREAD_NO_ERROR
;
885 wxThreadError
wxThread::Resume()
889 wxThreadState state
= m_internal
->GetState();
891 // the thread might be not actually paused yet - if there were no call to
892 // TestDestroy() since the last call to Pause(), so avoid that
893 // TestDestroy() deadlocks trying to enter m_critsect by leaving it before
900 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is suspended, resuming."),
903 m_internal
->Resume();
905 return wxTHREAD_NO_ERROR
;
908 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
910 return wxTHREAD_NO_ERROR
;
913 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
915 return wxTHREAD_MISC_ERROR
;
919 // -----------------------------------------------------------------------------
921 // -----------------------------------------------------------------------------
923 wxThread::ExitCode
wxThread::Wait()
925 wxCHECK_MSG( This() != this, (ExitCode
)-1,
926 _T("a thread can't wait for itself") );
928 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
929 _T("can't wait for detached thread") );
933 return m_internal
->GetExitCode();
936 wxThreadError
wxThread::Delete(ExitCode
*rc
)
939 wxThreadState state
= m_internal
->GetState();
941 // ask the thread to stop
942 m_internal
->SetCancelFlag();
946 // detached threads won't broadcast about their termination by default
947 // because usually nobody waits for them - but here we do, so ask the
948 // thread to notify us
949 m_internal
->Notify();
962 // resume the thread first (don't call our Resume() because this
963 // would dead lock when it tries to enter m_critsect)
964 m_internal
->Resume();
969 // wait until the thread stops
974 wxASSERT_MSG( !m_isDetached
,
975 _T("no return code for detached threads") );
977 // if it's a joinable thread, it's not deleted yet
978 *rc
= m_internal
->GetExitCode();
982 return wxTHREAD_NO_ERROR
;
985 wxThreadError
wxThread::Kill()
987 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
988 _T("a thread can't kill itself") );
990 switch ( m_internal
->GetState() )
994 return wxTHREAD_NOT_RUNNING
;
997 // resume the thread first
1003 #ifdef HAVE_PTHREAD_CANCEL
1004 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1007 wxLogError(_("Failed to terminate a thread."));
1009 return wxTHREAD_MISC_ERROR
;
1014 // if we use cleanup function, this will be done from
1016 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1017 ScheduleThreadForDeletion();
1022 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1026 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1029 return wxTHREAD_NO_ERROR
;
1033 void wxThread::Exit(ExitCode status
)
1035 // from the moment we call OnExit(), the main program may terminate at any
1036 // moment, so mark this thread as being already in process of being
1037 // deleted or wxThreadModule::OnExit() will try to delete it again
1038 ScheduleThreadForDeletion();
1040 // don't enter m_critsect before calling OnExit() because the user code
1041 // might deadlock if, for example, it signals a condition in OnExit() (a
1042 // common case) while the main thread calls any of functions entering
1043 // m_critsect on us (almost all of them do)
1046 // now do enter it because SignalExit() will change our state
1049 // next wake up the threads waiting for us (OTOH, this function won't return
1050 // until someone waited for us!)
1051 m_internal
->SignalExit();
1053 // leave the critical section before entering the dtor which tries to
1057 // delete C++ thread object if this is a detached thread - user is
1058 // responsible for doing this for joinable ones
1061 // FIXME I'm feeling bad about it - what if another thread function is
1062 // called (in another thread context) now? It will try to access
1063 // half destroyed object which will probably result in something
1064 // very bad - but we can't protect this by a crit section unless
1065 // we make it a global object, but this would mean that we can
1066 // only call one thread function at a time :-(
1070 // terminate the thread (pthread_exit() never returns)
1071 pthread_exit(status
);
1073 wxFAIL_MSG(_T("pthread_exit() failed"));
1076 // also test whether we were paused
1077 bool wxThread::TestDestroy()
1081 if ( m_internal
->GetState() == STATE_PAUSED
)
1083 // leave the crit section or the other threads will stop too if they
1084 // try to call any of (seemingly harmless) IsXXX() functions while we
1088 m_internal
->Pause();
1092 // thread wasn't requested to pause, nothing to do
1096 return m_internal
->WasCancelled();
1099 wxThread::~wxThread()
1104 // check that the thread either exited or couldn't be created
1105 if ( m_internal
->GetState() != STATE_EXITED
&&
1106 m_internal
->GetState() != STATE_NEW
)
1108 wxLogDebug(_T("The thread is being destroyed although it is still "
1109 "running! The application may crash."));
1113 #endif // __WXDEBUG__
1117 // remove this thread from the global array
1118 gs_allThreads
.Remove(this);
1121 // -----------------------------------------------------------------------------
1123 // -----------------------------------------------------------------------------
1125 bool wxThread::IsRunning() const
1127 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1129 return m_internal
->GetState() == STATE_RUNNING
;
1132 bool wxThread::IsAlive() const
1134 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1136 switch ( m_internal
->GetState() )
1147 bool wxThread::IsPaused() const
1149 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1151 return (m_internal
->GetState() == STATE_PAUSED
);
1154 //--------------------------------------------------------------------
1156 //--------------------------------------------------------------------
1158 class wxThreadModule
: public wxModule
1161 virtual bool OnInit();
1162 virtual void OnExit();
1165 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1168 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1170 bool wxThreadModule::OnInit()
1172 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1175 wxLogSysError(rc
, _("Thread module initialization failed: "
1176 "failed to create thread key"));
1181 gs_tidMain
= pthread_self();
1184 gs_mutexGui
= new wxMutex();
1186 gs_mutexGui
->Lock();
1192 void wxThreadModule::OnExit()
1194 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1196 // are there any threads left which are being deleted right now?
1197 size_t nThreadsBeingDeleted
;
1199 MutexLock
lock(gs_mutexDeleteThread
);
1200 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1203 if ( nThreadsBeingDeleted
> 0 )
1205 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1206 nThreadsBeingDeleted
);
1208 // have to wait until all of them disappear
1209 gs_condAllDeleted
->Wait();
1212 // terminate any threads left
1213 size_t count
= gs_allThreads
.GetCount();
1215 wxLogDebug(wxT("Some threads were not terminated by the application."));
1217 for ( size_t n
= 0u; n
< count
; n
++ )
1219 // Delete calls the destructor which removes the current entry. We
1220 // should only delete the first one each time.
1221 gs_allThreads
[0]->Delete();
1225 // destroy GUI mutex
1226 gs_mutexGui
->Unlock();
1231 // and free TLD slot
1232 (void)pthread_key_delete(gs_keySelf
);
1235 // ----------------------------------------------------------------------------
1237 // ----------------------------------------------------------------------------
1239 static void ScheduleThreadForDeletion()
1241 MutexLock
lock(gs_mutexDeleteThread
);
1243 if ( gs_nThreadsBeingDeleted
== 0 )
1245 gs_condAllDeleted
= new wxCondition
;
1248 gs_nThreadsBeingDeleted
++;
1250 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1251 gs_nThreadsBeingDeleted
,
1252 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1255 static void DeleteThread(wxThread
*This
)
1257 // gs_mutexDeleteThread should be unlocked before signalling the condition
1258 // or wxThreadModule::OnExit() would deadlock
1260 MutexLock
lock(gs_mutexDeleteThread
);
1262 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1266 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1267 _T("no threads scheduled for deletion, yet we delete "
1271 if ( !--gs_nThreadsBeingDeleted
)
1273 // no more threads left, signal it
1274 gs_condAllDeleted
->Signal();
1276 delete gs_condAllDeleted
;
1277 gs_condAllDeleted
= (wxCondition
*)NULL
;
1281 void wxMutexGuiEnter()
1284 gs_mutexGui
->Lock();
1288 void wxMutexGuiLeave()
1291 gs_mutexGui
->Unlock();