1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
25 #pragma implementation "thread.h"
32 #include "wx/thread.h"
33 #include "wx/module.h"
37 #include "wx/dynarray.h"
49 #ifdef HAVE_THR_SETCONCURRENCY
53 // we use wxFFile under Linux in GetCPUCount()
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 // the possible states of the thread and transitions from them
65 STATE_NEW
, // didn't start execution yet (=> RUNNING)
66 STATE_RUNNING
, // running (=> PAUSED or EXITED)
67 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
68 STATE_EXITED
// thread doesn't exist any more
71 // the exit value of a thread which has been cancelled
72 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
75 #define TRACE_THREADS _T("thread")
77 // ----------------------------------------------------------------------------
79 // ----------------------------------------------------------------------------
81 static void ScheduleThreadForDeletion();
82 static void DeleteThread(wxThread
*This
);
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
90 // -----------------------------------------------------------------------------
92 // -----------------------------------------------------------------------------
94 // we keep the list of all threads created by the application to be able to
95 // terminate them on exit if there are some left - otherwise the process would
97 static wxArrayThread gs_allThreads
;
99 // the id of the main thread
100 static pthread_t gs_tidMain
;
102 // the key for the pointer to the associated wxThread object
103 static pthread_key_t gs_keySelf
;
105 // the number of threads which are being deleted - the program won't exit
106 // until there are any left
107 static size_t gs_nThreadsBeingDeleted
= 0;
109 // a mutex to protect gs_nThreadsBeingDeleted
110 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
112 // and a condition variable which will be signaled when all
113 // gs_nThreadsBeingDeleted will have been deleted
114 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
117 // this mutex must be acquired before any call to a GUI function
118 static wxMutex
*gs_mutexGui
;
121 // ============================================================================
122 // wxMutex implementation
123 // ============================================================================
125 // ----------------------------------------------------------------------------
127 // ----------------------------------------------------------------------------
129 class wxMutexInternal
136 wxMutexError
TryLock();
137 wxMutexError
Unlock();
140 pthread_mutex_t m_mutex
;
142 friend class wxConditionInternal
;
145 wxMutexInternal::wxMutexInternal()
147 // support recursive locks like Win32, i.e. a thread can lock a mutex which
148 // it had itself already locked
150 // but initialization of recursive mutexes is non portable <sigh>, so try
152 #ifdef HAVE_PTHREAD_MUTEXATTR_T
153 pthread_mutexattr_t attr
;
154 pthread_mutexattr_init(&attr
);
155 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
157 pthread_mutex_init(&m_mutex
, &attr
);
158 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
159 // we can use this only as initializer so we have to assign it first to a
160 // temp var - assigning directly to m_mutex wouldn't even compile
161 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
163 #else // no recursive mutexes
164 pthread_mutex_init(&m_mutex
, NULL
);
166 // used by TryLock() below
167 #define NO_RECURSIVE_MUTEXES
168 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
171 wxMutexInternal::~wxMutexInternal()
173 pthread_mutex_destroy(&m_mutex
);
176 wxMutexError
wxMutexInternal::Lock()
178 int err
= pthread_mutex_lock(&m_mutex
);
182 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
183 return wxMUTEX_DEAD_LOCK
;
186 wxFAIL_MSG( _T("unexpected pthread_mutex_lock() return") );
190 wxLogDebug(_T("Failed to lock the mutex."));
191 return wxMUTEX_MISC_ERROR
;
194 return wxMUTEX_NO_ERROR
;
198 wxMutexError
wxMutexInternal::TryLock()
200 int err
= pthread_mutex_trylock(&m_mutex
);
207 wxFAIL_MSG( _T("unexpected pthread_mutex_trylock() return") );
211 wxLogDebug(_T("Failed to try to lock the mutex."));
212 return wxMUTEX_MISC_ERROR
;
215 return wxMUTEX_NO_ERROR
;
219 wxMutexError
wxMutexInternal::Unlock()
221 int err
= pthread_mutex_unlock(&m_mutex
);
225 // we don't own the mutex
226 return wxMUTEX_UNLOCKED
;
229 wxFAIL_MSG( _T("unexpected pthread_mutex_unlock() return") );
233 wxLogDebug(_T("Failed to unlock the mutex."));
234 return wxMUTEX_MISC_ERROR
;
237 return wxMUTEX_NO_ERROR
;
241 // ----------------------------------------------------------------------------
243 // ----------------------------------------------------------------------------
245 // TODO: this is completely generic, move it to common code?
249 m_internal
= new wxMutexInternal
;
257 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
262 wxMutexError
wxMutex::Lock()
264 wxMutexError err
= m_internal
->Lock();
274 wxMutexError
wxMutex::TryLock()
278 #ifdef NO_RECURSIVE_MUTEXES
279 return wxMUTEX_DEAD_LOCK
;
280 #else // have recursive mutexes on this platform
281 // we will succeed in locking it when we have it already locked
282 return wxMUTEX_NO_ERROR
;
283 #endif // recursive/non-recursive mutexes
286 wxMutexError err
= m_internal
->TryLock();
295 wxMutexError
wxMutex::Unlock()
303 wxLogDebug(wxT("Unlocking not locked mutex."));
305 return wxMUTEX_UNLOCKED
;
308 return m_internal
->Unlock();
311 // ===========================================================================
312 // wxCondition implementation
313 // ===========================================================================
315 // ---------------------------------------------------------------------------
316 // wxConditionInternal
317 // ---------------------------------------------------------------------------
319 class wxConditionInternal
322 wxConditionInternal( wxMutex
*mutex
);
323 ~wxConditionInternal();
327 bool Wait( const timespec
*ts
);
336 pthread_cond_t m_cond
;
339 wxConditionInternal::wxConditionInternal( wxMutex
*mutex
)
342 if ( pthread_cond_init( &m_cond
, NULL
) != 0 )
344 wxLogDebug(_T("pthread_cond_init() failed"));
348 wxConditionInternal::~wxConditionInternal()
350 if ( pthread_cond_destroy( &m_cond
) != 0 )
352 wxLogDebug(_T("pthread_cond_destroy() failed"));
356 void wxConditionInternal::Wait()
358 if ( pthread_cond_wait( &m_cond
, &(m_mutex
->m_internal
->m_mutex
) ) != 0 )
360 wxLogDebug(_T("pthread_cond_wait() failed"));
364 bool wxConditionInternal::Wait( const timespec
*ts
)
366 int result
= pthread_cond_timedwait( &m_cond
,
367 &(m_mutex
->m_internal
->m_mutex
),
369 if ( result
== ETIMEDOUT
)
372 wxASSERT_MSG( result
== 0, _T("pthread_cond_timedwait() failed") );
377 void wxConditionInternal::Signal()
379 int result
= pthread_cond_signal( &m_cond
);
382 wxFAIL_MSG( _T("pthread_cond_signal() failed") );
386 void wxConditionInternal::Broadcast()
388 int result
= pthread_cond_broadcast( &m_cond
);
391 wxFAIL_MSG( _T("pthread_cond_broadcast() failed") );
396 // ---------------------------------------------------------------------------
398 // ---------------------------------------------------------------------------
400 wxCondition::wxCondition( wxMutex
*mutex
)
404 wxFAIL_MSG( _T("NULL mutex in wxCondition ctor") );
410 m_internal
= new wxConditionInternal( mutex
);
414 wxCondition::~wxCondition()
419 void wxCondition::Wait()
425 bool wxCondition::Wait( unsigned long timeout_millis
)
427 wxCHECK_MSG( m_internal
, FALSE
, _T("can't wait on uninitalized condition") );
429 wxLongLong curtime
= wxGetLocalTimeMillis();
430 curtime
+= timeout_millis
;
431 wxLongLong temp
= curtime
/ 1000;
432 int sec
= temp
.GetLo();
434 temp
= curtime
- temp
;
435 int millis
= temp
.GetLo();
440 tspec
.tv_nsec
= millis
* 1000L * 1000L;
442 return m_internal
->Wait(&tspec
);
445 void wxCondition::Signal()
448 m_internal
->Signal();
451 void wxCondition::Broadcast()
454 m_internal
->Broadcast();
457 // ===========================================================================
458 // wxSemaphore implementation
459 // ===========================================================================
461 // ---------------------------------------------------------------------------
462 // wxSemaphoreInternal
463 // ---------------------------------------------------------------------------
465 class wxSemaphoreInternal
468 wxSemaphoreInternal( int initialcount
, int maxcount
);
473 bool Wait( unsigned long timeout_millis
);
485 wxSemaphoreInternal::wxSemaphoreInternal( int initialcount
, int maxcount
)
489 if ( (initialcount
< 0) || ((maxcount
> 0) && (initialcount
> maxcount
)) )
491 wxFAIL_MSG( _T("wxSemaphore: invalid initial count") );
495 count
= initialcount
;
498 void wxSemaphoreInternal::Wait()
500 wxMutexLocker
locker(*m_mutex
);
510 bool wxSemaphoreInternal::TryWait()
512 wxMutexLocker
locker(*m_mutex
);
522 bool wxSemaphoreInternal::Wait( unsigned long timeout_millis
)
524 wxMutexLocker
locker( *m_mutex
);
526 wxLongLong startTime
= wxGetLocalTimeMillis();
530 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
531 long remainingTime
= (long)timeout_millis
- (long)elapsed
.GetLo();
532 if ( remainingTime
<= 0 )
535 bool result
= m_cond
->Wait( remainingTime
);
545 void wxSemaphoreInternal::Post()
547 wxMutexLocker
locker(*m_mutex
);
549 if ( (maxcount
> 0) && (count
== maxcount
) )
551 wxFAIL_MSG( _T("wxSemaphore::Post() overflow") );
559 // --------------------------------------------------------------------------
561 // --------------------------------------------------------------------------
563 wxSemaphore::wxSemaphore( int initialcount
, int maxcount
)
565 m_internal
= new wxSemaphoreInternal( initialcount
, maxcount
);
568 wxSemaphore::~wxSemaphore()
573 void wxSemaphore::Wait()
578 bool wxSemaphore::TryWait()
580 return m_internal
->TryWait();
583 bool wxSemaphore::Wait( unsigned long timeout_millis
)
585 return m_internal
->Wait( timeout_millis
);
588 void wxSemaphore::Post()
593 // This class is used by wxThreadInternal to support Delete() on
595 class wxRefCountedCondition
598 // start with a initial reference count of 1
599 wxRefCountedCondition()
604 m_mutex
= new wxMutex();
605 m_cond
= new wxCondition( m_mutex
);
608 // increment the reference count
611 wxMutexLocker
locker( *m_mutex
);
616 // decrement the reference count if reference count is zero then delete the
620 bool shouldDelete
= FALSE
;
624 if ( --m_refCount
== 0 )
638 // sets the object to signaled this signal will be a persistent signal all
639 // further Wait()s on the object will return without blocking
642 wxMutexLocker
locker( *m_mutex
);
649 // wait till the object is signaled if the object was already signaled then
650 // return immediately
653 wxMutexLocker
locker( *m_mutex
);
669 // Cannot delete this object directly, call DeleteRef() instead
670 ~wxRefCountedCondition()
676 // suppress gcc warning about the class having private dtor and not having
677 // friend (so what??)
678 friend class wxDummyFriend
;
681 // ===========================================================================
682 // wxThread implementation
683 // ===========================================================================
685 // the thread callback functions must have the C linkage
689 #if HAVE_THREAD_CLEANUP_FUNCTIONS
690 // thread exit function
691 void wxPthreadCleanup(void *ptr
);
692 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
694 void *wxPthreadStart(void *ptr
);
698 // ----------------------------------------------------------------------------
700 // ----------------------------------------------------------------------------
702 class wxThreadInternal
708 // thread entry function
709 static void *PthreadStart(wxThread
*thread
);
714 // ask the thread to terminate
716 // wake up threads waiting for our termination
718 // wake up threads waiting for our start
719 void SignalRun() { m_semRun
.Post(); }
720 // go to sleep until Resume() is called
727 int GetPriority() const { return m_prio
; }
728 void SetPriority(int prio
) { m_prio
= prio
; }
730 wxThreadState
GetState() const { return m_state
; }
731 void SetState(wxThreadState state
) { m_state
= state
; }
733 pthread_t
GetId() const { return m_threadId
; }
734 pthread_t
*GetIdPtr() { return &m_threadId
; }
736 void SetCancelFlag() { m_cancelled
= TRUE
; }
737 bool WasCancelled() const { return m_cancelled
; }
739 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
740 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
743 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
744 bool IsReallyPaused() const { return m_isPaused
; }
746 // tell the thread that it is a detached one
749 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
752 // but even detached threads need to notifyus about their termination
753 // sometimes - tell the thread that it should do it
754 void Notify() { m_shouldBroadcast
= TRUE
; }
756 #if HAVE_THREAD_CLEANUP_FUNCTIONS
757 // this is used by wxPthreadCleanup() only
758 static void Cleanup(wxThread
*thread
);
759 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
762 pthread_t m_threadId
; // id of the thread
763 wxThreadState m_state
; // see wxThreadState enum
764 int m_prio
; // in wxWindows units: from 0 to 100
766 // this flag is set when the thread should terminate
769 // this flag is set when the thread is blocking on m_semSuspend
772 // the thread exit code - only used for joinable (!detached) threads and
773 // is only valid after the thread termination
774 wxThread::ExitCode m_exitcode
;
776 // many threads may call Wait(), but only one of them should call
777 // pthread_join(), so we have to keep track of this
778 wxCriticalSection m_csJoinFlag
;
779 bool m_shouldBeJoined
;
780 bool m_shouldBroadcast
;
783 // this semaphore is posted by Run() and the threads Entry() is not
784 // called before it is done
785 wxSemaphore m_semRun
;
787 // this one is signaled when the thread should resume after having been
789 wxSemaphore m_semSuspend
;
791 // finally this one is signalled when the thread exits
792 // we are using a reference counted condition to support
793 // Delete() for a detached thread
794 wxRefCountedCondition
*m_condEnd
;
797 // ----------------------------------------------------------------------------
798 // thread startup and exit functions
799 // ----------------------------------------------------------------------------
801 void *wxPthreadStart(void *ptr
)
803 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
806 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
808 wxThreadInternal
*pthread
= thread
->m_internal
;
810 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), pthread
->GetId());
812 // associate the thread pointer with the newly created thread so that
813 // wxThread::This() will work
814 int rc
= pthread_setspecific(gs_keySelf
, thread
);
817 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
822 // have to declare this before pthread_cleanup_push() which defines a
826 #if HAVE_THREAD_CLEANUP_FUNCTIONS
827 // install the cleanup handler which will be called if the thread is
829 pthread_cleanup_push(wxPthreadCleanup
, thread
);
830 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
832 // wait for the semaphore to be posted from Run()
833 pthread
->m_semRun
.Wait();
835 // test whether we should run the run at all - may be it was deleted
836 // before it started to Run()?
838 wxCriticalSectionLocker
lock(thread
->m_critsect
);
840 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
841 pthread
->WasCancelled();
846 // call the main entry
847 pthread
->m_exitcode
= thread
->Entry();
849 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
853 wxCriticalSectionLocker
lock(thread
->m_critsect
);
855 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
858 // change the state of the thread to "exited" so that
859 // wxPthreadCleanup handler won't do anything from now (if it's
860 // called before we do pthread_cleanup_pop below)
861 pthread
->SetState(STATE_EXITED
);
865 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
866 // contains the matching '}' for the '{' in push, so they must be used
867 // in the same block!
868 #if HAVE_THREAD_CLEANUP_FUNCTIONS
869 // remove the cleanup handler without executing it
870 pthread_cleanup_pop(FALSE
);
871 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
877 return EXITCODE_CANCELLED
;
881 // terminate the thread
882 thread
->Exit(pthread
->m_exitcode
);
884 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
890 #if HAVE_THREAD_CLEANUP_FUNCTIONS
892 // this handler is called when the thread is cancelled
893 extern "C" void wxPthreadCleanup(void *ptr
)
895 wxThreadInternal::Cleanup((wxThread
*)ptr
);
898 void wxThreadInternal::Cleanup(wxThread
*thread
)
901 wxCriticalSectionLocker
lock(thread
->m_critsect
);
902 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
904 // thread is already considered as finished.
909 // exit the thread gracefully
910 thread
->Exit(EXITCODE_CANCELLED
);
913 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
915 // ----------------------------------------------------------------------------
917 // ----------------------------------------------------------------------------
919 wxThreadInternal::wxThreadInternal()
923 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
927 // set to TRUE only when the thread starts waiting on m_semSuspend
930 // defaults for joinable threads
931 m_shouldBeJoined
= TRUE
;
932 m_shouldBroadcast
= TRUE
;
933 m_isDetached
= FALSE
;
935 m_condEnd
= new wxRefCountedCondition();
938 wxThreadInternal::~wxThreadInternal()
940 m_condEnd
->DeleteRef();
943 wxThreadError
wxThreadInternal::Run()
945 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
946 wxT("thread may only be started once after Create()") );
950 SetState(STATE_RUNNING
);
952 return wxTHREAD_NO_ERROR
;
955 void wxThreadInternal::Wait()
957 // if the thread we're waiting for is waiting for the GUI mutex, we will
958 // deadlock so make sure we release it temporarily
959 if ( wxThread::IsMain() )
962 bool isDetached
= m_isDetached
;
963 wxThreadIdType id
= (wxThreadIdType
) GetId();
965 wxLogTrace(TRACE_THREADS
,
966 _T("Starting to wait for thread %ld to exit."), id
);
968 // wait until the thread terminates (we're blocking in _another_ thread,
971 // a reference counting condition is used to handle the
972 // case where a detached thread deletes itself
973 // before m_condEnd->Wait() returns
974 // in this case the deletion of the condition object is deferred until
975 // all Wait()ing threads have finished calling DeleteRef()
978 m_condEnd
->DeleteRef();
980 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
982 // we can't use any member variables any more if the thread is detached
983 // because it could be already deleted
986 // to avoid memory leaks we should call pthread_join(), but it must
988 wxCriticalSectionLocker
lock(m_csJoinFlag
);
990 if ( m_shouldBeJoined
)
992 // FIXME shouldn't we set cancellation type to DISABLED here? If
993 // we're cancelled inside pthread_join(), things will almost
994 // certainly break - but if we disable the cancellation, we
996 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
998 wxLogError(_("Failed to join a thread, potential memory leak "
999 "detected - please restart the program"));
1002 m_shouldBeJoined
= FALSE
;
1006 // reacquire GUI mutex
1007 if ( wxThread::IsMain() )
1011 void wxThreadInternal::SignalExit()
1013 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
1015 SetState(STATE_EXITED
);
1017 // wake up all the threads waiting for our termination - if there are any
1018 if ( m_shouldBroadcast
)
1020 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
1023 m_condEnd
->SetSignaled();
1027 void wxThreadInternal::Pause()
1029 // the state is set from the thread which pauses us first, this function
1030 // is called later so the state should have been already set
1031 wxCHECK_RET( m_state
== STATE_PAUSED
,
1032 wxT("thread must first be paused with wxThread::Pause().") );
1034 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
1036 // wait until the semaphore is Post()ed from Resume()
1037 m_semSuspend
.Wait();
1040 void wxThreadInternal::Resume()
1042 wxCHECK_RET( m_state
== STATE_PAUSED
,
1043 wxT("can't resume thread which is not suspended.") );
1045 // the thread might be not actually paused yet - if there were no call to
1046 // TestDestroy() since the last call to Pause() for example
1047 if ( IsReallyPaused() )
1049 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
1052 m_semSuspend
.Post();
1055 SetReallyPaused(FALSE
);
1059 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
1063 SetState(STATE_RUNNING
);
1066 // -----------------------------------------------------------------------------
1067 // wxThread static functions
1068 // -----------------------------------------------------------------------------
1070 wxThread
*wxThread::This()
1072 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1075 bool wxThread::IsMain()
1077 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
1080 void wxThread::Yield()
1082 #ifdef HAVE_SCHED_YIELD
1087 void wxThread::Sleep(unsigned long milliseconds
)
1089 wxUsleep(milliseconds
);
1092 int wxThread::GetCPUCount()
1094 #if defined(__LINUX__) && wxUSE_FFILE
1095 // read from proc (can't use wxTextFile here because it's a special file:
1096 // it has 0 size but still can be read from)
1099 wxFFile
file(_T("/proc/cpuinfo"));
1100 if ( file
.IsOpened() )
1102 // slurp the whole file
1104 if ( file
.ReadAll(&s
) )
1106 // (ab)use Replace() to find the number of "processor" strings
1107 size_t count
= s
.Replace(_T("processor"), _T(""));
1113 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1117 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1120 #elif defined(_SC_NPROCESSORS_ONLN)
1121 // this works for Solaris
1122 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1127 #endif // different ways to get number of CPUs
1134 // VMS is a 64 bit system and threads have 64 bit pointers.
1135 // ??? also needed for other systems????
1136 unsigned long long wxThread::GetCurrentId()
1138 return (unsigned long long)pthread_self();
1140 unsigned long wxThread::GetCurrentId()
1142 return (unsigned long)pthread_self();
1146 bool wxThread::SetConcurrency(size_t level
)
1148 #ifdef HAVE_THR_SETCONCURRENCY
1149 int rc
= thr_setconcurrency(level
);
1152 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1156 #else // !HAVE_THR_SETCONCURRENCY
1157 // ok only for the default value
1159 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1162 // -----------------------------------------------------------------------------
1164 // -----------------------------------------------------------------------------
1166 wxThread::wxThread(wxThreadKind kind
)
1168 // add this thread to the global list of all threads
1169 gs_allThreads
.Add(this);
1171 m_internal
= new wxThreadInternal();
1173 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1176 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1178 if ( m_internal
->GetState() != STATE_NEW
)
1180 // don't recreate thread
1181 return wxTHREAD_RUNNING
;
1184 // set up the thread attribute: right now, we only set thread priority
1185 pthread_attr_t attr
;
1186 pthread_attr_init(&attr
);
1188 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1190 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1192 wxLogError(_("Cannot retrieve thread scheduling policy."));
1196 /* the pthread.h contains too many spaces. This is a work-around */
1197 # undef sched_get_priority_max
1198 #undef sched_get_priority_min
1199 #define sched_get_priority_max(_pol_) \
1200 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1201 #define sched_get_priority_min(_pol_) \
1202 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1205 int max_prio
= sched_get_priority_max(policy
),
1206 min_prio
= sched_get_priority_min(policy
),
1207 prio
= m_internal
->GetPriority();
1209 if ( min_prio
== -1 || max_prio
== -1 )
1211 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1214 else if ( max_prio
== min_prio
)
1216 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1218 // notify the programmer that this doesn't work here
1219 wxLogWarning(_("Thread priority setting is ignored."));
1221 //else: we have default priority, so don't complain
1223 // anyhow, don't do anything because priority is just ignored
1227 struct sched_param sp
;
1228 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1230 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1233 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1235 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1237 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1240 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1242 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1243 // this will make the threads created by this process really concurrent
1244 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1246 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1248 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1250 // VZ: assume that this one is always available (it's rather fundamental),
1251 // if this function is ever missing we should try to use
1252 // pthread_detach() instead (after thread creation)
1255 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1257 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1260 // never try to join detached threads
1261 m_internal
->Detach();
1263 //else: threads are created joinable by default, it's ok
1265 // create the new OS thread object
1266 int rc
= pthread_create
1268 m_internal
->GetIdPtr(),
1274 if ( pthread_attr_destroy(&attr
) != 0 )
1276 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1281 m_internal
->SetState(STATE_EXITED
);
1283 return wxTHREAD_NO_RESOURCE
;
1286 return wxTHREAD_NO_ERROR
;
1289 wxThreadError
wxThread::Run()
1291 wxCriticalSectionLocker
lock(m_critsect
);
1293 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1294 wxT("must call wxThread::Create() first") );
1296 return m_internal
->Run();
1299 // -----------------------------------------------------------------------------
1301 // -----------------------------------------------------------------------------
1303 void wxThread::SetPriority(unsigned int prio
)
1305 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1306 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1307 wxT("invalid thread priority") );
1309 wxCriticalSectionLocker
lock(m_critsect
);
1311 switch ( m_internal
->GetState() )
1314 // thread not yet started, priority will be set when it is
1315 m_internal
->SetPriority(prio
);
1320 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1322 struct sched_param sparam
;
1323 sparam
.sched_priority
= prio
;
1325 if ( pthread_setschedparam(m_internal
->GetId(),
1326 SCHED_OTHER
, &sparam
) != 0 )
1328 wxLogError(_("Failed to set thread priority %d."), prio
);
1331 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1336 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1340 unsigned int wxThread::GetPriority() const
1342 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1344 return m_internal
->GetPriority();
1347 wxThreadIdType
wxThread::GetId() const
1349 return (wxThreadIdType
) m_internal
->GetId();
1352 // -----------------------------------------------------------------------------
1354 // -----------------------------------------------------------------------------
1356 wxThreadError
wxThread::Pause()
1358 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1359 _T("a thread can't pause itself") );
1361 wxCriticalSectionLocker
lock(m_critsect
);
1363 if ( m_internal
->GetState() != STATE_RUNNING
)
1365 wxLogDebug(wxT("Can't pause thread which is not running."));
1367 return wxTHREAD_NOT_RUNNING
;
1370 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1373 // just set a flag, the thread will be really paused only during the next
1374 // call to TestDestroy()
1375 m_internal
->SetState(STATE_PAUSED
);
1377 return wxTHREAD_NO_ERROR
;
1380 wxThreadError
wxThread::Resume()
1382 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1383 _T("a thread can't resume itself") );
1385 wxCriticalSectionLocker
lock(m_critsect
);
1387 wxThreadState state
= m_internal
->GetState();
1392 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1395 m_internal
->Resume();
1397 return wxTHREAD_NO_ERROR
;
1400 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1402 return wxTHREAD_NO_ERROR
;
1405 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1407 return wxTHREAD_MISC_ERROR
;
1411 // -----------------------------------------------------------------------------
1413 // -----------------------------------------------------------------------------
1415 wxThread::ExitCode
wxThread::Wait()
1417 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1418 _T("a thread can't wait for itself") );
1420 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1421 _T("can't wait for detached thread") );
1425 return m_internal
->GetExitCode();
1428 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1430 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1431 _T("a thread can't delete itself") );
1434 wxThreadState state
= m_internal
->GetState();
1436 // ask the thread to stop
1437 m_internal
->SetCancelFlag();
1441 // detached threads won't broadcast about their termination by default
1442 // because usually nobody waits for them - but here we do, so ask the
1443 // thread to notify us
1444 m_internal
->Notify();
1452 // we need to wake up the thread so that PthreadStart() will
1453 // terminate - right now it's blocking on m_semRun
1454 m_internal
->SignalRun();
1463 // resume the thread first (don't call our Resume() because this
1464 // would dead lock when it tries to enter m_critsect)
1465 m_internal
->Resume();
1470 // wait until the thread stops
1475 wxASSERT_MSG( !m_isDetached
,
1476 _T("no return code for detached threads") );
1478 // if it's a joinable thread, it's not deleted yet
1479 *rc
= m_internal
->GetExitCode();
1483 return wxTHREAD_NO_ERROR
;
1486 wxThreadError
wxThread::Kill()
1488 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1489 _T("a thread can't kill itself") );
1491 switch ( m_internal
->GetState() )
1495 return wxTHREAD_NOT_RUNNING
;
1498 // resume the thread first
1504 #ifdef HAVE_PTHREAD_CANCEL
1505 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1508 wxLogError(_("Failed to terminate a thread."));
1510 return wxTHREAD_MISC_ERROR
;
1515 // if we use cleanup function, this will be done from
1516 // wxPthreadCleanup()
1517 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1518 ScheduleThreadForDeletion();
1520 // don't call OnExit() here, it can only be called in the
1521 // threads context and we're in the context of another thread
1524 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1528 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1531 return wxTHREAD_NO_ERROR
;
1535 void wxThread::Exit(ExitCode status
)
1537 wxASSERT_MSG( This() == this,
1538 _T("wxThread::Exit() can only be called in the "
1539 "context of the same thread") );
1541 // from the moment we call OnExit(), the main program may terminate at any
1542 // moment, so mark this thread as being already in process of being
1543 // deleted or wxThreadModule::OnExit() will try to delete it again
1544 ScheduleThreadForDeletion();
1546 // don't enter m_critsect before calling OnExit() because the user code
1547 // might deadlock if, for example, it signals a condition in OnExit() (a
1548 // common case) while the main thread calls any of functions entering
1549 // m_critsect on us (almost all of them do)
1552 // now do enter it because SignalExit() will change our state
1555 // next wake up the threads waiting for us (OTOH, this function won't return
1556 // until someone waited for us!)
1557 m_internal
->SignalExit();
1559 // leave the critical section before entering the dtor which tries to
1563 // delete C++ thread object if this is a detached thread - user is
1564 // responsible for doing this for joinable ones
1567 // FIXME I'm feeling bad about it - what if another thread function is
1568 // called (in another thread context) now? It will try to access
1569 // half destroyed object which will probably result in something
1570 // very bad - but we can't protect this by a crit section unless
1571 // we make it a global object, but this would mean that we can
1572 // only call one thread function at a time :-(
1576 // terminate the thread (pthread_exit() never returns)
1577 pthread_exit(status
);
1579 wxFAIL_MSG(_T("pthread_exit() failed"));
1582 // also test whether we were paused
1583 bool wxThread::TestDestroy()
1585 wxASSERT_MSG( This() == this,
1586 _T("wxThread::TestDestroy() can only be called in the "
1587 "context of the same thread") );
1591 if ( m_internal
->GetState() == STATE_PAUSED
)
1593 m_internal
->SetReallyPaused(TRUE
);
1595 // leave the crit section or the other threads will stop too if they
1596 // try to call any of (seemingly harmless) IsXXX() functions while we
1600 m_internal
->Pause();
1604 // thread wasn't requested to pause, nothing to do
1608 return m_internal
->WasCancelled();
1611 wxThread::~wxThread()
1616 // check that the thread either exited or couldn't be created
1617 if ( m_internal
->GetState() != STATE_EXITED
&&
1618 m_internal
->GetState() != STATE_NEW
)
1620 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1621 "running! The application may crash."), GetId());
1625 #endif // __WXDEBUG__
1629 // remove this thread from the global array
1630 gs_allThreads
.Remove(this);
1632 // detached thread will decrement this counter in DeleteThread(), but it
1633 // is not called for the joinable threads, so do it here
1634 if ( !m_isDetached
)
1636 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1638 gs_nThreadsBeingDeleted
--;
1640 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1641 gs_nThreadsBeingDeleted
- 1);
1645 // -----------------------------------------------------------------------------
1647 // -----------------------------------------------------------------------------
1649 bool wxThread::IsRunning() const
1651 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1653 return m_internal
->GetState() == STATE_RUNNING
;
1656 bool wxThread::IsAlive() const
1658 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1660 switch ( m_internal
->GetState() )
1671 bool wxThread::IsPaused() const
1673 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1675 return (m_internal
->GetState() == STATE_PAUSED
);
1678 //--------------------------------------------------------------------
1680 //--------------------------------------------------------------------
1682 class wxThreadModule
: public wxModule
1685 virtual bool OnInit();
1686 virtual void OnExit();
1689 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1692 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1694 bool wxThreadModule::OnInit()
1696 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1699 wxLogSysError(rc
, _("Thread module initialization failed: "
1700 "failed to create thread key"));
1705 gs_tidMain
= pthread_self();
1708 gs_mutexGui
= new wxMutex();
1710 gs_mutexGui
->Lock();
1713 gs_mutexDeleteThread
= new wxMutex();
1714 gs_condAllDeleted
= new wxCondition( gs_mutexDeleteThread
);
1719 void wxThreadModule::OnExit()
1721 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1723 // are there any threads left which are being deleted right now?
1724 size_t nThreadsBeingDeleted
;
1727 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1728 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1730 if ( nThreadsBeingDeleted
> 0 )
1732 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1733 nThreadsBeingDeleted
);
1735 // have to wait until all of them disappear
1736 gs_condAllDeleted
->Wait();
1740 // terminate any threads left
1741 size_t count
= gs_allThreads
.GetCount();
1744 wxLogDebug(wxT("%u threads were not terminated by the application."),
1748 for ( size_t n
= 0u; n
< count
; n
++ )
1750 // Delete calls the destructor which removes the current entry. We
1751 // should only delete the first one each time.
1752 gs_allThreads
[0]->Delete();
1756 // destroy GUI mutex
1757 gs_mutexGui
->Unlock();
1762 // and free TLD slot
1763 (void)pthread_key_delete(gs_keySelf
);
1765 delete gs_condAllDeleted
;
1766 delete gs_mutexDeleteThread
;
1769 // ----------------------------------------------------------------------------
1771 // ----------------------------------------------------------------------------
1773 static void ScheduleThreadForDeletion()
1775 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1777 gs_nThreadsBeingDeleted
++;
1779 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1780 gs_nThreadsBeingDeleted
,
1781 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1784 static void DeleteThread(wxThread
*This
)
1786 // gs_mutexDeleteThread should be unlocked before signalling the condition
1787 // or wxThreadModule::OnExit() would deadlock
1788 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1790 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1794 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1795 _T("no threads scheduled for deletion, yet we delete "
1798 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1799 gs_nThreadsBeingDeleted
- 1);
1801 if ( !--gs_nThreadsBeingDeleted
)
1803 // no more threads left, signal it
1804 gs_condAllDeleted
->Signal();
1808 void wxMutexGuiEnter()
1811 gs_mutexGui
->Lock();
1815 void wxMutexGuiLeave()
1818 gs_mutexGui
->Unlock();