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 #ifdef HAVE_THR_SETCONCURRENCY
52 // we use wxFFile under Linux in GetCPUCount()
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
61 // the possible states of the thread and transitions from them
64 STATE_NEW
, // didn't start execution yet (=> RUNNING)
65 STATE_RUNNING
, // running (=> PAUSED or EXITED)
66 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
67 STATE_EXITED
// thread doesn't exist any more
70 // the exit value of a thread which has been cancelled
71 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
74 #define TRACE_THREADS _T("thread")
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 static void ScheduleThreadForDeletion();
81 static void DeleteThread(wxThread
*This
);
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 // same as wxMutexLocker but for "native" mutex
91 MutexLock(pthread_mutex_t
& mutex
)
94 if ( pthread_mutex_lock(m_mutex
) != 0 )
96 wxLogDebug(_T("pthread_mutex_lock() failed"));
102 if ( pthread_mutex_unlock(m_mutex
) != 0 )
104 wxLogDebug(_T("pthread_mutex_unlock() failed"));
109 pthread_mutex_t
*m_mutex
;
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
118 // -----------------------------------------------------------------------------
120 // -----------------------------------------------------------------------------
122 // we keep the list of all threads created by the application to be able to
123 // terminate them on exit if there are some left - otherwise the process would
125 static wxArrayThread gs_allThreads
;
127 // the id of the main thread
128 static pthread_t gs_tidMain
;
130 // the key for the pointer to the associated wxThread object
131 static pthread_key_t gs_keySelf
;
133 // the number of threads which are being deleted - the program won't exit
134 // until there are any left
135 static size_t gs_nThreadsBeingDeleted
= 0;
137 // a mutex to protect gs_nThreadsBeingDeleted
138 static pthread_mutex_t gs_mutexDeleteThread
;
140 // and a condition variable which will be signaled when all
141 // gs_nThreadsBeingDeleted will have been deleted
142 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
145 // this mutex must be acquired before any call to a GUI function
146 static wxMutex
*gs_mutexGui
;
149 // ============================================================================
151 // ============================================================================
153 //--------------------------------------------------------------------
154 // wxMutex (Posix implementation)
155 //--------------------------------------------------------------------
157 class wxMutexInternal
160 pthread_mutex_t m_mutex
;
165 m_internal
= new wxMutexInternal
;
167 // support recursive locks like Win32, i.e. a thread can lock a mutex which
168 // it had itself already locked
169 pthread_mutexattr_t attr
;
170 pthread_mutexattr_init(&attr
);
171 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
172 pthread_mutex_init(&(m_internal
->m_mutex
), &attr
);
180 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
182 pthread_mutex_destroy( &(m_internal
->m_mutex
) );
186 wxMutexError
wxMutex::Lock()
188 int err
= pthread_mutex_lock( &(m_internal
->m_mutex
) );
191 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
193 return wxMUTEX_DEAD_LOCK
;
198 return wxMUTEX_NO_ERROR
;
201 wxMutexError
wxMutex::TryLock()
208 int err
= pthread_mutex_trylock( &(m_internal
->m_mutex
) );
211 case EBUSY
: return wxMUTEX_BUSY
;
216 return wxMUTEX_NO_ERROR
;
219 wxMutexError
wxMutex::Unlock()
227 wxLogDebug(wxT("Unlocking not locked mutex."));
229 return wxMUTEX_UNLOCKED
;
232 pthread_mutex_unlock( &(m_internal
->m_mutex
) );
234 return wxMUTEX_NO_ERROR
;
237 //--------------------------------------------------------------------
238 // wxCondition (Posix implementation)
239 //--------------------------------------------------------------------
241 // The native POSIX condition variables are dumb: if the condition is signaled
242 // before another thread starts to wait on it, the signal is lost and so this
243 // other thread will be never woken up. It's much more convenient to us to
244 // remember that the condition was signaled and to return from Wait()
245 // immediately in this case (this is more like Win32 automatic event objects)
247 class wxConditionInternal
250 wxConditionInternal();
251 ~wxConditionInternal();
254 bool WaitWithTimeout(const timespec
* ts
);
264 bool m_wasSignaled
; // TRUE if condition was signaled while
265 // nobody waited for it
266 size_t m_nWaiters
; // TRUE if someone already waits for us
268 pthread_mutex_t m_mutexProtect
; // protects access to vars above
270 pthread_mutex_t m_mutex
; // the mutex used with the condition
271 pthread_cond_t m_condition
; // the condition itself
274 wxConditionInternal::wxConditionInternal()
276 m_wasSignaled
= FALSE
;
279 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
281 // this is supposed to never happen
282 wxFAIL_MSG( _T("pthread_cond_init() failed") );
285 if ( pthread_mutex_init(&m_mutex
, (pthread_mutexattr_t
*)NULL
) != 0 ||
286 pthread_mutex_init(&m_mutexProtect
, NULL
) != 0 )
289 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
292 // initially the mutex is locked, so no thread can Signal() or Broadcast()
293 // until another thread starts to Wait()
294 if ( pthread_mutex_lock(&m_mutex
) != 0 )
296 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
300 wxConditionInternal::~wxConditionInternal()
302 if ( pthread_cond_destroy( &m_condition
) != 0 )
304 wxLogDebug(_T("Failed to destroy condition variable (some "
305 "threads are probably still waiting on it?)"));
308 if ( pthread_mutex_unlock( &m_mutex
) != 0 )
310 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
313 if ( pthread_mutex_destroy( &m_mutex
) != 0 ||
314 pthread_mutex_destroy( &m_mutexProtect
) != 0 )
316 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
320 void wxConditionInternal::WaitDone()
322 MutexLock
lock(m_mutexProtect
);
324 m_wasSignaled
= FALSE
;
328 bool wxConditionInternal::ShouldWait()
330 MutexLock
lock(m_mutexProtect
);
334 // the condition was signaled before we started to wait, reset the
336 m_wasSignaled
= FALSE
;
341 // we start to wait for it
347 bool wxConditionInternal::HasWaiters()
349 MutexLock
lock(m_mutexProtect
);
353 // someone waits for us, signal the condition normally
357 // nobody waits for us and may be never will - so just remember that the
358 // condition was signaled and don't do anything else
359 m_wasSignaled
= TRUE
;
364 void wxConditionInternal::Wait()
368 if ( pthread_cond_wait( &m_condition
, &m_mutex
) != 0 )
370 // not supposed to ever happen
371 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
378 bool wxConditionInternal::WaitWithTimeout(const timespec
* ts
)
384 switch ( pthread_cond_timedwait( &m_condition
, &m_mutex
, ts
) )
387 // condition signaled
392 wxLogDebug(_T("pthread_cond_timedwait() failed"));
398 // wait interrupted or timeout elapsed
404 // the condition had already been signaled before
413 void wxConditionInternal::Signal()
417 MutexLock
lock(m_mutex
);
419 if ( pthread_cond_signal( &m_condition
) != 0 )
421 // shouldn't ever happen
422 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
427 void wxConditionInternal::Broadcast()
431 MutexLock
lock(m_mutex
);
433 if ( pthread_cond_broadcast( &m_condition
) != 0 )
435 // shouldn't ever happen
436 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
441 wxCondition::wxCondition()
443 m_internal
= new wxConditionInternal
;
446 wxCondition::~wxCondition()
451 void wxCondition::Wait()
456 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
460 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
461 tspec
.tv_nsec
= nsec
;
463 return m_internal
->WaitWithTimeout(&tspec
);
466 void wxCondition::Signal()
468 m_internal
->Signal();
471 void wxCondition::Broadcast()
473 m_internal
->Broadcast();
476 //--------------------------------------------------------------------
477 // wxThread (Posix implementation)
478 //--------------------------------------------------------------------
480 class wxThreadInternal
486 // thread entry function
487 static void *PthreadStart(void *ptr
);
489 #if HAVE_THREAD_CLEANUP_FUNCTIONS
490 // thread exit function
491 static void PthreadCleanup(void *ptr
);
497 // ask the thread to terminate
499 // wake up threads waiting for our termination
501 // wake up threads waiting for our start
502 void SignalRun() { m_condRun
.Signal(); }
503 // go to sleep until Resume() is called
510 int GetPriority() const { return m_prio
; }
511 void SetPriority(int prio
) { m_prio
= prio
; }
513 wxThreadState
GetState() const { return m_state
; }
514 void SetState(wxThreadState state
) { m_state
= state
; }
516 pthread_t
GetId() const { return m_threadId
; }
517 pthread_t
*GetIdPtr() { return &m_threadId
; }
519 void SetCancelFlag() { m_cancelled
= TRUE
; }
520 bool WasCancelled() const { return m_cancelled
; }
522 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
523 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
526 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
527 bool IsReallyPaused() const { return m_isPaused
; }
529 // tell the thread that it is a detached one
532 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
535 // but even detached threads need to notifyus about their termination
536 // sometimes - tell the thread that it should do it
537 void Notify() { m_shouldBroadcast
= TRUE
; }
540 pthread_t m_threadId
; // id of the thread
541 wxThreadState m_state
; // see wxThreadState enum
542 int m_prio
; // in wxWindows units: from 0 to 100
544 // this flag is set when the thread should terminate
547 // this flag is set when the thread is blocking on m_condSuspend
550 // the thread exit code - only used for joinable (!detached) threads and
551 // is only valid after the thread termination
552 wxThread::ExitCode m_exitcode
;
554 // many threads may call Wait(), but only one of them should call
555 // pthread_join(), so we have to keep track of this
556 wxCriticalSection m_csJoinFlag
;
557 bool m_shouldBeJoined
;
558 bool m_shouldBroadcast
;
561 // VZ: it's possible that we might do with less than three different
562 // condition objects - for example, m_condRun and m_condEnd a priori
563 // won't be used in the same time. But for now I prefer this may be a
564 // bit less efficient but safer solution of having distinct condition
565 // variables for each purpose.
567 // this condition is signaled by Run() and the threads Entry() is not
568 // called before it is done
569 wxCondition m_condRun
;
571 // this one is signaled when the thread should resume after having been
573 wxCondition m_condSuspend
;
575 // finally this one is signalled when the thread exits
576 wxCondition m_condEnd
;
579 // ----------------------------------------------------------------------------
580 // thread startup and exit functions
581 // ----------------------------------------------------------------------------
583 void *wxThreadInternal::PthreadStart(void *ptr
)
585 wxThread
*thread
= (wxThread
*)ptr
;
586 wxThreadInternal
*pthread
= thread
->m_internal
;
588 // associate the thread pointer with the newly created thread so that
589 // wxThread::This() will work
590 int rc
= pthread_setspecific(gs_keySelf
, thread
);
593 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
598 // have to declare this before pthread_cleanup_push() which defines a
602 #if HAVE_THREAD_CLEANUP_FUNCTIONS
603 // install the cleanup handler which will be called if the thread is
605 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
606 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
608 // wait for the condition to be signaled from Run()
609 pthread
->m_condRun
.Wait();
611 // test whether we should run the run at all - may be it was deleted
612 // before it started to Run()?
614 wxCriticalSectionLocker
lock(thread
->m_critsect
);
616 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
617 pthread
->WasCancelled();
622 // call the main entry
623 pthread
->m_exitcode
= thread
->Entry();
625 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
629 wxCriticalSectionLocker
lock(thread
->m_critsect
);
631 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
634 // change the state of the thread to "exited" so that
635 // PthreadCleanup handler won't do anything from now (if it's
636 // called before we do pthread_cleanup_pop below)
637 pthread
->SetState(STATE_EXITED
);
641 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
642 // contains the matching '}' for the '{' in push, so they must be used
643 // in the same block!
644 #if HAVE_THREAD_CLEANUP_FUNCTIONS
645 // remove the cleanup handler without executing it
646 pthread_cleanup_pop(FALSE
);
647 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
653 return EXITCODE_CANCELLED
;
657 // terminate the thread
658 thread
->Exit(pthread
->m_exitcode
);
660 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
666 #if HAVE_THREAD_CLEANUP_FUNCTIONS
668 // this handler is called when the thread is cancelled
669 void wxThreadInternal::PthreadCleanup(void *ptr
)
671 wxThread
*thread
= (wxThread
*) ptr
;
674 wxCriticalSectionLocker
lock(thread
->m_critsect
);
675 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
677 // thread is already considered as finished.
682 // exit the thread gracefully
683 thread
->Exit(EXITCODE_CANCELLED
);
686 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
688 // ----------------------------------------------------------------------------
690 // ----------------------------------------------------------------------------
692 wxThreadInternal::wxThreadInternal()
696 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
700 // set to TRUE only when the thread starts waiting on m_condSuspend
703 // defaults for joinable threads
704 m_shouldBeJoined
= TRUE
;
705 m_shouldBroadcast
= TRUE
;
706 m_isDetached
= FALSE
;
709 wxThreadInternal::~wxThreadInternal()
713 wxThreadError
wxThreadInternal::Run()
715 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
716 wxT("thread may only be started once after Create()") );
720 SetState(STATE_RUNNING
);
722 return wxTHREAD_NO_ERROR
;
725 void wxThreadInternal::Wait()
727 // if the thread we're waiting for is waiting for the GUI mutex, we will
728 // deadlock so make sure we release it temporarily
729 if ( wxThread::IsMain() )
732 bool isDetached
= m_isDetached
;
733 long id
= (long)GetId();
734 wxLogTrace(TRACE_THREADS
, _T("Starting to wait for thread %ld to exit."),
737 // wait until the thread terminates (we're blocking in _another_ thread,
741 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
743 // we can't use any member variables any more if the thread is detached
744 // because it could be already deleted
747 // to avoid memory leaks we should call pthread_join(), but it must
749 wxCriticalSectionLocker
lock(m_csJoinFlag
);
751 if ( m_shouldBeJoined
)
753 // FIXME shouldn't we set cancellation type to DISABLED here? If
754 // we're cancelled inside pthread_join(), things will almost
755 // certainly break - but if we disable the cancellation, we
757 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
759 wxLogError(_("Failed to join a thread, potential memory leak "
760 "detected - please restart the program"));
763 m_shouldBeJoined
= FALSE
;
767 // reacquire GUI mutex
768 if ( wxThread::IsMain() )
772 void wxThreadInternal::SignalExit()
774 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
776 SetState(STATE_EXITED
);
778 // wake up all the threads waiting for our termination - if there are any
779 if ( m_shouldBroadcast
)
781 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
784 m_condEnd
.Broadcast();
788 void wxThreadInternal::Pause()
790 // the state is set from the thread which pauses us first, this function
791 // is called later so the state should have been already set
792 wxCHECK_RET( m_state
== STATE_PAUSED
,
793 wxT("thread must first be paused with wxThread::Pause().") );
795 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
797 // wait until the condition is signaled from Resume()
798 m_condSuspend
.Wait();
801 void wxThreadInternal::Resume()
803 wxCHECK_RET( m_state
== STATE_PAUSED
,
804 wxT("can't resume thread which is not suspended.") );
806 // the thread might be not actually paused yet - if there were no call to
807 // TestDestroy() since the last call to Pause() for example
808 if ( IsReallyPaused() )
810 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
813 m_condSuspend
.Signal();
816 SetReallyPaused(FALSE
);
820 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
824 SetState(STATE_RUNNING
);
827 // -----------------------------------------------------------------------------
828 // wxThread static functions
829 // -----------------------------------------------------------------------------
831 wxThread
*wxThread::This()
833 return (wxThread
*)pthread_getspecific(gs_keySelf
);
836 bool wxThread::IsMain()
838 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
841 void wxThread::Yield()
843 #ifdef HAVE_SCHED_YIELD
848 void wxThread::Sleep(unsigned long milliseconds
)
850 wxUsleep(milliseconds
);
853 int wxThread::GetCPUCount()
855 #if defined(__LINUX__)
856 // read from proc (can't use wxTextFile here because it's a special file:
857 // it has 0 size but still can be read from)
860 wxFFile
file(_T("/proc/cpuinfo"));
861 if ( file
.IsOpened() )
863 // slurp the whole file
865 if ( file
.ReadAll(&s
) )
867 // (ab)use Replace() to find the number of "processor" strings
868 size_t count
= s
.Replace(_T("processor"), _T(""));
874 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
878 wxLogDebug(_T("failed to read /proc/cpuinfo"));
881 #elif defined(_SC_NPROCESSORS_ONLN)
882 // this works for Solaris
883 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
888 #endif // different ways to get number of CPUs
894 bool wxThread::SetConcurrency(size_t level
)
896 #ifdef HAVE_THR_SETCONCURRENCY
897 int rc
= thr_setconcurrency(level
);
900 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
904 #else // !HAVE_THR_SETCONCURRENCY
905 // ok only for the default value
907 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
910 // -----------------------------------------------------------------------------
912 // -----------------------------------------------------------------------------
914 wxThread::wxThread(wxThreadKind kind
)
916 // add this thread to the global list of all threads
917 gs_allThreads
.Add(this);
919 m_internal
= new wxThreadInternal();
921 m_isDetached
= kind
== wxTHREAD_DETACHED
;
924 wxThreadError
wxThread::Create()
926 if ( m_internal
->GetState() != STATE_NEW
)
928 // don't recreate thread
929 return wxTHREAD_RUNNING
;
932 // set up the thread attribute: right now, we only set thread priority
934 pthread_attr_init(&attr
);
936 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
938 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
940 wxLogError(_("Cannot retrieve thread scheduling policy."));
944 /* the pthread.h contains too many spaces. This is a work-around */
945 # undef sched_get_priority_max
946 #undef sched_get_priority_min
947 #define sched_get_priority_max(_pol_) \
948 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
949 #define sched_get_priority_min(_pol_) \
950 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
953 int max_prio
= sched_get_priority_max(policy
),
954 min_prio
= sched_get_priority_min(policy
),
955 prio
= m_internal
->GetPriority();
957 if ( min_prio
== -1 || max_prio
== -1 )
959 wxLogError(_("Cannot get priority range for scheduling policy %d."),
962 else if ( max_prio
== min_prio
)
964 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
966 // notify the programmer that this doesn't work here
967 wxLogWarning(_("Thread priority setting is ignored."));
969 //else: we have default priority, so don't complain
971 // anyhow, don't do anything because priority is just ignored
975 struct sched_param sp
;
976 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
978 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
981 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
983 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
985 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
988 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
990 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
991 // this will make the threads created by this process really concurrent
992 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
994 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
996 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
998 // VZ: assume that this one is always available (it's rather fundamental),
999 // if this function is ever missing we should try to use
1000 // pthread_detach() instead (after thread creation)
1003 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1005 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1008 // never try to join detached threads
1009 m_internal
->Detach();
1011 //else: threads are created joinable by default, it's ok
1013 // create the new OS thread object
1014 int rc
= pthread_create
1016 m_internal
->GetIdPtr(),
1018 wxThreadInternal::PthreadStart
,
1022 if ( pthread_attr_destroy(&attr
) != 0 )
1024 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1029 m_internal
->SetState(STATE_EXITED
);
1031 return wxTHREAD_NO_RESOURCE
;
1034 return wxTHREAD_NO_ERROR
;
1037 wxThreadError
wxThread::Run()
1039 wxCriticalSectionLocker
lock(m_critsect
);
1041 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1042 wxT("must call wxThread::Create() first") );
1044 return m_internal
->Run();
1047 // -----------------------------------------------------------------------------
1049 // -----------------------------------------------------------------------------
1051 void wxThread::SetPriority(unsigned int prio
)
1053 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1054 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1055 wxT("invalid thread priority") );
1057 wxCriticalSectionLocker
lock(m_critsect
);
1059 switch ( m_internal
->GetState() )
1062 // thread not yet started, priority will be set when it is
1063 m_internal
->SetPriority(prio
);
1068 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1070 struct sched_param sparam
;
1071 sparam
.sched_priority
= prio
;
1073 if ( pthread_setschedparam(m_internal
->GetId(),
1074 SCHED_OTHER
, &sparam
) != 0 )
1076 wxLogError(_("Failed to set thread priority %d."), prio
);
1079 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1084 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1088 unsigned int wxThread::GetPriority() const
1090 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1092 return m_internal
->GetPriority();
1095 unsigned long wxThread::GetId() const
1097 return (unsigned long)m_internal
->GetId();
1100 // -----------------------------------------------------------------------------
1102 // -----------------------------------------------------------------------------
1104 wxThreadError
wxThread::Pause()
1106 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1107 _T("a thread can't pause itself") );
1109 wxCriticalSectionLocker
lock(m_critsect
);
1111 if ( m_internal
->GetState() != STATE_RUNNING
)
1113 wxLogDebug(wxT("Can't pause thread which is not running."));
1115 return wxTHREAD_NOT_RUNNING
;
1118 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1121 // just set a flag, the thread will be really paused only during the next
1122 // call to TestDestroy()
1123 m_internal
->SetState(STATE_PAUSED
);
1125 return wxTHREAD_NO_ERROR
;
1128 wxThreadError
wxThread::Resume()
1130 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1131 _T("a thread can't resume itself") );
1133 wxCriticalSectionLocker
lock(m_critsect
);
1135 wxThreadState state
= m_internal
->GetState();
1140 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1143 m_internal
->Resume();
1145 return wxTHREAD_NO_ERROR
;
1148 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1150 return wxTHREAD_NO_ERROR
;
1153 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1155 return wxTHREAD_MISC_ERROR
;
1159 // -----------------------------------------------------------------------------
1161 // -----------------------------------------------------------------------------
1163 wxThread::ExitCode
wxThread::Wait()
1165 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1166 _T("a thread can't wait for itself") );
1168 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1169 _T("can't wait for detached thread") );
1173 return m_internal
->GetExitCode();
1176 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1178 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1179 _T("a thread can't delete itself") );
1182 wxThreadState state
= m_internal
->GetState();
1184 // ask the thread to stop
1185 m_internal
->SetCancelFlag();
1189 // detached threads won't broadcast about their termination by default
1190 // because usually nobody waits for them - but here we do, so ask the
1191 // thread to notify us
1192 m_internal
->Notify();
1200 // we need to wake up the thread so that PthreadStart() will
1201 // terminate - right now it's blocking on m_condRun
1202 m_internal
->SignalRun();
1211 // resume the thread first (don't call our Resume() because this
1212 // would dead lock when it tries to enter m_critsect)
1213 m_internal
->Resume();
1218 // wait until the thread stops
1223 wxASSERT_MSG( !m_isDetached
,
1224 _T("no return code for detached threads") );
1226 // if it's a joinable thread, it's not deleted yet
1227 *rc
= m_internal
->GetExitCode();
1231 return wxTHREAD_NO_ERROR
;
1234 wxThreadError
wxThread::Kill()
1236 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1237 _T("a thread can't kill itself") );
1239 switch ( m_internal
->GetState() )
1243 return wxTHREAD_NOT_RUNNING
;
1246 // resume the thread first
1252 #ifdef HAVE_PTHREAD_CANCEL
1253 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1256 wxLogError(_("Failed to terminate a thread."));
1258 return wxTHREAD_MISC_ERROR
;
1263 // if we use cleanup function, this will be done from
1265 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1266 ScheduleThreadForDeletion();
1268 // don't call OnExit() here, it can only be called in the
1269 // threads context and we're in the context of another thread
1272 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1276 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1279 return wxTHREAD_NO_ERROR
;
1283 void wxThread::Exit(ExitCode status
)
1285 wxASSERT_MSG( This() == this,
1286 _T("wxThread::Exit() can only be called in the "
1287 "context of the same thread") );
1289 // from the moment we call OnExit(), the main program may terminate at any
1290 // moment, so mark this thread as being already in process of being
1291 // deleted or wxThreadModule::OnExit() will try to delete it again
1292 ScheduleThreadForDeletion();
1294 // don't enter m_critsect before calling OnExit() because the user code
1295 // might deadlock if, for example, it signals a condition in OnExit() (a
1296 // common case) while the main thread calls any of functions entering
1297 // m_critsect on us (almost all of them do)
1300 // now do enter it because SignalExit() will change our state
1303 // next wake up the threads waiting for us (OTOH, this function won't return
1304 // until someone waited for us!)
1305 m_internal
->SignalExit();
1307 // leave the critical section before entering the dtor which tries to
1311 // delete C++ thread object if this is a detached thread - user is
1312 // responsible for doing this for joinable ones
1315 // FIXME I'm feeling bad about it - what if another thread function is
1316 // called (in another thread context) now? It will try to access
1317 // half destroyed object which will probably result in something
1318 // very bad - but we can't protect this by a crit section unless
1319 // we make it a global object, but this would mean that we can
1320 // only call one thread function at a time :-(
1324 // terminate the thread (pthread_exit() never returns)
1325 pthread_exit(status
);
1327 wxFAIL_MSG(_T("pthread_exit() failed"));
1330 // also test whether we were paused
1331 bool wxThread::TestDestroy()
1333 wxASSERT_MSG( This() == this,
1334 _T("wxThread::TestDestroy() can only be called in the "
1335 "context of the same thread") );
1339 if ( m_internal
->GetState() == STATE_PAUSED
)
1341 m_internal
->SetReallyPaused(TRUE
);
1343 // leave the crit section or the other threads will stop too if they
1344 // try to call any of (seemingly harmless) IsXXX() functions while we
1348 m_internal
->Pause();
1352 // thread wasn't requested to pause, nothing to do
1356 return m_internal
->WasCancelled();
1359 wxThread::~wxThread()
1364 // check that the thread either exited or couldn't be created
1365 if ( m_internal
->GetState() != STATE_EXITED
&&
1366 m_internal
->GetState() != STATE_NEW
)
1368 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1369 "running! The application may crash."), GetId());
1373 #endif // __WXDEBUG__
1377 // remove this thread from the global array
1378 gs_allThreads
.Remove(this);
1380 // detached thread will decrement this counter in DeleteThread(), but it
1381 // is not called for the joinable threads, so do it here
1382 if ( !m_isDetached
)
1384 MutexLock
lock(gs_mutexDeleteThread
);
1385 gs_nThreadsBeingDeleted
--;
1387 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1388 gs_nThreadsBeingDeleted
- 1);
1392 // -----------------------------------------------------------------------------
1394 // -----------------------------------------------------------------------------
1396 bool wxThread::IsRunning() const
1398 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1400 return m_internal
->GetState() == STATE_RUNNING
;
1403 bool wxThread::IsAlive() const
1405 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1407 switch ( m_internal
->GetState() )
1418 bool wxThread::IsPaused() const
1420 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1422 return (m_internal
->GetState() == STATE_PAUSED
);
1425 //--------------------------------------------------------------------
1427 //--------------------------------------------------------------------
1429 class wxThreadModule
: public wxModule
1432 virtual bool OnInit();
1433 virtual void OnExit();
1436 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1439 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1441 bool wxThreadModule::OnInit()
1443 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1446 wxLogSysError(rc
, _("Thread module initialization failed: "
1447 "failed to create thread key"));
1452 gs_tidMain
= pthread_self();
1455 gs_mutexGui
= new wxMutex();
1457 gs_mutexGui
->Lock();
1460 // under Solaris we get a warning from CC when using
1461 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1462 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1467 void wxThreadModule::OnExit()
1469 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1471 // are there any threads left which are being deleted right now?
1472 size_t nThreadsBeingDeleted
;
1474 MutexLock
lock(gs_mutexDeleteThread
);
1475 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1478 if ( nThreadsBeingDeleted
> 0 )
1480 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1481 nThreadsBeingDeleted
);
1483 // have to wait until all of them disappear
1484 gs_condAllDeleted
->Wait();
1487 // terminate any threads left
1488 size_t count
= gs_allThreads
.GetCount();
1491 wxLogDebug(wxT("%u threads were not terminated by the application."),
1495 for ( size_t n
= 0u; n
< count
; n
++ )
1497 // Delete calls the destructor which removes the current entry. We
1498 // should only delete the first one each time.
1499 gs_allThreads
[0]->Delete();
1503 // destroy GUI mutex
1504 gs_mutexGui
->Unlock();
1509 // and free TLD slot
1510 (void)pthread_key_delete(gs_keySelf
);
1513 // ----------------------------------------------------------------------------
1515 // ----------------------------------------------------------------------------
1517 static void ScheduleThreadForDeletion()
1519 MutexLock
lock(gs_mutexDeleteThread
);
1521 if ( gs_nThreadsBeingDeleted
== 0 )
1523 gs_condAllDeleted
= new wxCondition
;
1526 gs_nThreadsBeingDeleted
++;
1528 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1529 gs_nThreadsBeingDeleted
,
1530 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1533 static void DeleteThread(wxThread
*This
)
1535 // gs_mutexDeleteThread should be unlocked before signalling the condition
1536 // or wxThreadModule::OnExit() would deadlock
1538 MutexLock
lock(gs_mutexDeleteThread
);
1540 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1544 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1545 _T("no threads scheduled for deletion, yet we delete "
1549 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1550 gs_nThreadsBeingDeleted
- 1);
1552 if ( !--gs_nThreadsBeingDeleted
)
1554 // no more threads left, signal it
1555 gs_condAllDeleted
->Signal();
1557 delete gs_condAllDeleted
;
1558 gs_condAllDeleted
= (wxCondition
*)NULL
;
1562 void wxMutexGuiEnter()
1565 gs_mutexGui
->Lock();
1569 void wxMutexGuiLeave()
1572 gs_mutexGui
->Unlock();