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())
72 // implement wxCriticalSection using mutexes
73 wxCriticalSection::wxCriticalSection( wxCriticalSectionType critSecType
)
74 : m_mutex( critSecType
== wxCRITSEC_DEFAULT
? wxMUTEX_RECURSIVE
: wxMUTEX_DEFAULT
) { }
75 wxCriticalSection::~wxCriticalSection() { }
77 void wxCriticalSection::Enter() { (void)m_mutex
.Lock(); }
78 void wxCriticalSection::Leave() { (void)m_mutex
.Unlock(); }
81 // ----------------------------------------------------------------------------
83 // ----------------------------------------------------------------------------
85 // the possible states of the thread and transitions from them
88 STATE_NEW
, // didn't start execution yet (=> RUNNING)
89 STATE_RUNNING
, // running (=> PAUSED or EXITED)
90 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
91 STATE_EXITED
// thread doesn't exist any more
94 // the exit value of a thread which has been cancelled
95 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
97 // trace mask for wxThread operations
98 #define TRACE_THREADS _T("thread")
100 // you can get additional debugging messages for the semaphore operations
101 #define TRACE_SEMA _T("semaphore")
103 // ----------------------------------------------------------------------------
105 // ----------------------------------------------------------------------------
107 static void ScheduleThreadForDeletion();
108 static void DeleteThread(wxThread
*This
);
110 // ----------------------------------------------------------------------------
112 // ----------------------------------------------------------------------------
114 // an (non owning) array of pointers to threads
115 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
117 // an entry for a thread we can wait for
119 // -----------------------------------------------------------------------------
121 // -----------------------------------------------------------------------------
123 // we keep the list of all threads created by the application to be able to
124 // terminate them on exit if there are some left - otherwise the process would
126 static wxArrayThread gs_allThreads
;
128 // a mutex to protect gs_allThreads
129 static wxMutex
*gs_mutexAllThreads
= NULL
;
131 // the id of the main thread
132 static pthread_t gs_tidMain
= (pthread_t
)-1;
134 // the key for the pointer to the associated wxThread object
135 static pthread_key_t gs_keySelf
;
137 // the number of threads which are being deleted - the program won't exit
138 // until there are any left
139 static size_t gs_nThreadsBeingDeleted
= 0;
141 // a mutex to protect gs_nThreadsBeingDeleted
142 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
144 // and a condition variable which will be signaled when all
145 // gs_nThreadsBeingDeleted will have been deleted
146 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
148 // this mutex must be acquired before any call to a GUI function
149 // (it's not inside #if wxUSE_GUI because this file is compiled as part
151 static wxMutex
*gs_mutexGui
= NULL
;
153 // when we wait for a thread to exit, we're blocking on a condition which the
154 // thread signals in its SignalExit() method -- but this condition can't be a
155 // member of the thread itself as a detached thread may delete itself at any
156 // moment and accessing the condition member of the thread after this would
157 // result in a disaster
159 // so instead we maintain a global list of the structs below for the threads
160 // we're interested in waiting on
162 // ============================================================================
163 // wxMutex implementation
164 // ============================================================================
166 // ----------------------------------------------------------------------------
168 // ----------------------------------------------------------------------------
170 // this is a simple wrapper around pthread_mutex_t which provides error
172 class wxMutexInternal
175 wxMutexInternal(wxMutexType mutexType
);
179 wxMutexError
Lock(unsigned long ms
);
180 wxMutexError
TryLock();
181 wxMutexError
Unlock();
183 bool IsOk() const { return m_isOk
; }
186 // convert the result of pthread_mutex_[timed]lock() call to wx return code
187 wxMutexError
HandleLockResult(int err
);
190 pthread_mutex_t m_mutex
;
193 // wxConditionInternal uses our m_mutex
194 friend class wxConditionInternal
;
197 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
198 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
199 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
200 // in the library, otherwise we wouldn't compile this code at all)
201 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
204 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
209 case wxMUTEX_RECURSIVE
:
210 // support recursive locks like Win32, i.e. a thread can lock a
211 // mutex which it had itself already locked
213 // unfortunately initialization of recursive mutexes is non
214 // portable, so try several methods
215 #ifdef HAVE_PTHREAD_MUTEXATTR_T
217 pthread_mutexattr_t attr
;
218 pthread_mutexattr_init(&attr
);
219 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
221 err
= pthread_mutex_init(&m_mutex
, &attr
);
223 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
224 // we can use this only as initializer so we have to assign it
225 // first to a temp var - assigning directly to m_mutex wouldn't
228 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
231 #else // no recursive mutexes
233 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
237 wxFAIL_MSG( _T("unknown mutex type") );
240 case wxMUTEX_DEFAULT
:
241 err
= pthread_mutex_init(&m_mutex
, NULL
);
248 wxLogApiError( wxT("pthread_mutex_init()"), err
);
252 wxMutexInternal::~wxMutexInternal()
256 int err
= pthread_mutex_destroy(&m_mutex
);
259 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
264 wxMutexError
wxMutexInternal::Lock()
266 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
269 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
271 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
272 static const long MSEC_IN_SEC
= 1000;
273 static const long NSEC_IN_MSEC
= 1000000;
274 static const long NSEC_IN_USEC
= 1000;
275 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
277 time_t seconds
= ms
/MSEC_IN_SEC
;
278 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
279 timespec ts
= { 0, 0 };
281 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
282 // function is in librt and we don't link with it currently, so use
283 // gettimeofday() instead -- if it turns out that this is really too
284 // imprecise, we should modify configure to check if clock_gettime() is
285 // available and whether it requires -lrt and use it instead
287 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
292 if ( wxGetTimeOfDay(&tv
) != -1 )
294 ts
.tv_sec
= tv
.tv_sec
;
295 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
298 else // fall back on system timer
300 ts
.tv_sec
= time(NULL
);
303 ts
.tv_sec
+= seconds
;
304 ts
.tv_nsec
+= nanoseconds
;
305 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
308 ts
.tv_nsec
-= NSEC_IN_SEC
;
311 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
312 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
315 return wxMUTEX_MISC_ERROR
;
316 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
319 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
324 // only error checking mutexes return this value and so it's an
325 // unexpected situation -- hence use assert, not wxLogDebug
326 wxFAIL_MSG( _T("mutex deadlock prevented") );
327 return wxMUTEX_DEAD_LOCK
;
330 wxLogDebug(_T("pthread_mutex_[timed]lock(): mutex not initialized"));
334 return wxMUTEX_TIMEOUT
;
337 return wxMUTEX_NO_ERROR
;
340 wxLogApiError(_T("pthread_mutex_[timed]lock()"), err
);
343 return wxMUTEX_MISC_ERROR
;
347 wxMutexError
wxMutexInternal::TryLock()
349 int err
= pthread_mutex_trylock(&m_mutex
);
353 // not an error: mutex is already locked, but we're prepared for
358 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
362 return wxMUTEX_NO_ERROR
;
365 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
368 return wxMUTEX_MISC_ERROR
;
371 wxMutexError
wxMutexInternal::Unlock()
373 int err
= pthread_mutex_unlock(&m_mutex
);
377 // we don't own the mutex
378 return wxMUTEX_UNLOCKED
;
381 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
385 return wxMUTEX_NO_ERROR
;
388 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
391 return wxMUTEX_MISC_ERROR
;
394 // ===========================================================================
395 // wxCondition implementation
396 // ===========================================================================
398 // ---------------------------------------------------------------------------
399 // wxConditionInternal
400 // ---------------------------------------------------------------------------
402 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
403 // with a pthread_mutex_t)
404 class wxConditionInternal
407 wxConditionInternal(wxMutex
& mutex
);
408 ~wxConditionInternal();
410 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
413 wxCondError
WaitTimeout(unsigned long milliseconds
);
415 wxCondError
Signal();
416 wxCondError
Broadcast();
419 // get the POSIX mutex associated with us
420 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
423 pthread_cond_t m_cond
;
428 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
431 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
437 wxLogApiError(_T("pthread_cond_init()"), err
);
441 wxConditionInternal::~wxConditionInternal()
445 int err
= pthread_cond_destroy(&m_cond
);
448 wxLogApiError(_T("pthread_cond_destroy()"), err
);
453 wxCondError
wxConditionInternal::Wait()
455 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
458 wxLogApiError(_T("pthread_cond_wait()"), err
);
460 return wxCOND_MISC_ERROR
;
463 return wxCOND_NO_ERROR
;
466 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
468 wxLongLong curtime
= wxGetLocalTimeMillis();
469 curtime
+= milliseconds
;
470 wxLongLong temp
= curtime
/ 1000;
471 int sec
= temp
.GetLo();
473 temp
= curtime
- temp
;
474 int millis
= temp
.GetLo();
479 tspec
.tv_nsec
= millis
* 1000L * 1000L;
481 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
485 return wxCOND_TIMEOUT
;
488 return wxCOND_NO_ERROR
;
491 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
494 return wxCOND_MISC_ERROR
;
497 wxCondError
wxConditionInternal::Signal()
499 int err
= pthread_cond_signal(&m_cond
);
502 wxLogApiError(_T("pthread_cond_signal()"), err
);
504 return wxCOND_MISC_ERROR
;
507 return wxCOND_NO_ERROR
;
510 wxCondError
wxConditionInternal::Broadcast()
512 int err
= pthread_cond_broadcast(&m_cond
);
515 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
517 return wxCOND_MISC_ERROR
;
520 return wxCOND_NO_ERROR
;
523 // ===========================================================================
524 // wxSemaphore implementation
525 // ===========================================================================
527 // ---------------------------------------------------------------------------
528 // wxSemaphoreInternal
529 // ---------------------------------------------------------------------------
531 // we implement the semaphores using mutexes and conditions instead of using
532 // the sem_xxx() POSIX functions because they're not widely available and also
533 // because it's impossible to implement WaitTimeout() using them
534 class wxSemaphoreInternal
537 wxSemaphoreInternal(int initialcount
, int maxcount
);
539 bool IsOk() const { return m_isOk
; }
542 wxSemaError
TryWait();
543 wxSemaError
WaitTimeout(unsigned long milliseconds
);
557 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
561 if ( (initialcount
< 0 || maxcount
< 0) ||
562 ((maxcount
> 0) && (initialcount
> maxcount
)) )
564 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
570 m_maxcount
= (size_t)maxcount
;
571 m_count
= (size_t)initialcount
;
574 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
577 wxSemaError
wxSemaphoreInternal::Wait()
579 wxMutexLocker
locker(m_mutex
);
581 while ( m_count
== 0 )
583 wxLogTrace(TRACE_SEMA
,
584 _T("Thread %ld waiting for semaphore to become signalled"),
585 wxThread::GetCurrentId());
587 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
588 return wxSEMA_MISC_ERROR
;
590 wxLogTrace(TRACE_SEMA
,
591 _T("Thread %ld finished waiting for semaphore, count = %lu"),
592 wxThread::GetCurrentId(), (unsigned long)m_count
);
597 return wxSEMA_NO_ERROR
;
600 wxSemaError
wxSemaphoreInternal::TryWait()
602 wxMutexLocker
locker(m_mutex
);
609 return wxSEMA_NO_ERROR
;
612 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
614 wxMutexLocker
locker(m_mutex
);
616 wxLongLong startTime
= wxGetLocalTimeMillis();
618 while ( m_count
== 0 )
620 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
621 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
622 if ( remainingTime
<= 0 )
625 return wxSEMA_TIMEOUT
;
628 switch ( m_cond
.WaitTimeout(remainingTime
) )
631 return wxSEMA_TIMEOUT
;
634 return wxSEMA_MISC_ERROR
;
636 case wxCOND_NO_ERROR
:
643 return wxSEMA_NO_ERROR
;
646 wxSemaError
wxSemaphoreInternal::Post()
648 wxMutexLocker
locker(m_mutex
);
650 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
652 return wxSEMA_OVERFLOW
;
657 wxLogTrace(TRACE_SEMA
,
658 _T("Thread %ld about to signal semaphore, count = %lu"),
659 wxThread::GetCurrentId(), (unsigned long)m_count
);
661 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
665 // ===========================================================================
666 // wxThread implementation
667 // ===========================================================================
669 // the thread callback functions must have the C linkage
673 #ifdef wxHAVE_PTHREAD_CLEANUP
674 // thread exit function
675 void wxPthreadCleanup(void *ptr
);
676 #endif // wxHAVE_PTHREAD_CLEANUP
678 void *wxPthreadStart(void *ptr
);
682 // ----------------------------------------------------------------------------
684 // ----------------------------------------------------------------------------
686 class wxThreadInternal
692 // thread entry function
693 static void *PthreadStart(wxThread
*thread
);
698 // unblock the thread allowing it to run
699 void SignalRun() { m_semRun
.Post(); }
700 // ask the thread to terminate
702 // go to sleep until Resume() is called
709 int GetPriority() const { return m_prio
; }
710 void SetPriority(int prio
) { m_prio
= prio
; }
712 wxThreadState
GetState() const { return m_state
; }
713 void SetState(wxThreadState state
)
716 static const wxChar
*stateNames
[] =
724 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
725 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
726 #endif // __WXDEBUG__
731 pthread_t
GetId() const { return m_threadId
; }
732 pthread_t
*GetIdPtr() { return &m_threadId
; }
734 void SetCancelFlag() { m_cancelled
= true; }
735 bool WasCancelled() const { return m_cancelled
; }
737 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
738 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
741 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
742 bool IsReallyPaused() const { return m_isPaused
; }
744 // tell the thread that it is a detached one
747 wxCriticalSectionLocker
lock(m_csJoinFlag
);
749 m_shouldBeJoined
= false;
753 #ifdef wxHAVE_PTHREAD_CLEANUP
754 // this is used by wxPthreadCleanup() only
755 static void Cleanup(wxThread
*thread
);
756 #endif // wxHAVE_PTHREAD_CLEANUP
759 pthread_t m_threadId
; // id of the thread
760 wxThreadState m_state
; // see wxThreadState enum
761 int m_prio
; // in wxWidgets units: from 0 to 100
763 // this flag is set when the thread should terminate
766 // this flag is set when the thread is blocking on m_semSuspend
769 // the thread exit code - only used for joinable (!detached) threads and
770 // is only valid after the thread termination
771 wxThread::ExitCode m_exitcode
;
773 // many threads may call Wait(), but only one of them should call
774 // pthread_join(), so we have to keep track of this
775 wxCriticalSection m_csJoinFlag
;
776 bool m_shouldBeJoined
;
779 // this semaphore is posted by Run() and the threads Entry() is not
780 // called before it is done
781 wxSemaphore m_semRun
;
783 // this one is signaled when the thread should resume after having been
785 wxSemaphore m_semSuspend
;
788 // ----------------------------------------------------------------------------
789 // thread startup and exit functions
790 // ----------------------------------------------------------------------------
792 void *wxPthreadStart(void *ptr
)
794 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
797 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
799 wxThreadInternal
*pthread
= thread
->m_internal
;
801 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
803 // associate the thread pointer with the newly created thread so that
804 // wxThread::This() will work
805 int rc
= pthread_setspecific(gs_keySelf
, thread
);
808 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
813 // have to declare this before pthread_cleanup_push() which defines a
817 #ifdef wxHAVE_PTHREAD_CLEANUP
818 // install the cleanup handler which will be called if the thread is
820 pthread_cleanup_push(wxPthreadCleanup
, thread
);
821 #endif // wxHAVE_PTHREAD_CLEANUP
823 // wait for the semaphore to be posted from Run()
824 pthread
->m_semRun
.Wait();
826 // test whether we should run the run at all - may be it was deleted
827 // before it started to Run()?
829 wxCriticalSectionLocker
lock(thread
->m_critsect
);
831 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
832 pthread
->WasCancelled();
837 // call the main entry
838 wxLogTrace(TRACE_THREADS
,
839 _T("Thread %ld about to enter its Entry()."),
844 pthread
->m_exitcode
= thread
->Entry();
846 wxLogTrace(TRACE_THREADS
,
847 _T("Thread %ld Entry() returned %lu."),
848 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
850 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
853 wxCriticalSectionLocker
lock(thread
->m_critsect
);
855 // change the state of the thread to "exited" so that
856 // wxPthreadCleanup handler won't do anything from now (if it's
857 // called before we do pthread_cleanup_pop below)
858 pthread
->SetState(STATE_EXITED
);
862 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
863 // '}' for the '{' in push, so they must be used in the same block!
864 #ifdef wxHAVE_PTHREAD_CLEANUP
866 // under Tru64 we get a warning from macro expansion
868 #pragma message disable(declbutnotref)
871 // remove the cleanup handler without executing it
872 pthread_cleanup_pop(FALSE
);
875 #pragma message restore
877 #endif // wxHAVE_PTHREAD_CLEANUP
881 // FIXME: deleting a possibly joinable thread here???
884 return EXITCODE_CANCELLED
;
888 // terminate the thread
889 thread
->Exit(pthread
->m_exitcode
);
891 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
897 #ifdef wxHAVE_PTHREAD_CLEANUP
899 // this handler is called when the thread is cancelled
900 extern "C" void wxPthreadCleanup(void *ptr
)
902 wxThreadInternal::Cleanup((wxThread
*)ptr
);
905 void wxThreadInternal::Cleanup(wxThread
*thread
)
907 if (pthread_getspecific(gs_keySelf
) == 0) return;
909 wxCriticalSectionLocker
lock(thread
->m_critsect
);
910 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
912 // thread is already considered as finished.
917 // exit the thread gracefully
918 thread
->Exit(EXITCODE_CANCELLED
);
921 #endif // wxHAVE_PTHREAD_CLEANUP
923 // ----------------------------------------------------------------------------
925 // ----------------------------------------------------------------------------
927 wxThreadInternal::wxThreadInternal()
931 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
935 // set to true only when the thread starts waiting on m_semSuspend
938 // defaults for joinable threads
939 m_shouldBeJoined
= true;
940 m_isDetached
= false;
943 wxThreadInternal::~wxThreadInternal()
947 wxThreadError
wxThreadInternal::Run()
949 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
950 wxT("thread may only be started once after Create()") );
952 SetState(STATE_RUNNING
);
954 // wake up threads waiting for our start
957 return wxTHREAD_NO_ERROR
;
960 void wxThreadInternal::Wait()
962 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
964 // if the thread we're waiting for is waiting for the GUI mutex, we will
965 // deadlock so make sure we release it temporarily
966 if ( wxThread::IsMain() )
969 wxLogTrace(TRACE_THREADS
,
970 _T("Starting to wait for thread %ld to exit."),
973 // to avoid memory leaks we should call pthread_join(), but it must only be
974 // done once so use a critical section to serialize the code below
976 wxCriticalSectionLocker
lock(m_csJoinFlag
);
978 if ( m_shouldBeJoined
)
980 // FIXME shouldn't we set cancellation type to DISABLED here? If
981 // we're cancelled inside pthread_join(), things will almost
982 // certainly break - but if we disable the cancellation, we
984 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
986 // this is a serious problem, so use wxLogError and not
987 // wxLogDebug: it is possible to bring the system to its knees
988 // by creating too many threads and not joining them quite
990 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
993 m_shouldBeJoined
= false;
997 // reacquire GUI mutex
998 if ( wxThread::IsMain() )
1002 void wxThreadInternal::Pause()
1004 // the state is set from the thread which pauses us first, this function
1005 // is called later so the state should have been already set
1006 wxCHECK_RET( m_state
== STATE_PAUSED
,
1007 wxT("thread must first be paused with wxThread::Pause().") );
1009 wxLogTrace(TRACE_THREADS
,
1010 _T("Thread %ld goes to sleep."), THR_ID(this));
1012 // wait until the semaphore is Post()ed from Resume()
1013 m_semSuspend
.Wait();
1016 void wxThreadInternal::Resume()
1018 wxCHECK_RET( m_state
== STATE_PAUSED
,
1019 wxT("can't resume thread which is not suspended.") );
1021 // the thread might be not actually paused yet - if there were no call to
1022 // TestDestroy() since the last call to Pause() for example
1023 if ( IsReallyPaused() )
1025 wxLogTrace(TRACE_THREADS
,
1026 _T("Waking up thread %ld"), THR_ID(this));
1029 m_semSuspend
.Post();
1032 SetReallyPaused(false);
1036 wxLogTrace(TRACE_THREADS
,
1037 _T("Thread %ld is not yet really paused"), THR_ID(this));
1040 SetState(STATE_RUNNING
);
1043 // -----------------------------------------------------------------------------
1044 // wxThread static functions
1045 // -----------------------------------------------------------------------------
1047 wxThread
*wxThread::This()
1049 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1052 bool wxThread::IsMain()
1054 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
1057 void wxThread::Yield()
1059 #ifdef HAVE_SCHED_YIELD
1064 int wxThread::GetCPUCount()
1066 #if defined(_SC_NPROCESSORS_ONLN)
1067 // this works for Solaris and Linux 2.6
1068 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1073 #elif defined(__LINUX__) && wxUSE_FFILE
1074 // read from proc (can't use wxTextFile here because it's a special file:
1075 // it has 0 size but still can be read from)
1078 wxFFile
file(_T("/proc/cpuinfo"));
1079 if ( file
.IsOpened() )
1081 // slurp the whole file
1083 if ( file
.ReadAll(&s
) )
1085 // (ab)use Replace() to find the number of "processor: num" strings
1086 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1092 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1096 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1099 #endif // different ways to get number of CPUs
1105 // VMS is a 64 bit system and threads have 64 bit pointers.
1106 // FIXME: also needed for other systems????
1108 unsigned long long wxThread::GetCurrentId()
1110 return (unsigned long long)pthread_self();
1115 unsigned long wxThread::GetCurrentId()
1117 return (unsigned long)pthread_self();
1120 #endif // __VMS/!__VMS
1123 bool wxThread::SetConcurrency(size_t level
)
1125 #ifdef HAVE_THR_SETCONCURRENCY
1126 int rc
= thr_setconcurrency(level
);
1129 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1133 #else // !HAVE_THR_SETCONCURRENCY
1134 // ok only for the default value
1136 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1139 // -----------------------------------------------------------------------------
1141 // -----------------------------------------------------------------------------
1143 wxThread::wxThread(wxThreadKind kind
)
1145 // add this thread to the global list of all threads
1147 wxMutexLocker
lock(*gs_mutexAllThreads
);
1149 gs_allThreads
.Add(this);
1152 m_internal
= new wxThreadInternal();
1154 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1157 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1158 #define WXUNUSED_STACKSIZE(identifier) identifier
1160 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1163 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1165 if ( m_internal
->GetState() != STATE_NEW
)
1167 // don't recreate thread
1168 return wxTHREAD_RUNNING
;
1171 // set up the thread attribute: right now, we only set thread priority
1172 pthread_attr_t attr
;
1173 pthread_attr_init(&attr
);
1175 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1177 pthread_attr_setstacksize(&attr
, stackSize
);
1180 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1182 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1184 wxLogError(_("Cannot retrieve thread scheduling policy."));
1188 /* the pthread.h contains too many spaces. This is a work-around */
1189 # undef sched_get_priority_max
1190 #undef sched_get_priority_min
1191 #define sched_get_priority_max(_pol_) \
1192 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1193 #define sched_get_priority_min(_pol_) \
1194 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1197 int max_prio
= sched_get_priority_max(policy
),
1198 min_prio
= sched_get_priority_min(policy
),
1199 prio
= m_internal
->GetPriority();
1201 if ( min_prio
== -1 || max_prio
== -1 )
1203 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1206 else if ( max_prio
== min_prio
)
1208 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1210 // notify the programmer that this doesn't work here
1211 wxLogWarning(_("Thread priority setting is ignored."));
1213 //else: we have default priority, so don't complain
1215 // anyhow, don't do anything because priority is just ignored
1219 struct sched_param sp
;
1220 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1222 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1225 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1227 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1229 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1232 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1234 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1235 // this will make the threads created by this process really concurrent
1236 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1238 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1240 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1242 // VZ: assume that this one is always available (it's rather fundamental),
1243 // if this function is ever missing we should try to use
1244 // pthread_detach() instead (after thread creation)
1247 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1249 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1252 // never try to join detached threads
1253 m_internal
->Detach();
1255 //else: threads are created joinable by default, it's ok
1257 // create the new OS thread object
1258 int rc
= pthread_create
1260 m_internal
->GetIdPtr(),
1266 if ( pthread_attr_destroy(&attr
) != 0 )
1268 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1273 m_internal
->SetState(STATE_EXITED
);
1275 return wxTHREAD_NO_RESOURCE
;
1278 return wxTHREAD_NO_ERROR
;
1281 wxThreadError
wxThread::Run()
1283 wxCriticalSectionLocker
lock(m_critsect
);
1285 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1286 wxT("must call wxThread::Create() first") );
1288 return m_internal
->Run();
1291 // -----------------------------------------------------------------------------
1293 // -----------------------------------------------------------------------------
1295 void wxThread::SetPriority(unsigned int prio
)
1297 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1298 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1299 wxT("invalid thread priority") );
1301 wxCriticalSectionLocker
lock(m_critsect
);
1303 switch ( m_internal
->GetState() )
1306 // thread not yet started, priority will be set when it is
1307 m_internal
->SetPriority(prio
);
1312 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1313 #if defined(__LINUX__)
1314 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1315 // a priority other than 0. Instead, we use the BSD setpriority
1316 // which alllows us to set a 'nice' value between 20 to -20. Only
1317 // super user can set a value less than zero (more negative yields
1318 // higher priority). setpriority set the static priority of a
1319 // process, but this is OK since Linux is configured as a thread
1322 // FIXME this is not true for 2.6!!
1324 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1325 // to Unix priorities 20..-20
1326 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1328 wxLogError(_("Failed to set thread priority %d."), prio
);
1332 struct sched_param sparam
;
1333 sparam
.sched_priority
= prio
;
1335 if ( pthread_setschedparam(m_internal
->GetId(),
1336 SCHED_OTHER
, &sparam
) != 0 )
1338 wxLogError(_("Failed to set thread priority %d."), prio
);
1342 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1347 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1351 unsigned int wxThread::GetPriority() const
1353 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1355 return m_internal
->GetPriority();
1358 wxThreadIdType
wxThread::GetId() const
1360 return (wxThreadIdType
) m_internal
->GetId();
1363 // -----------------------------------------------------------------------------
1365 // -----------------------------------------------------------------------------
1367 wxThreadError
wxThread::Pause()
1369 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1370 _T("a thread can't pause itself") );
1372 wxCriticalSectionLocker
lock(m_critsect
);
1374 if ( m_internal
->GetState() != STATE_RUNNING
)
1376 wxLogDebug(wxT("Can't pause thread which is not running."));
1378 return wxTHREAD_NOT_RUNNING
;
1381 // just set a flag, the thread will be really paused only during the next
1382 // call to TestDestroy()
1383 m_internal
->SetState(STATE_PAUSED
);
1385 return wxTHREAD_NO_ERROR
;
1388 wxThreadError
wxThread::Resume()
1390 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1391 _T("a thread can't resume itself") );
1393 wxCriticalSectionLocker
lock(m_critsect
);
1395 wxThreadState state
= m_internal
->GetState();
1400 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1403 m_internal
->Resume();
1405 return wxTHREAD_NO_ERROR
;
1408 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1410 return wxTHREAD_NO_ERROR
;
1413 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1415 return wxTHREAD_MISC_ERROR
;
1419 // -----------------------------------------------------------------------------
1421 // -----------------------------------------------------------------------------
1423 wxThread::ExitCode
wxThread::Wait()
1425 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1426 _T("a thread can't wait for itself") );
1428 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1429 _T("can't wait for detached thread") );
1433 return m_internal
->GetExitCode();
1436 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1438 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1439 _T("a thread can't delete itself") );
1441 bool isDetached
= m_isDetached
;
1444 wxThreadState state
= m_internal
->GetState();
1446 // ask the thread to stop
1447 m_internal
->SetCancelFlag();
1454 // we need to wake up the thread so that PthreadStart() will
1455 // terminate - right now it's blocking on run semaphore in
1457 m_internal
->SignalRun();
1466 // resume the thread first
1467 m_internal
->Resume();
1474 // wait until the thread stops
1479 // return the exit code of the thread
1480 *rc
= m_internal
->GetExitCode();
1483 //else: can't wait for detached threads
1486 return wxTHREAD_NO_ERROR
;
1489 wxThreadError
wxThread::Kill()
1491 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1492 _T("a thread can't kill itself") );
1494 switch ( m_internal
->GetState() )
1498 return wxTHREAD_NOT_RUNNING
;
1501 // resume the thread first
1507 #ifdef HAVE_PTHREAD_CANCEL
1508 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1509 #endif // HAVE_PTHREAD_CANCEL
1511 wxLogError(_("Failed to terminate a thread."));
1513 return wxTHREAD_MISC_ERROR
;
1516 #ifdef HAVE_PTHREAD_CANCEL
1519 // if we use cleanup function, this will be done from
1520 // wxPthreadCleanup()
1521 #ifndef wxHAVE_PTHREAD_CLEANUP
1522 ScheduleThreadForDeletion();
1524 // don't call OnExit() here, it can only be called in the
1525 // threads context and we're in the context of another thread
1528 #endif // wxHAVE_PTHREAD_CLEANUP
1532 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1535 return wxTHREAD_NO_ERROR
;
1536 #endif // HAVE_PTHREAD_CANCEL
1540 void wxThread::Exit(ExitCode status
)
1542 wxASSERT_MSG( This() == this,
1543 _T("wxThread::Exit() can only be called in the context of the same thread") );
1547 // from the moment we call OnExit(), the main program may terminate at
1548 // any moment, so mark this thread as being already in process of being
1549 // deleted or wxThreadModule::OnExit() will try to delete it again
1550 ScheduleThreadForDeletion();
1553 // don't enter m_critsect before calling OnExit() because the user code
1554 // might deadlock if, for example, it signals a condition in OnExit() (a
1555 // common case) while the main thread calls any of functions entering
1556 // m_critsect on us (almost all of them do)
1561 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
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 :-(
1574 pthread_setspecific(gs_keySelf
, 0);
1579 m_internal
->SetState(STATE_EXITED
);
1583 // terminate the thread (pthread_exit() never returns)
1584 pthread_exit(status
);
1586 wxFAIL_MSG(_T("pthread_exit() failed"));
1589 // also test whether we were paused
1590 bool wxThread::TestDestroy()
1592 wxASSERT_MSG( This() == this,
1593 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1597 if ( m_internal
->GetState() == STATE_PAUSED
)
1599 m_internal
->SetReallyPaused(true);
1601 // leave the crit section or the other threads will stop too if they
1602 // try to call any of (seemingly harmless) IsXXX() functions while we
1606 m_internal
->Pause();
1610 // thread wasn't requested to pause, nothing to do
1614 return m_internal
->WasCancelled();
1617 wxThread::~wxThread()
1622 // check that the thread either exited or couldn't be created
1623 if ( m_internal
->GetState() != STATE_EXITED
&&
1624 m_internal
->GetState() != STATE_NEW
)
1626 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1631 #endif // __WXDEBUG__
1635 // remove this thread from the global array
1637 wxMutexLocker
lock(*gs_mutexAllThreads
);
1639 gs_allThreads
.Remove(this);
1643 // -----------------------------------------------------------------------------
1645 // -----------------------------------------------------------------------------
1647 bool wxThread::IsRunning() const
1649 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1651 return m_internal
->GetState() == STATE_RUNNING
;
1654 bool wxThread::IsAlive() const
1656 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1658 switch ( m_internal
->GetState() )
1669 bool wxThread::IsPaused() const
1671 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1673 return (m_internal
->GetState() == STATE_PAUSED
);
1676 //--------------------------------------------------------------------
1678 //--------------------------------------------------------------------
1680 class wxThreadModule
: public wxModule
1683 virtual bool OnInit();
1684 virtual void OnExit();
1687 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1690 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1692 bool wxThreadModule::OnInit()
1694 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1697 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1702 gs_tidMain
= pthread_self();
1704 gs_mutexAllThreads
= new wxMutex();
1706 gs_mutexGui
= new wxMutex();
1707 gs_mutexGui
->Lock();
1709 gs_mutexDeleteThread
= new wxMutex();
1710 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1715 void wxThreadModule::OnExit()
1717 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1719 // are there any threads left which are being deleted right now?
1720 size_t nThreadsBeingDeleted
;
1723 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1724 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1726 if ( nThreadsBeingDeleted
> 0 )
1728 wxLogTrace(TRACE_THREADS
,
1729 _T("Waiting for %lu threads to disappear"),
1730 (unsigned long)nThreadsBeingDeleted
);
1732 // have to wait until all of them disappear
1733 gs_condAllDeleted
->Wait();
1740 wxMutexLocker
lock(*gs_mutexAllThreads
);
1742 // terminate any threads left
1743 count
= gs_allThreads
.GetCount();
1746 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1747 (unsigned long)count
);
1749 } // unlock mutex before deleting the threads as they lock it in their dtor
1751 for ( size_t n
= 0u; n
< count
; n
++ )
1753 // Delete calls the destructor which removes the current entry. We
1754 // should only delete the first one each time.
1755 gs_allThreads
[0]->Delete();
1758 delete gs_mutexAllThreads
;
1760 // destroy GUI mutex
1761 gs_mutexGui
->Unlock();
1764 // and free TLD slot
1765 (void)pthread_key_delete(gs_keySelf
);
1767 delete gs_condAllDeleted
;
1768 delete gs_mutexDeleteThread
;
1771 // ----------------------------------------------------------------------------
1773 // ----------------------------------------------------------------------------
1775 static void ScheduleThreadForDeletion()
1777 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1779 gs_nThreadsBeingDeleted
++;
1781 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1782 (unsigned long)gs_nThreadsBeingDeleted
,
1783 gs_nThreadsBeingDeleted
== 1 ? _T("") : _T("s"));
1786 static void DeleteThread(wxThread
*This
)
1788 // gs_mutexDeleteThread should be unlocked before signalling the condition
1789 // or wxThreadModule::OnExit() would deadlock
1790 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1792 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1796 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1797 _T("no threads scheduled for deletion, yet we delete one?") );
1799 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1800 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1802 if ( !--gs_nThreadsBeingDeleted
)
1804 // no more threads left, signal it
1805 gs_condAllDeleted
->Signal();
1809 void wxMutexGuiEnterImpl()
1811 gs_mutexGui
->Lock();
1814 void wxMutexGuiLeaveImpl()
1816 gs_mutexGui
->Unlock();
1819 // ----------------------------------------------------------------------------
1820 // include common implementation code
1821 // ----------------------------------------------------------------------------
1823 #include "wx/thrimpl.cpp"
1825 #endif // wxUSE_THREADS