1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/threadpsx.cpp
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 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
30 #include "wx/except.h"
34 #include "wx/dynarray.h"
39 #include "wx/stopwatch.h"
40 #include "wx/module.h"
52 #ifdef HAVE_THR_SETCONCURRENCY
56 // we use wxFFile under Linux in GetCPUCount()
61 #include <sys/resource.h>
65 #define THR_ID(thr) ((long long)(thr)->GetId())
67 #define THR_ID(thr) ((long)(thr)->GetId())
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
74 // the possible states of the thread and transitions from them
77 STATE_NEW
, // didn't start execution yet (=> RUNNING)
78 STATE_RUNNING
, // running (=> PAUSED or EXITED)
79 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
80 STATE_EXITED
// thread doesn't exist any more
83 // the exit value of a thread which has been cancelled
84 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
86 // trace mask for wxThread operations
87 #define TRACE_THREADS _T("thread")
89 // you can get additional debugging messages for the semaphore operations
90 #define TRACE_SEMA _T("semaphore")
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 static void ScheduleThreadForDeletion();
97 static void DeleteThread(wxThread
*This
);
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // an (non owning) array of pointers to threads
104 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
106 // an entry for a thread we can wait for
108 // -----------------------------------------------------------------------------
110 // -----------------------------------------------------------------------------
112 // we keep the list of all threads created by the application to be able to
113 // terminate them on exit if there are some left - otherwise the process would
115 static wxArrayThread gs_allThreads
;
117 // a mutex to protect gs_allThreads
118 static wxMutex
*gs_mutexAllThreads
= NULL
;
120 // the id of the main thread
121 static pthread_t gs_tidMain
= (pthread_t
)-1;
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 wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
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
;
137 // this mutex must be acquired before any call to a GUI function
138 // (it's not inside #if wxUSE_GUI because this file is compiled as part
140 static wxMutex
*gs_mutexGui
= NULL
;
142 // when we wait for a thread to exit, we're blocking on a condition which the
143 // thread signals in its SignalExit() method -- but this condition can't be a
144 // member of the thread itself as a detached thread may delete itself at any
145 // moment and accessing the condition member of the thread after this would
146 // result in a disaster
148 // so instead we maintain a global list of the structs below for the threads
149 // we're interested in waiting on
151 // ============================================================================
152 // wxMutex implementation
153 // ============================================================================
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
159 // this is a simple wrapper around pthread_mutex_t which provides error
161 class wxMutexInternal
164 wxMutexInternal(wxMutexType mutexType
);
168 wxMutexError
Lock(unsigned long ms
);
169 wxMutexError
TryLock();
170 wxMutexError
Unlock();
172 bool IsOk() const { return m_isOk
; }
175 // convert the result of pthread_mutex_[timed]lock() call to wx return code
176 wxMutexError
HandleLockResult(int err
);
179 pthread_mutex_t m_mutex
;
182 // wxConditionInternal uses our m_mutex
183 friend class wxConditionInternal
;
186 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
187 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
188 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
189 // in the library, otherwise we wouldn't compile this code at all)
190 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
193 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
198 case wxMUTEX_RECURSIVE
:
199 // support recursive locks like Win32, i.e. a thread can lock a
200 // mutex which it had itself already locked
202 // unfortunately initialization of recursive mutexes is non
203 // portable, so try several methods
204 #ifdef HAVE_PTHREAD_MUTEXATTR_T
206 pthread_mutexattr_t attr
;
207 pthread_mutexattr_init(&attr
);
208 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
210 err
= pthread_mutex_init(&m_mutex
, &attr
);
212 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
213 // we can use this only as initializer so we have to assign it
214 // first to a temp var - assigning directly to m_mutex wouldn't
217 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
220 #else // no recursive mutexes
222 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
226 wxFAIL_MSG( _T("unknown mutex type") );
229 case wxMUTEX_DEFAULT
:
230 err
= pthread_mutex_init(&m_mutex
, NULL
);
237 wxLogApiError( wxT("pthread_mutex_init()"), err
);
241 wxMutexInternal::~wxMutexInternal()
245 int err
= pthread_mutex_destroy(&m_mutex
);
248 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
253 wxMutexError
wxMutexInternal::Lock()
255 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
258 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
260 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
261 static const long MSEC_IN_SEC
= 1000;
262 static const long NSEC_IN_MSEC
= 1000000;
263 static const long NSEC_IN_USEC
= 1000;
264 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
266 time_t seconds
= ms
/MSEC_IN_SEC
;
267 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
268 timespec ts
= { 0, 0 };
270 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
271 // function is in librt and we don't link with it currently, so use
272 // gettimeofday() instead -- if it turns out that this is really too
273 // imprecise, we should modify configure to check if clock_gettime() is
274 // available and whether it requires -lrt and use it instead
276 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
281 if ( wxGetTimeOfDay(&tv
) != -1 )
283 ts
.tv_sec
= tv
.tv_sec
;
284 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
287 else // fall back on system timer
289 ts
.tv_sec
= time(NULL
);
292 ts
.tv_sec
+= seconds
;
293 ts
.tv_nsec
+= nanoseconds
;
294 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
297 ts
.tv_nsec
-= NSEC_IN_SEC
;
300 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
301 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
304 return wxMUTEX_MISC_ERROR
;
305 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
308 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
313 // only error checking mutexes return this value and so it's an
314 // unexpected situation -- hence use assert, not wxLogDebug
315 wxFAIL_MSG( _T("mutex deadlock prevented") );
316 return wxMUTEX_DEAD_LOCK
;
319 wxLogDebug(_T("pthread_mutex_[timed]lock(): mutex not initialized"));
323 return wxMUTEX_TIMEOUT
;
326 return wxMUTEX_NO_ERROR
;
329 wxLogApiError(_T("pthread_mutex_[timed]lock()"), err
);
332 return wxMUTEX_MISC_ERROR
;
336 wxMutexError
wxMutexInternal::TryLock()
338 int err
= pthread_mutex_trylock(&m_mutex
);
342 // not an error: mutex is already locked, but we're prepared for
347 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
351 return wxMUTEX_NO_ERROR
;
354 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
357 return wxMUTEX_MISC_ERROR
;
360 wxMutexError
wxMutexInternal::Unlock()
362 int err
= pthread_mutex_unlock(&m_mutex
);
366 // we don't own the mutex
367 return wxMUTEX_UNLOCKED
;
370 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
374 return wxMUTEX_NO_ERROR
;
377 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
380 return wxMUTEX_MISC_ERROR
;
383 // ===========================================================================
384 // wxCondition implementation
385 // ===========================================================================
387 // ---------------------------------------------------------------------------
388 // wxConditionInternal
389 // ---------------------------------------------------------------------------
391 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
392 // with a pthread_mutex_t)
393 class wxConditionInternal
396 wxConditionInternal(wxMutex
& mutex
);
397 ~wxConditionInternal();
399 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
402 wxCondError
WaitTimeout(unsigned long milliseconds
);
404 wxCondError
Signal();
405 wxCondError
Broadcast();
408 // get the POSIX mutex associated with us
409 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
412 pthread_cond_t m_cond
;
417 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
420 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
426 wxLogApiError(_T("pthread_cond_init()"), err
);
430 wxConditionInternal::~wxConditionInternal()
434 int err
= pthread_cond_destroy(&m_cond
);
437 wxLogApiError(_T("pthread_cond_destroy()"), err
);
442 wxCondError
wxConditionInternal::Wait()
444 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
447 wxLogApiError(_T("pthread_cond_wait()"), err
);
449 return wxCOND_MISC_ERROR
;
452 return wxCOND_NO_ERROR
;
455 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
457 wxLongLong curtime
= wxGetLocalTimeMillis();
458 curtime
+= milliseconds
;
459 wxLongLong temp
= curtime
/ 1000;
460 int sec
= temp
.GetLo();
462 temp
= curtime
- temp
;
463 int millis
= temp
.GetLo();
468 tspec
.tv_nsec
= millis
* 1000L * 1000L;
470 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
474 return wxCOND_TIMEOUT
;
477 return wxCOND_NO_ERROR
;
480 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
483 return wxCOND_MISC_ERROR
;
486 wxCondError
wxConditionInternal::Signal()
488 int err
= pthread_cond_signal(&m_cond
);
491 wxLogApiError(_T("pthread_cond_signal()"), err
);
493 return wxCOND_MISC_ERROR
;
496 return wxCOND_NO_ERROR
;
499 wxCondError
wxConditionInternal::Broadcast()
501 int err
= pthread_cond_broadcast(&m_cond
);
504 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
506 return wxCOND_MISC_ERROR
;
509 return wxCOND_NO_ERROR
;
512 // ===========================================================================
513 // wxSemaphore implementation
514 // ===========================================================================
516 // ---------------------------------------------------------------------------
517 // wxSemaphoreInternal
518 // ---------------------------------------------------------------------------
520 // we implement the semaphores using mutexes and conditions instead of using
521 // the sem_xxx() POSIX functions because they're not widely available and also
522 // because it's impossible to implement WaitTimeout() using them
523 class wxSemaphoreInternal
526 wxSemaphoreInternal(int initialcount
, int maxcount
);
528 bool IsOk() const { return m_isOk
; }
531 wxSemaError
TryWait();
532 wxSemaError
WaitTimeout(unsigned long milliseconds
);
546 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
550 if ( (initialcount
< 0 || maxcount
< 0) ||
551 ((maxcount
> 0) && (initialcount
> maxcount
)) )
553 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
559 m_maxcount
= (size_t)maxcount
;
560 m_count
= (size_t)initialcount
;
563 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
566 wxSemaError
wxSemaphoreInternal::Wait()
568 wxMutexLocker
locker(m_mutex
);
570 while ( m_count
== 0 )
572 wxLogTrace(TRACE_SEMA
,
573 _T("Thread %ld waiting for semaphore to become signalled"),
574 wxThread::GetCurrentId());
576 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
577 return wxSEMA_MISC_ERROR
;
579 wxLogTrace(TRACE_SEMA
,
580 _T("Thread %ld finished waiting for semaphore, count = %lu"),
581 wxThread::GetCurrentId(), (unsigned long)m_count
);
586 return wxSEMA_NO_ERROR
;
589 wxSemaError
wxSemaphoreInternal::TryWait()
591 wxMutexLocker
locker(m_mutex
);
598 return wxSEMA_NO_ERROR
;
601 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
603 wxMutexLocker
locker(m_mutex
);
605 wxLongLong startTime
= wxGetLocalTimeMillis();
607 while ( m_count
== 0 )
609 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
610 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
611 if ( remainingTime
<= 0 )
614 return wxSEMA_TIMEOUT
;
617 switch ( m_cond
.WaitTimeout(remainingTime
) )
620 return wxSEMA_TIMEOUT
;
623 return wxSEMA_MISC_ERROR
;
625 case wxCOND_NO_ERROR
:
632 return wxSEMA_NO_ERROR
;
635 wxSemaError
wxSemaphoreInternal::Post()
637 wxMutexLocker
locker(m_mutex
);
639 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
641 return wxSEMA_OVERFLOW
;
646 wxLogTrace(TRACE_SEMA
,
647 _T("Thread %ld about to signal semaphore, count = %lu"),
648 wxThread::GetCurrentId(), (unsigned long)m_count
);
650 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
654 // ===========================================================================
655 // wxThread implementation
656 // ===========================================================================
658 // the thread callback functions must have the C linkage
662 #ifdef wxHAVE_PTHREAD_CLEANUP
663 // thread exit function
664 void wxPthreadCleanup(void *ptr
);
665 #endif // wxHAVE_PTHREAD_CLEANUP
667 void *wxPthreadStart(void *ptr
);
671 // ----------------------------------------------------------------------------
673 // ----------------------------------------------------------------------------
675 class wxThreadInternal
681 // thread entry function
682 static void *PthreadStart(wxThread
*thread
);
687 // unblock the thread allowing it to run
688 void SignalRun() { m_semRun
.Post(); }
689 // ask the thread to terminate
691 // go to sleep until Resume() is called
698 int GetPriority() const { return m_prio
; }
699 void SetPriority(int prio
) { m_prio
= prio
; }
701 wxThreadState
GetState() const { return m_state
; }
702 void SetState(wxThreadState state
)
705 static const wxChar
*stateNames
[] =
713 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
714 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
715 #endif // __WXDEBUG__
720 pthread_t
GetId() const { return m_threadId
; }
721 pthread_t
*GetIdPtr() { return &m_threadId
; }
723 void SetCancelFlag() { m_cancelled
= true; }
724 bool WasCancelled() const { return m_cancelled
; }
726 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
727 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
730 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
731 bool IsReallyPaused() const { return m_isPaused
; }
733 // tell the thread that it is a detached one
736 wxCriticalSectionLocker
lock(m_csJoinFlag
);
738 m_shouldBeJoined
= false;
742 #ifdef wxHAVE_PTHREAD_CLEANUP
743 // this is used by wxPthreadCleanup() only
744 static void Cleanup(wxThread
*thread
);
745 #endif // wxHAVE_PTHREAD_CLEANUP
748 pthread_t m_threadId
; // id of the thread
749 wxThreadState m_state
; // see wxThreadState enum
750 int m_prio
; // in wxWidgets units: from 0 to 100
752 // this flag is set when the thread should terminate
755 // this flag is set when the thread is blocking on m_semSuspend
758 // the thread exit code - only used for joinable (!detached) threads and
759 // is only valid after the thread termination
760 wxThread::ExitCode m_exitcode
;
762 // many threads may call Wait(), but only one of them should call
763 // pthread_join(), so we have to keep track of this
764 wxCriticalSection m_csJoinFlag
;
765 bool m_shouldBeJoined
;
768 // this semaphore is posted by Run() and the threads Entry() is not
769 // called before it is done
770 wxSemaphore m_semRun
;
772 // this one is signaled when the thread should resume after having been
774 wxSemaphore m_semSuspend
;
777 // ----------------------------------------------------------------------------
778 // thread startup and exit functions
779 // ----------------------------------------------------------------------------
781 void *wxPthreadStart(void *ptr
)
783 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
786 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
788 wxThreadInternal
*pthread
= thread
->m_internal
;
790 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
792 // associate the thread pointer with the newly created thread so that
793 // wxThread::This() will work
794 int rc
= pthread_setspecific(gs_keySelf
, thread
);
797 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
802 // have to declare this before pthread_cleanup_push() which defines a
806 #ifdef wxHAVE_PTHREAD_CLEANUP
807 // install the cleanup handler which will be called if the thread is
809 pthread_cleanup_push(wxPthreadCleanup
, thread
);
810 #endif // wxHAVE_PTHREAD_CLEANUP
812 // wait for the semaphore to be posted from Run()
813 pthread
->m_semRun
.Wait();
815 // test whether we should run the run at all - may be it was deleted
816 // before it started to Run()?
818 wxCriticalSectionLocker
lock(thread
->m_critsect
);
820 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
821 pthread
->WasCancelled();
826 // call the main entry
827 wxLogTrace(TRACE_THREADS
,
828 _T("Thread %ld about to enter its Entry()."),
833 pthread
->m_exitcode
= thread
->Entry();
835 wxLogTrace(TRACE_THREADS
,
836 _T("Thread %ld Entry() returned %lu."),
837 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
839 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
842 wxCriticalSectionLocker
lock(thread
->m_critsect
);
844 // change the state of the thread to "exited" so that
845 // wxPthreadCleanup handler won't do anything from now (if it's
846 // called before we do pthread_cleanup_pop below)
847 pthread
->SetState(STATE_EXITED
);
851 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
852 // '}' for the '{' in push, so they must be used in the same block!
853 #ifdef wxHAVE_PTHREAD_CLEANUP
855 // under Tru64 we get a warning from macro expansion
857 #pragma message disable(declbutnotref)
860 // remove the cleanup handler without executing it
861 pthread_cleanup_pop(FALSE
);
864 #pragma message restore
866 #endif // wxHAVE_PTHREAD_CLEANUP
870 // FIXME: deleting a possibly joinable thread here???
873 return EXITCODE_CANCELLED
;
877 // terminate the thread
878 thread
->Exit(pthread
->m_exitcode
);
880 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
886 #ifdef wxHAVE_PTHREAD_CLEANUP
888 // this handler is called when the thread is cancelled
889 extern "C" void wxPthreadCleanup(void *ptr
)
891 wxThreadInternal::Cleanup((wxThread
*)ptr
);
894 void wxThreadInternal::Cleanup(wxThread
*thread
)
896 if (pthread_getspecific(gs_keySelf
) == 0) return;
898 wxCriticalSectionLocker
lock(thread
->m_critsect
);
899 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
901 // thread is already considered as finished.
906 // exit the thread gracefully
907 thread
->Exit(EXITCODE_CANCELLED
);
910 #endif // wxHAVE_PTHREAD_CLEANUP
912 // ----------------------------------------------------------------------------
914 // ----------------------------------------------------------------------------
916 wxThreadInternal::wxThreadInternal()
920 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
924 // set to true only when the thread starts waiting on m_semSuspend
927 // defaults for joinable threads
928 m_shouldBeJoined
= true;
929 m_isDetached
= false;
932 wxThreadInternal::~wxThreadInternal()
936 wxThreadError
wxThreadInternal::Run()
938 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
939 wxT("thread may only be started once after Create()") );
941 SetState(STATE_RUNNING
);
943 // wake up threads waiting for our start
946 return wxTHREAD_NO_ERROR
;
949 void wxThreadInternal::Wait()
951 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
953 // if the thread we're waiting for is waiting for the GUI mutex, we will
954 // deadlock so make sure we release it temporarily
955 if ( wxThread::IsMain() )
958 wxLogTrace(TRACE_THREADS
,
959 _T("Starting to wait for thread %ld to exit."),
962 // to avoid memory leaks we should call pthread_join(), but it must only be
963 // done once so use a critical section to serialize the code below
965 wxCriticalSectionLocker
lock(m_csJoinFlag
);
967 if ( m_shouldBeJoined
)
969 // FIXME shouldn't we set cancellation type to DISABLED here? If
970 // we're cancelled inside pthread_join(), things will almost
971 // certainly break - but if we disable the cancellation, we
973 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
975 // this is a serious problem, so use wxLogError and not
976 // wxLogDebug: it is possible to bring the system to its knees
977 // by creating too many threads and not joining them quite
979 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
982 m_shouldBeJoined
= false;
986 // reacquire GUI mutex
987 if ( wxThread::IsMain() )
991 void wxThreadInternal::Pause()
993 // the state is set from the thread which pauses us first, this function
994 // is called later so the state should have been already set
995 wxCHECK_RET( m_state
== STATE_PAUSED
,
996 wxT("thread must first be paused with wxThread::Pause().") );
998 wxLogTrace(TRACE_THREADS
,
999 _T("Thread %ld goes to sleep."), THR_ID(this));
1001 // wait until the semaphore is Post()ed from Resume()
1002 m_semSuspend
.Wait();
1005 void wxThreadInternal::Resume()
1007 wxCHECK_RET( m_state
== STATE_PAUSED
,
1008 wxT("can't resume thread which is not suspended.") );
1010 // the thread might be not actually paused yet - if there were no call to
1011 // TestDestroy() since the last call to Pause() for example
1012 if ( IsReallyPaused() )
1014 wxLogTrace(TRACE_THREADS
,
1015 _T("Waking up thread %ld"), THR_ID(this));
1018 m_semSuspend
.Post();
1021 SetReallyPaused(false);
1025 wxLogTrace(TRACE_THREADS
,
1026 _T("Thread %ld is not yet really paused"), THR_ID(this));
1029 SetState(STATE_RUNNING
);
1032 // -----------------------------------------------------------------------------
1033 // wxThread static functions
1034 // -----------------------------------------------------------------------------
1036 wxThread
*wxThread::This()
1038 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1041 bool wxThread::IsMain()
1043 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
1046 void wxThread::Yield()
1048 #ifdef HAVE_SCHED_YIELD
1053 void wxThread::Sleep(unsigned long milliseconds
)
1055 wxMilliSleep(milliseconds
);
1058 int wxThread::GetCPUCount()
1060 #if defined(_SC_NPROCESSORS_ONLN)
1061 // this works for Solaris and Linux 2.6
1062 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1067 #elif defined(__LINUX__) && wxUSE_FFILE
1068 // read from proc (can't use wxTextFile here because it's a special file:
1069 // it has 0 size but still can be read from)
1072 wxFFile
file(_T("/proc/cpuinfo"));
1073 if ( file
.IsOpened() )
1075 // slurp the whole file
1077 if ( file
.ReadAll(&s
) )
1079 // (ab)use Replace() to find the number of "processor: num" strings
1080 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1086 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1090 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1093 #endif // different ways to get number of CPUs
1099 // VMS is a 64 bit system and threads have 64 bit pointers.
1100 // FIXME: also needed for other systems????
1102 unsigned long long wxThread::GetCurrentId()
1104 return (unsigned long long)pthread_self();
1109 unsigned long wxThread::GetCurrentId()
1111 return (unsigned long)pthread_self();
1114 #endif // __VMS/!__VMS
1117 bool wxThread::SetConcurrency(size_t level
)
1119 #ifdef HAVE_THR_SETCONCURRENCY
1120 int rc
= thr_setconcurrency(level
);
1123 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1127 #else // !HAVE_THR_SETCONCURRENCY
1128 // ok only for the default value
1130 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1133 // -----------------------------------------------------------------------------
1135 // -----------------------------------------------------------------------------
1137 wxThread::wxThread(wxThreadKind kind
)
1139 // add this thread to the global list of all threads
1141 wxMutexLocker
lock(*gs_mutexAllThreads
);
1143 gs_allThreads
.Add(this);
1146 m_internal
= new wxThreadInternal();
1148 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1151 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1152 #define WXUNUSED_STACKSIZE(identifier) identifier
1154 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1157 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1159 if ( m_internal
->GetState() != STATE_NEW
)
1161 // don't recreate thread
1162 return wxTHREAD_RUNNING
;
1165 // set up the thread attribute: right now, we only set thread priority
1166 pthread_attr_t attr
;
1167 pthread_attr_init(&attr
);
1169 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1171 pthread_attr_setstacksize(&attr
, stackSize
);
1174 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1176 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1178 wxLogError(_("Cannot retrieve thread scheduling policy."));
1182 /* the pthread.h contains too many spaces. This is a work-around */
1183 # undef sched_get_priority_max
1184 #undef sched_get_priority_min
1185 #define sched_get_priority_max(_pol_) \
1186 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1187 #define sched_get_priority_min(_pol_) \
1188 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1191 int max_prio
= sched_get_priority_max(policy
),
1192 min_prio
= sched_get_priority_min(policy
),
1193 prio
= m_internal
->GetPriority();
1195 if ( min_prio
== -1 || max_prio
== -1 )
1197 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1200 else if ( max_prio
== min_prio
)
1202 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1204 // notify the programmer that this doesn't work here
1205 wxLogWarning(_("Thread priority setting is ignored."));
1207 //else: we have default priority, so don't complain
1209 // anyhow, don't do anything because priority is just ignored
1213 struct sched_param sp
;
1214 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1216 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1219 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1221 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1223 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1226 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1228 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1229 // this will make the threads created by this process really concurrent
1230 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1232 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1234 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1236 // VZ: assume that this one is always available (it's rather fundamental),
1237 // if this function is ever missing we should try to use
1238 // pthread_detach() instead (after thread creation)
1241 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1243 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1246 // never try to join detached threads
1247 m_internal
->Detach();
1249 //else: threads are created joinable by default, it's ok
1251 // create the new OS thread object
1252 int rc
= pthread_create
1254 m_internal
->GetIdPtr(),
1260 if ( pthread_attr_destroy(&attr
) != 0 )
1262 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1267 m_internal
->SetState(STATE_EXITED
);
1269 return wxTHREAD_NO_RESOURCE
;
1272 return wxTHREAD_NO_ERROR
;
1275 wxThreadError
wxThread::Run()
1277 wxCriticalSectionLocker
lock(m_critsect
);
1279 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1280 wxT("must call wxThread::Create() first") );
1282 return m_internal
->Run();
1285 // -----------------------------------------------------------------------------
1287 // -----------------------------------------------------------------------------
1289 void wxThread::SetPriority(unsigned int prio
)
1291 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1292 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1293 wxT("invalid thread priority") );
1295 wxCriticalSectionLocker
lock(m_critsect
);
1297 switch ( m_internal
->GetState() )
1300 // thread not yet started, priority will be set when it is
1301 m_internal
->SetPriority(prio
);
1306 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1307 #if defined(__LINUX__)
1308 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1309 // a priority other than 0. Instead, we use the BSD setpriority
1310 // which alllows us to set a 'nice' value between 20 to -20. Only
1311 // super user can set a value less than zero (more negative yields
1312 // higher priority). setpriority set the static priority of a
1313 // process, but this is OK since Linux is configured as a thread
1316 // FIXME this is not true for 2.6!!
1318 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1319 // to Unix priorities 20..-20
1320 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1322 wxLogError(_("Failed to set thread priority %d."), prio
);
1326 struct sched_param sparam
;
1327 sparam
.sched_priority
= prio
;
1329 if ( pthread_setschedparam(m_internal
->GetId(),
1330 SCHED_OTHER
, &sparam
) != 0 )
1332 wxLogError(_("Failed to set thread priority %d."), prio
);
1336 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1341 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1345 unsigned int wxThread::GetPriority() const
1347 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1349 return m_internal
->GetPriority();
1352 wxThreadIdType
wxThread::GetId() const
1354 return (wxThreadIdType
) m_internal
->GetId();
1357 // -----------------------------------------------------------------------------
1359 // -----------------------------------------------------------------------------
1361 wxThreadError
wxThread::Pause()
1363 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1364 _T("a thread can't pause itself") );
1366 wxCriticalSectionLocker
lock(m_critsect
);
1368 if ( m_internal
->GetState() != STATE_RUNNING
)
1370 wxLogDebug(wxT("Can't pause thread which is not running."));
1372 return wxTHREAD_NOT_RUNNING
;
1375 // just set a flag, the thread will be really paused only during the next
1376 // call to TestDestroy()
1377 m_internal
->SetState(STATE_PAUSED
);
1379 return wxTHREAD_NO_ERROR
;
1382 wxThreadError
wxThread::Resume()
1384 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1385 _T("a thread can't resume itself") );
1387 wxCriticalSectionLocker
lock(m_critsect
);
1389 wxThreadState state
= m_internal
->GetState();
1394 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1397 m_internal
->Resume();
1399 return wxTHREAD_NO_ERROR
;
1402 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1404 return wxTHREAD_NO_ERROR
;
1407 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1409 return wxTHREAD_MISC_ERROR
;
1413 // -----------------------------------------------------------------------------
1415 // -----------------------------------------------------------------------------
1417 wxThread::ExitCode
wxThread::Wait()
1419 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1420 _T("a thread can't wait for itself") );
1422 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1423 _T("can't wait for detached thread") );
1427 return m_internal
->GetExitCode();
1430 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1432 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1433 _T("a thread can't delete itself") );
1435 bool isDetached
= m_isDetached
;
1438 wxThreadState state
= m_internal
->GetState();
1440 // ask the thread to stop
1441 m_internal
->SetCancelFlag();
1448 // we need to wake up the thread so that PthreadStart() will
1449 // terminate - right now it's blocking on run semaphore in
1451 m_internal
->SignalRun();
1460 // resume the thread first
1461 m_internal
->Resume();
1468 // wait until the thread stops
1473 // return the exit code of the thread
1474 *rc
= m_internal
->GetExitCode();
1477 //else: can't wait for detached threads
1480 return wxTHREAD_NO_ERROR
;
1483 wxThreadError
wxThread::Kill()
1485 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1486 _T("a thread can't kill itself") );
1488 switch ( m_internal
->GetState() )
1492 return wxTHREAD_NOT_RUNNING
;
1495 // resume the thread first
1501 #ifdef HAVE_PTHREAD_CANCEL
1502 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1503 #endif // HAVE_PTHREAD_CANCEL
1505 wxLogError(_("Failed to terminate a thread."));
1507 return wxTHREAD_MISC_ERROR
;
1510 #ifdef HAVE_PTHREAD_CANCEL
1513 // if we use cleanup function, this will be done from
1514 // wxPthreadCleanup()
1515 #ifndef wxHAVE_PTHREAD_CLEANUP
1516 ScheduleThreadForDeletion();
1518 // don't call OnExit() here, it can only be called in the
1519 // threads context and we're in the context of another thread
1522 #endif // wxHAVE_PTHREAD_CLEANUP
1526 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1529 return wxTHREAD_NO_ERROR
;
1530 #endif // HAVE_PTHREAD_CANCEL
1534 void wxThread::Exit(ExitCode status
)
1536 wxASSERT_MSG( This() == this,
1537 _T("wxThread::Exit() can only be called in the context of the same thread") );
1541 // from the moment we call OnExit(), the main program may terminate at
1542 // any 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();
1547 // don't enter m_critsect before calling OnExit() because the user code
1548 // might deadlock if, for example, it signals a condition in OnExit() (a
1549 // common case) while the main thread calls any of functions entering
1550 // m_critsect on us (almost all of them do)
1555 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1557 // delete C++ thread object if this is a detached thread - user is
1558 // responsible for doing this for joinable ones
1561 // FIXME I'm feeling bad about it - what if another thread function is
1562 // called (in another thread context) now? It will try to access
1563 // half destroyed object which will probably result in something
1564 // very bad - but we can't protect this by a crit section unless
1565 // we make it a global object, but this would mean that we can
1566 // only call one thread function at a time :-(
1568 pthread_setspecific(gs_keySelf
, 0);
1573 m_internal
->SetState(STATE_EXITED
);
1577 // terminate the thread (pthread_exit() never returns)
1578 pthread_exit(status
);
1580 wxFAIL_MSG(_T("pthread_exit() failed"));
1583 // also test whether we were paused
1584 bool wxThread::TestDestroy()
1586 wxASSERT_MSG( This() == this,
1587 _T("wxThread::TestDestroy() can only be called in the 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 running! The application may crash."),
1625 #endif // __WXDEBUG__
1629 // remove this thread from the global array
1631 wxMutexLocker
lock(*gs_mutexAllThreads
);
1633 gs_allThreads
.Remove(this);
1637 // -----------------------------------------------------------------------------
1639 // -----------------------------------------------------------------------------
1641 bool wxThread::IsRunning() const
1643 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1645 return m_internal
->GetState() == STATE_RUNNING
;
1648 bool wxThread::IsAlive() const
1650 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1652 switch ( m_internal
->GetState() )
1663 bool wxThread::IsPaused() const
1665 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1667 return (m_internal
->GetState() == STATE_PAUSED
);
1670 //--------------------------------------------------------------------
1672 //--------------------------------------------------------------------
1674 class wxThreadModule
: public wxModule
1677 virtual bool OnInit();
1678 virtual void OnExit();
1681 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1684 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1686 bool wxThreadModule::OnInit()
1688 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1691 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1696 gs_tidMain
= pthread_self();
1698 gs_mutexAllThreads
= new wxMutex();
1700 gs_mutexGui
= new wxMutex();
1701 gs_mutexGui
->Lock();
1703 gs_mutexDeleteThread
= new wxMutex();
1704 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1709 void wxThreadModule::OnExit()
1711 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1713 // are there any threads left which are being deleted right now?
1714 size_t nThreadsBeingDeleted
;
1717 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1718 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1720 if ( nThreadsBeingDeleted
> 0 )
1722 wxLogTrace(TRACE_THREADS
,
1723 _T("Waiting for %lu threads to disappear"),
1724 (unsigned long)nThreadsBeingDeleted
);
1726 // have to wait until all of them disappear
1727 gs_condAllDeleted
->Wait();
1734 wxMutexLocker
lock(*gs_mutexAllThreads
);
1736 // terminate any threads left
1737 count
= gs_allThreads
.GetCount();
1740 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1741 (unsigned long)count
);
1743 } // unlock mutex before deleting the threads as they lock it in their dtor
1745 for ( size_t n
= 0u; n
< count
; n
++ )
1747 // Delete calls the destructor which removes the current entry. We
1748 // should only delete the first one each time.
1749 gs_allThreads
[0]->Delete();
1752 delete gs_mutexAllThreads
;
1754 // destroy GUI mutex
1755 gs_mutexGui
->Unlock();
1758 // and free TLD slot
1759 (void)pthread_key_delete(gs_keySelf
);
1761 delete gs_condAllDeleted
;
1762 delete gs_mutexDeleteThread
;
1765 // ----------------------------------------------------------------------------
1767 // ----------------------------------------------------------------------------
1769 static void ScheduleThreadForDeletion()
1771 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1773 gs_nThreadsBeingDeleted
++;
1775 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1776 (unsigned long)gs_nThreadsBeingDeleted
,
1777 gs_nThreadsBeingDeleted
== 1 ? _T("") : _T("s"));
1780 static void DeleteThread(wxThread
*This
)
1782 // gs_mutexDeleteThread should be unlocked before signalling the condition
1783 // or wxThreadModule::OnExit() would deadlock
1784 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1786 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1790 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1791 _T("no threads scheduled for deletion, yet we delete one?") );
1793 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1794 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1796 if ( !--gs_nThreadsBeingDeleted
)
1798 // no more threads left, signal it
1799 gs_condAllDeleted
->Signal();
1803 void wxMutexGuiEnter()
1805 gs_mutexGui
->Lock();
1808 void wxMutexGuiLeave()
1810 gs_mutexGui
->Unlock();
1813 // ----------------------------------------------------------------------------
1814 // include common implementation code
1815 // ----------------------------------------------------------------------------
1817 #include "wx/thrimpl.cpp"
1819 #endif // wxUSE_THREADS