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"
27 // With simple makefiles, we must ignore the file body if not using
33 #include "wx/thread.h"
34 #include "wx/module.h"
38 #include "wx/dynarray.h"
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 // the possible states of the thread and transitions from them
57 STATE_NEW
, // didn't start execution yet (=> RUNNING)
58 STATE_RUNNING
, // running (=> PAUSED or EXITED)
59 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
60 STATE_EXITED
// thread doesn't exist any more
63 // the exit value of a thread which has been cancelled
64 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
67 #define TRACE_THREADS _T("thread")
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 static void ScheduleThreadForDeletion();
74 static void DeleteThread(wxThread
*This
);
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 // same as wxMutexLocker but for "native" mutex
84 MutexLock(pthread_mutex_t
& mutex
)
87 if ( pthread_mutex_lock(m_mutex
) != 0 )
89 wxLogDebug(_T("pthread_mutex_lock() failed"));
95 if ( pthread_mutex_unlock(m_mutex
) != 0 )
97 wxLogDebug(_T("pthread_mutex_unlock() failed"));
102 pthread_mutex_t
*m_mutex
;
105 // ----------------------------------------------------------------------------
107 // ----------------------------------------------------------------------------
109 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
111 // -----------------------------------------------------------------------------
113 // -----------------------------------------------------------------------------
115 // we keep the list of all threads created by the application to be able to
116 // terminate them on exit if there are some left - otherwise the process would
118 static wxArrayThread gs_allThreads
;
120 // the id of the main thread
121 static pthread_t gs_tidMain
;
123 // the key for the pointer to the associated wxThread object
124 static pthread_key_t gs_keySelf
;
126 // the number of threads which are being deleted - the program won't exit
127 // until there are any left
128 static size_t gs_nThreadsBeingDeleted
= 0;
130 // a mutex to protect gs_nThreadsBeingDeleted
131 static pthread_mutex_t gs_mutexDeleteThread
= PTHREAD_MUTEX_INITIALIZER
;
133 // and a condition variable which will be signaled when all
134 // gs_nThreadsBeingDeleted will have been deleted
135 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
138 // this mutex must be acquired before any call to a GUI function
139 static wxMutex
*gs_mutexGui
;
142 // ============================================================================
144 // ============================================================================
146 //--------------------------------------------------------------------
147 // wxMutex (Posix implementation)
148 //--------------------------------------------------------------------
150 class wxMutexInternal
153 pthread_mutex_t m_mutex
;
158 m_internal
= new wxMutexInternal
;
160 pthread_mutex_init(&(m_internal
->m_mutex
),
161 (pthread_mutexattr_t
*) NULL
);
168 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
170 pthread_mutex_destroy( &(m_internal
->m_mutex
) );
174 wxMutexError
wxMutex::Lock()
176 int err
= pthread_mutex_lock( &(m_internal
->m_mutex
) );
179 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
181 return wxMUTEX_DEAD_LOCK
;
186 return wxMUTEX_NO_ERROR
;
189 wxMutexError
wxMutex::TryLock()
196 int err
= pthread_mutex_trylock( &(m_internal
->m_mutex
) );
199 case EBUSY
: return wxMUTEX_BUSY
;
204 return wxMUTEX_NO_ERROR
;
207 wxMutexError
wxMutex::Unlock()
215 wxLogDebug(wxT("Unlocking not locked mutex."));
217 return wxMUTEX_UNLOCKED
;
220 pthread_mutex_unlock( &(m_internal
->m_mutex
) );
222 return wxMUTEX_NO_ERROR
;
225 //--------------------------------------------------------------------
226 // wxCondition (Posix implementation)
227 //--------------------------------------------------------------------
229 // notice that we must use a mutex with POSIX condition variables to ensure
230 // that the worker thread doesn't signal condition before the waiting thread
231 // starts to wait for it
232 class wxConditionInternal
235 wxConditionInternal();
236 ~wxConditionInternal();
239 bool WaitWithTimeout(const timespec
* ts
);
245 pthread_mutex_t m_mutex
;
246 pthread_cond_t m_condition
;
249 wxConditionInternal::wxConditionInternal()
251 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
253 // this is supposed to never happen
254 wxFAIL_MSG( _T("pthread_cond_init() failed") );
257 if ( pthread_mutex_init(&m_mutex
, (pthread_mutexattr_t
*)NULL
) != 0 )
260 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
263 // initially the mutex is locked, so no thread can Signal() or Broadcast()
264 // until another thread starts to Wait()
265 if ( pthread_mutex_lock(&m_mutex
) != 0 )
267 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
271 wxConditionInternal::~wxConditionInternal()
273 if ( pthread_cond_destroy( &m_condition
) != 0 )
275 wxLogDebug(_T("Failed to destroy condition variable (some "
276 "threads are probably still waiting on it?)"));
279 if ( pthread_mutex_unlock( &m_mutex
) != 0 )
281 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
284 if ( pthread_mutex_destroy( &m_mutex
) != 0 )
286 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
290 void wxConditionInternal::Wait()
292 if ( pthread_cond_wait( &m_condition
, &m_mutex
) != 0 )
294 // not supposed to ever happen
295 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
299 bool wxConditionInternal::WaitWithTimeout(const timespec
* ts
)
301 switch ( pthread_cond_timedwait( &m_condition
, &m_mutex
, ts
) )
304 // condition signaled
308 wxLogDebug(_T("pthread_cond_timedwait() failed"));
314 // wait interrupted or timeout elapsed
319 void wxConditionInternal::Signal()
321 MutexLock
lock(m_mutex
);
323 if ( pthread_cond_signal( &m_condition
) != 0 )
325 // shouldn't ever happen
326 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
330 void wxConditionInternal::Broadcast()
332 MutexLock
lock(m_mutex
);
334 if ( pthread_cond_broadcast( &m_condition
) != 0 )
336 // shouldn't ever happen
337 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
341 wxCondition::wxCondition()
343 m_internal
= new wxConditionInternal
;
346 wxCondition::~wxCondition()
351 void wxCondition::Wait()
356 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
360 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
361 tspec
.tv_nsec
= nsec
;
363 return m_internal
->WaitWithTimeout(&tspec
);
366 void wxCondition::Signal()
368 m_internal
->Signal();
371 void wxCondition::Broadcast()
373 m_internal
->Broadcast();
376 //--------------------------------------------------------------------
377 // wxThread (Posix implementation)
378 //--------------------------------------------------------------------
380 class wxThreadInternal
386 // thread entry function
387 static void *PthreadStart(void *ptr
);
389 #if HAVE_THREAD_CLEANUP_FUNCTIONS
390 // thread exit function
391 static void PthreadCleanup(void *ptr
);
397 // ask the thread to terminate
399 // wake up threads waiting for our termination
401 // go to sleep until Resume() is called
408 int GetPriority() const { return m_prio
; }
409 void SetPriority(int prio
) { m_prio
= prio
; }
411 wxThreadState
GetState() const { return m_state
; }
412 void SetState(wxThreadState state
) { m_state
= state
; }
414 pthread_t
GetId() const { return m_threadId
; }
415 pthread_t
*GetIdPtr() { return &m_threadId
; }
417 void SetCancelFlag() { m_cancelled
= TRUE
; }
418 bool WasCancelled() const { return m_cancelled
; }
420 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
421 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
423 // tell the thread that it is a detached one
424 void Detach() { m_shouldBeJoined
= m_shouldBroadcast
= FALSE
; }
425 // but even detached threads need to notifyus about their termination
426 // sometimes - tell the thread that it should do it
427 void Notify() { m_shouldBroadcast
= TRUE
; }
430 pthread_t m_threadId
; // id of the thread
431 wxThreadState m_state
; // see wxThreadState enum
432 int m_prio
; // in wxWindows units: from 0 to 100
434 // this flag is set when the thread should terminate
437 // the thread exit code - only used for joinable (!detached) threads and
438 // is only valid after the thread termination
439 wxThread::ExitCode m_exitcode
;
441 // many threads may call Wait(), but only one of them should call
442 // pthread_join(), so we have to keep track of this
443 wxCriticalSection m_csJoinFlag
;
444 bool m_shouldBeJoined
;
445 bool m_shouldBroadcast
;
447 // VZ: it's possible that we might do with less than three different
448 // condition objects - for example, m_condRun and m_condEnd a priori
449 // won't be used in the same time. But for now I prefer this may be a
450 // bit less efficient but safer solution of having distinct condition
451 // variables for each purpose.
453 // this condition is signaled by Run() and the threads Entry() is not
454 // called before it is done
455 wxCondition m_condRun
;
457 // this one is signaled when the thread should resume after having been
459 wxCondition m_condSuspend
;
461 // finally this one is signalled when the thread exits
462 wxCondition m_condEnd
;
465 // ----------------------------------------------------------------------------
466 // thread startup and exit functions
467 // ----------------------------------------------------------------------------
469 void *wxThreadInternal::PthreadStart(void *ptr
)
471 wxThread
*thread
= (wxThread
*)ptr
;
472 wxThreadInternal
*pthread
= thread
->m_internal
;
474 // associate the thread pointer with the newly created thread so that
475 // wxThread::This() will work
476 int rc
= pthread_setspecific(gs_keySelf
, thread
);
479 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
484 #if HAVE_THREAD_CLEANUP_FUNCTIONS
485 // install the cleanup handler which will be called if the thread is
487 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
488 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
490 // wait for the condition to be signaled from Run()
491 pthread
->m_condRun
.Wait();
493 // call the main entry
494 pthread
->m_exitcode
= thread
->Entry();
496 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
500 wxCriticalSectionLocker
lock(thread
->m_critsect
);
502 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
505 // change the state of the thread to "exited" so that PthreadCleanup
506 // handler won't do anything from now (if it's called before we do
507 // pthread_cleanup_pop below)
508 pthread
->SetState(STATE_EXITED
);
511 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
512 // contains the matching '}' for the '{' in push, so they must be used
513 // in the same block!
514 #if HAVE_THREAD_CLEANUP_FUNCTIONS
515 // remove the cleanup handler without executing it
516 pthread_cleanup_pop(FALSE
);
517 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
519 // terminate the thread
520 thread
->Exit(pthread
->m_exitcode
);
522 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
527 #if HAVE_THREAD_CLEANUP_FUNCTIONS
529 // this handler is called when the thread is cancelled
530 void wxThreadInternal::PthreadCleanup(void *ptr
)
532 wxThread
*thread
= (wxThread
*) ptr
;
535 wxCriticalSectionLocker
lock(thread
->m_critsect
);
536 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
538 // thread is already considered as finished.
543 // exit the thread gracefully
544 thread
->Exit(EXITCODE_CANCELLED
);
547 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
549 // ----------------------------------------------------------------------------
551 // ----------------------------------------------------------------------------
553 wxThreadInternal::wxThreadInternal()
557 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
561 // defaults for joinable threads
562 m_shouldBeJoined
= TRUE
;
563 m_shouldBroadcast
= TRUE
;
566 wxThreadInternal::~wxThreadInternal()
570 wxThreadError
wxThreadInternal::Run()
572 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
573 wxT("thread may only be started once after Create()") );
577 SetState(STATE_RUNNING
);
579 return wxTHREAD_NO_ERROR
;
582 void wxThreadInternal::Wait()
584 // if the thread we're waiting for is waiting for the GUI mutex, we will
585 // deadlock so make sure we release it temporarily
586 if ( wxThread::IsMain() )
589 // wait until the thread terminates (we're blocking in _another_ thread,
593 // to avoid memory leaks we should call pthread_join(), but it must only
595 wxCriticalSectionLocker
lock(m_csJoinFlag
);
597 if ( m_shouldBeJoined
)
599 // FIXME shouldn't we set cancellation type to DISABLED here? If we're
600 // cancelled inside pthread_join(), things will almost certainly
601 // break - but if we disable the cancellation, we might deadlock
602 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
604 wxLogError(_T("Failed to join a thread, potential memory leak "
605 "detected - please restart the program"));
608 m_shouldBeJoined
= FALSE
;
611 // reacquire GUI mutex
612 if ( wxThread::IsMain() )
616 void wxThreadInternal::SignalExit()
618 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
620 SetState(STATE_EXITED
);
622 // wake up all the threads waiting for our termination - if there are any
623 if ( m_shouldBroadcast
)
625 m_condEnd
.Broadcast();
629 void wxThreadInternal::Pause()
631 // the state is set from the thread which pauses us first, this function
632 // is called later so the state should have been already set
633 wxCHECK_RET( m_state
== STATE_PAUSED
,
634 wxT("thread must first be paused with wxThread::Pause().") );
636 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
638 // wait until the condition is signaled from Resume()
639 m_condSuspend
.Wait();
642 void wxThreadInternal::Resume()
644 wxCHECK_RET( m_state
== STATE_PAUSED
,
645 wxT("can't resume thread which is not suspended.") );
647 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
650 m_condSuspend
.Signal();
652 SetState(STATE_RUNNING
);
655 // -----------------------------------------------------------------------------
656 // wxThread static functions
657 // -----------------------------------------------------------------------------
659 wxThread
*wxThread::This()
661 return (wxThread
*)pthread_getspecific(gs_keySelf
);
664 bool wxThread::IsMain()
666 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
669 void wxThread::Yield()
674 void wxThread::Sleep(unsigned long milliseconds
)
676 wxUsleep(milliseconds
);
679 // -----------------------------------------------------------------------------
681 // -----------------------------------------------------------------------------
683 wxThread::wxThread(wxThreadKind kind
)
685 // add this thread to the global list of all threads
686 gs_allThreads
.Add(this);
688 m_internal
= new wxThreadInternal();
690 m_isDetached
= kind
== wxTHREAD_DETACHED
;
693 wxThreadError
wxThread::Create()
695 if ( m_internal
->GetState() != STATE_NEW
)
697 // don't recreate thread
698 return wxTHREAD_RUNNING
;
701 // set up the thread attribute: right now, we only set thread priority
703 pthread_attr_init(&attr
);
705 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
707 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
709 wxLogError(_("Cannot retrieve thread scheduling policy."));
712 int min_prio
= sched_get_priority_min(policy
),
713 max_prio
= sched_get_priority_max(policy
),
714 prio
= m_internal
->GetPriority();
716 if ( min_prio
== -1 || max_prio
== -1 )
718 wxLogError(_("Cannot get priority range for scheduling policy %d."),
721 else if ( max_prio
== min_prio
)
723 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
725 // notify the programmer that this doesn't work here
726 wxLogWarning(_("Thread priority setting is ignored."));
728 //else: we have default priority, so don't complain
730 // anyhow, don't do anything because priority is just ignored
734 struct sched_param sp
;
735 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
737 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
740 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
742 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
744 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
747 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
749 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
750 // this will make the threads created by this process really concurrent
751 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
753 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
755 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
757 // VZ: assume that this one is always available (it's rather fundamental),
758 // if this function is ever missing we should try to use
759 // pthread_detach() instead (after thread creation)
762 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
764 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
767 // never try to join detached threads
768 m_internal
->Detach();
770 //else: threads are created joinable by default, it's ok
772 // create the new OS thread object
773 int rc
= pthread_create
775 m_internal
->GetIdPtr(),
777 wxThreadInternal::PthreadStart
,
781 if ( pthread_attr_destroy(&attr
) != 0 )
783 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
788 m_internal
->SetState(STATE_EXITED
);
790 return wxTHREAD_NO_RESOURCE
;
793 return wxTHREAD_NO_ERROR
;
796 wxThreadError
wxThread::Run()
798 wxCriticalSectionLocker
lock(m_critsect
);
800 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
801 wxT("must call wxThread::Create() first") );
803 return m_internal
->Run();
806 // -----------------------------------------------------------------------------
808 // -----------------------------------------------------------------------------
810 void wxThread::SetPriority(unsigned int prio
)
812 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
813 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
814 wxT("invalid thread priority") );
816 wxCriticalSectionLocker
lock(m_critsect
);
818 switch ( m_internal
->GetState() )
821 // thread not yet started, priority will be set when it is
822 m_internal
->SetPriority(prio
);
827 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
829 struct sched_param sparam
;
830 sparam
.sched_priority
= prio
;
832 if ( pthread_setschedparam(m_internal
->GetId(),
833 SCHED_OTHER
, &sparam
) != 0 )
835 wxLogError(_("Failed to set thread priority %d."), prio
);
838 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
843 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
847 unsigned int wxThread::GetPriority() const
849 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
851 return m_internal
->GetPriority();
854 unsigned long wxThread::GetId() const
856 return (unsigned long)m_internal
->GetId();
859 // -----------------------------------------------------------------------------
861 // -----------------------------------------------------------------------------
863 wxThreadError
wxThread::Pause()
865 wxCriticalSectionLocker
lock(m_critsect
);
867 if ( m_internal
->GetState() != STATE_RUNNING
)
869 wxLogDebug(wxT("Can't pause thread which is not running."));
871 return wxTHREAD_NOT_RUNNING
;
874 // just set a flag, the thread will be really paused only during the next
875 // call to TestDestroy()
876 m_internal
->SetState(STATE_PAUSED
);
878 return wxTHREAD_NO_ERROR
;
881 wxThreadError
wxThread::Resume()
885 wxThreadState state
= m_internal
->GetState();
887 // the thread might be not actually paused yet - if there were no call to
888 // TestDestroy() since the last call to Pause(), so avoid that
889 // TestDestroy() deadlocks trying to enter m_critsect by leaving it before
896 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is suspended, resuming."),
899 m_internal
->Resume();
901 return wxTHREAD_NO_ERROR
;
904 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
906 return wxTHREAD_NO_ERROR
;
909 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
911 return wxTHREAD_MISC_ERROR
;
915 // -----------------------------------------------------------------------------
917 // -----------------------------------------------------------------------------
919 wxThread::ExitCode
wxThread::Wait()
921 wxCHECK_MSG( This() != this, (ExitCode
)-1,
922 _T("a thread can't wait for itself") );
924 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
925 _T("can't wait for detached thread") );
929 return m_internal
->GetExitCode();
932 wxThreadError
wxThread::Delete(ExitCode
*rc
)
935 wxThreadState state
= m_internal
->GetState();
937 // ask the thread to stop
938 m_internal
->SetCancelFlag();
942 // detached threads won't broadcast about their termination by default
943 // because usually nobody waits for them - but here we do, so ask the
944 // thread to notify us
945 m_internal
->Notify();
958 // resume the thread first (don't call our Resume() because this
959 // would dead lock when it tries to enter m_critsect)
960 m_internal
->Resume();
965 // wait until the thread stops
970 wxASSERT_MSG( !m_isDetached
,
971 _T("no return code for detached threads") );
973 // if it's a joinable thread, it's not deleted yet
974 *rc
= m_internal
->GetExitCode();
978 return wxTHREAD_NO_ERROR
;
981 wxThreadError
wxThread::Kill()
983 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
984 _T("a thread can't kill itself") );
986 switch ( m_internal
->GetState() )
990 return wxTHREAD_NOT_RUNNING
;
993 // resume the thread first
999 #ifdef HAVE_PTHREAD_CANCEL
1000 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1003 wxLogError(_("Failed to terminate a thread."));
1005 return wxTHREAD_MISC_ERROR
;
1010 // if we use cleanup function, this will be done from
1012 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1013 ScheduleThreadForDeletion();
1018 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1022 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1025 return wxTHREAD_NO_ERROR
;
1029 void wxThread::Exit(ExitCode status
)
1031 // from the moment we call OnExit(), the main program may terminate at any
1032 // moment, so mark this thread as being already in process of being
1033 // deleted or wxThreadModule::OnExit() will try to delete it again
1034 ScheduleThreadForDeletion();
1036 // don't enter m_critsect before calling OnExit() because the user code
1037 // might deadlock if, for example, it signals a condition in OnExit() (a
1038 // common case) while the main thread calls any of functions entering
1039 // m_critsect on us (almost all of them do)
1042 // now do enter it because SignalExit() will change our state
1045 // next wake up the threads waiting for us (OTOH, this function won't return
1046 // until someone waited for us!)
1047 m_internal
->SignalExit();
1049 // leave the critical section before entering the dtor which tries to
1053 // delete C++ thread object if this is a detached thread - user is
1054 // responsible for doing this for joinable ones
1057 // FIXME I'm feeling bad about it - what if another thread function is
1058 // called (in another thread context) now? It will try to access
1059 // half destroyed object which will probably result in something
1060 // very bad - but we can't protect this by a crit section unless
1061 // we make it a global object, but this would mean that we can
1062 // only call one thread function at a time :-(
1066 // terminate the thread (pthread_exit() never returns)
1067 pthread_exit(status
);
1069 wxFAIL_MSG(_T("pthread_exit() failed"));
1072 // also test whether we were paused
1073 bool wxThread::TestDestroy()
1077 if ( m_internal
->GetState() == STATE_PAUSED
)
1079 // leave the crit section or the other threads will stop too if they
1080 // try to call any of (seemingly harmless) IsXXX() functions while we
1084 m_internal
->Pause();
1088 // thread wasn't requested to pause, nothing to do
1092 return m_internal
->WasCancelled();
1095 wxThread::~wxThread()
1100 // check that the thread either exited or couldn't be created
1101 if ( m_internal
->GetState() != STATE_EXITED
&&
1102 m_internal
->GetState() != STATE_NEW
)
1104 wxLogDebug(_T("The thread is being destroyed although it is still "
1105 "running! The application may crash."));
1109 #endif // __WXDEBUG__
1113 // remove this thread from the global array
1114 gs_allThreads
.Remove(this);
1117 // -----------------------------------------------------------------------------
1119 // -----------------------------------------------------------------------------
1121 bool wxThread::IsRunning() const
1123 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1125 return m_internal
->GetState() == STATE_RUNNING
;
1128 bool wxThread::IsAlive() const
1130 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1132 switch ( m_internal
->GetState() )
1143 bool wxThread::IsPaused() const
1145 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1147 return (m_internal
->GetState() == STATE_PAUSED
);
1150 //--------------------------------------------------------------------
1152 //--------------------------------------------------------------------
1154 class wxThreadModule
: public wxModule
1157 virtual bool OnInit();
1158 virtual void OnExit();
1161 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1164 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1166 bool wxThreadModule::OnInit()
1168 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1171 wxLogSysError(rc
, _("Thread module initialization failed: "
1172 "failed to create thread key"));
1177 gs_tidMain
= pthread_self();
1180 gs_mutexGui
= new wxMutex();
1182 gs_mutexGui
->Lock();
1188 void wxThreadModule::OnExit()
1190 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1192 // are there any threads left which are being deleted right now?
1193 size_t nThreadsBeingDeleted
;
1195 MutexLock
lock(gs_mutexDeleteThread
);
1196 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1199 if ( nThreadsBeingDeleted
> 0 )
1201 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1202 nThreadsBeingDeleted
);
1204 // have to wait until all of them disappear
1205 gs_condAllDeleted
->Wait();
1208 // terminate any threads left
1209 size_t count
= gs_allThreads
.GetCount();
1211 wxLogDebug(wxT("Some threads were not terminated by the application."));
1213 for ( size_t n
= 0u; n
< count
; n
++ )
1215 // Delete calls the destructor which removes the current entry. We
1216 // should only delete the first one each time.
1217 gs_allThreads
[0]->Delete();
1221 // destroy GUI mutex
1222 gs_mutexGui
->Unlock();
1227 // and free TLD slot
1228 (void)pthread_key_delete(gs_keySelf
);
1231 // ----------------------------------------------------------------------------
1233 // ----------------------------------------------------------------------------
1235 static void ScheduleThreadForDeletion()
1237 MutexLock
lock(gs_mutexDeleteThread
);
1239 if ( gs_nThreadsBeingDeleted
== 0 )
1241 gs_condAllDeleted
= new wxCondition
;
1244 gs_nThreadsBeingDeleted
++;
1246 wxLogTrace(TRACE_THREADS
, _T("%u threads waiting to be deleted"),
1247 gs_nThreadsBeingDeleted
);
1250 static void DeleteThread(wxThread
*This
)
1252 // gs_mutexDeleteThread should be unlocked before signalling the condition
1253 // or wxThreadModule::OnExit() would deadlock
1255 MutexLock
lock(gs_mutexDeleteThread
);
1257 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1261 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1262 _T("no threads scheduled for deletion, yet we delete "
1266 if ( !--gs_nThreadsBeingDeleted
)
1268 // no more threads left, signal it
1269 gs_condAllDeleted
->Signal();
1271 delete gs_condAllDeleted
;
1272 gs_condAllDeleted
= (wxCondition
*)NULL
;
1276 void wxMutexGuiEnter()
1279 gs_mutexGui
->Lock();
1283 void wxMutexGuiLeave()
1286 gs_mutexGui
->Unlock();