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"
32 #include "wx/dynarray.h"
37 #include "wx/stopwatch.h"
38 #include "wx/module.h"
50 #ifdef HAVE_THR_SETCONCURRENCY
54 // we use wxFFile under Linux in GetCPUCount()
59 #include <sys/resource.h>
63 #define THR_ID(thr) ((long long)(thr)->GetId())
65 #define THR_ID(thr) ((long)(thr)->GetId())
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // the possible states of the thread and transitions from them
75 STATE_NEW
, // didn't start execution yet (=> RUNNING)
76 STATE_RUNNING
, // running (=> PAUSED or EXITED)
77 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
78 STATE_EXITED
// thread doesn't exist any more
81 // the exit value of a thread which has been cancelled
82 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
84 // trace mask for wxThread operations
85 #define TRACE_THREADS _T("thread")
87 // you can get additional debugging messages for the semaphore operations
88 #define TRACE_SEMA _T("semaphore")
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 static void ScheduleThreadForDeletion();
95 static void DeleteThread(wxThread
*This
);
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 // an (non owning) array of pointers to threads
102 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
104 // an entry for a thread we can wait for
106 // -----------------------------------------------------------------------------
108 // -----------------------------------------------------------------------------
110 // we keep the list of all threads created by the application to be able to
111 // terminate them on exit if there are some left - otherwise the process would
113 static wxArrayThread gs_allThreads
;
115 // a mutex to protect gs_allThreads
116 static wxMutex
*gs_mutexAllThreads
= NULL
;
118 // the id of the main thread
119 static pthread_t gs_tidMain
= (pthread_t
)-1;
121 // the key for the pointer to the associated wxThread object
122 static pthread_key_t gs_keySelf
;
124 // the number of threads which are being deleted - the program won't exit
125 // until there are any left
126 static size_t gs_nThreadsBeingDeleted
= 0;
128 // a mutex to protect gs_nThreadsBeingDeleted
129 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
131 // and a condition variable which will be signaled when all
132 // gs_nThreadsBeingDeleted will have been deleted
133 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
135 // this mutex must be acquired before any call to a GUI function
136 // (it's not inside #if wxUSE_GUI because this file is compiled as part
138 static wxMutex
*gs_mutexGui
= NULL
;
140 // when we wait for a thread to exit, we're blocking on a condition which the
141 // thread signals in its SignalExit() method -- but this condition can't be a
142 // member of the thread itself as a detached thread may delete itself at any
143 // moment and accessing the condition member of the thread after this would
144 // result in a disaster
146 // so instead we maintain a global list of the structs below for the threads
147 // we're interested in waiting on
149 // ============================================================================
150 // wxMutex implementation
151 // ============================================================================
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // this is a simple wrapper around pthread_mutex_t which provides error
159 class wxMutexInternal
162 wxMutexInternal(wxMutexType mutexType
);
166 wxMutexError
Lock(unsigned long ms
);
167 wxMutexError
TryLock();
168 wxMutexError
Unlock();
170 bool IsOk() const { return m_isOk
; }
173 // convert the result of pthread_mutex_[timed]lock() call to wx return code
174 wxMutexError
HandleLockResult(int err
);
177 pthread_mutex_t m_mutex
;
180 // wxConditionInternal uses our m_mutex
181 friend class wxConditionInternal
;
184 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
185 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
186 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
187 // in the library, otherwise we wouldn't compile this code at all)
188 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
191 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
196 case wxMUTEX_RECURSIVE
:
197 // support recursive locks like Win32, i.e. a thread can lock a
198 // mutex which it had itself already locked
200 // unfortunately initialization of recursive mutexes is non
201 // portable, so try several methods
202 #ifdef HAVE_PTHREAD_MUTEXATTR_T
204 pthread_mutexattr_t attr
;
205 pthread_mutexattr_init(&attr
);
206 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
208 err
= pthread_mutex_init(&m_mutex
, &attr
);
210 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
211 // we can use this only as initializer so we have to assign it
212 // first to a temp var - assigning directly to m_mutex wouldn't
215 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
218 #else // no recursive mutexes
220 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
224 wxFAIL_MSG( _T("unknown mutex type") );
227 case wxMUTEX_DEFAULT
:
228 err
= pthread_mutex_init(&m_mutex
, NULL
);
235 wxLogApiError( wxT("pthread_mutex_init()"), err
);
239 wxMutexInternal::~wxMutexInternal()
243 int err
= pthread_mutex_destroy(&m_mutex
);
246 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
251 wxMutexError
wxMutexInternal::Lock()
253 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
256 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
258 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
259 static const long MSEC_IN_SEC
= 1000;
260 static const long NSEC_IN_MSEC
= 1000000;
261 static const long NSEC_IN_USEC
= 1000;
262 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
264 time_t seconds
= ms
/MSEC_IN_SEC
;
265 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
266 timespec ts
= { 0, 0 };
268 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
269 // function is in librt and we don't link with it currently, so use
270 // gettimeofday() instead -- if it turns out that this is really too
271 // imprecise, we should modify configure to check if clock_gettime() is
272 // available and whether it requires -lrt and use it instead
274 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
279 if ( wxGetTimeOfDay(&tv
) != -1 )
281 ts
.tv_sec
= tv
.tv_sec
;
282 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
285 else // fall back on system timer
287 ts
.tv_sec
= time(NULL
);
290 ts
.tv_sec
+= seconds
;
291 ts
.tv_nsec
+= nanoseconds
;
292 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
295 ts
.tv_nsec
-= NSEC_IN_SEC
;
298 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
299 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
302 return wxMUTEX_MISC_ERROR
;
303 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
306 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
311 // only error checking mutexes return this value and so it's an
312 // unexpected situation -- hence use assert, not wxLogDebug
313 wxFAIL_MSG( _T("mutex deadlock prevented") );
314 return wxMUTEX_DEAD_LOCK
;
317 wxLogDebug(_T("pthread_mutex_[timed]lock(): mutex not initialized"));
321 return wxMUTEX_TIMEOUT
;
324 return wxMUTEX_NO_ERROR
;
327 wxLogApiError(_T("pthread_mutex_[timed]lock()"), err
);
330 return wxMUTEX_MISC_ERROR
;
334 wxMutexError
wxMutexInternal::TryLock()
336 int err
= pthread_mutex_trylock(&m_mutex
);
340 // not an error: mutex is already locked, but we're prepared for
345 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
349 return wxMUTEX_NO_ERROR
;
352 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
355 return wxMUTEX_MISC_ERROR
;
358 wxMutexError
wxMutexInternal::Unlock()
360 int err
= pthread_mutex_unlock(&m_mutex
);
364 // we don't own the mutex
365 return wxMUTEX_UNLOCKED
;
368 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
372 return wxMUTEX_NO_ERROR
;
375 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
378 return wxMUTEX_MISC_ERROR
;
381 // ===========================================================================
382 // wxCondition implementation
383 // ===========================================================================
385 // ---------------------------------------------------------------------------
386 // wxConditionInternal
387 // ---------------------------------------------------------------------------
389 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
390 // with a pthread_mutex_t)
391 class wxConditionInternal
394 wxConditionInternal(wxMutex
& mutex
);
395 ~wxConditionInternal();
397 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
400 wxCondError
WaitTimeout(unsigned long milliseconds
);
402 wxCondError
Signal();
403 wxCondError
Broadcast();
406 // get the POSIX mutex associated with us
407 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
410 pthread_cond_t m_cond
;
415 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
418 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
424 wxLogApiError(_T("pthread_cond_init()"), err
);
428 wxConditionInternal::~wxConditionInternal()
432 int err
= pthread_cond_destroy(&m_cond
);
435 wxLogApiError(_T("pthread_cond_destroy()"), err
);
440 wxCondError
wxConditionInternal::Wait()
442 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
445 wxLogApiError(_T("pthread_cond_wait()"), err
);
447 return wxCOND_MISC_ERROR
;
450 return wxCOND_NO_ERROR
;
453 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
455 wxLongLong curtime
= wxGetLocalTimeMillis();
456 curtime
+= milliseconds
;
457 wxLongLong temp
= curtime
/ 1000;
458 int sec
= temp
.GetLo();
460 temp
= curtime
- temp
;
461 int millis
= temp
.GetLo();
466 tspec
.tv_nsec
= millis
* 1000L * 1000L;
468 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
472 return wxCOND_TIMEOUT
;
475 return wxCOND_NO_ERROR
;
478 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
481 return wxCOND_MISC_ERROR
;
484 wxCondError
wxConditionInternal::Signal()
486 int err
= pthread_cond_signal(&m_cond
);
489 wxLogApiError(_T("pthread_cond_signal()"), err
);
491 return wxCOND_MISC_ERROR
;
494 return wxCOND_NO_ERROR
;
497 wxCondError
wxConditionInternal::Broadcast()
499 int err
= pthread_cond_broadcast(&m_cond
);
502 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
504 return wxCOND_MISC_ERROR
;
507 return wxCOND_NO_ERROR
;
510 // ===========================================================================
511 // wxSemaphore implementation
512 // ===========================================================================
514 // ---------------------------------------------------------------------------
515 // wxSemaphoreInternal
516 // ---------------------------------------------------------------------------
518 // we implement the semaphores using mutexes and conditions instead of using
519 // the sem_xxx() POSIX functions because they're not widely available and also
520 // because it's impossible to implement WaitTimeout() using them
521 class wxSemaphoreInternal
524 wxSemaphoreInternal(int initialcount
, int maxcount
);
526 bool IsOk() const { return m_isOk
; }
529 wxSemaError
TryWait();
530 wxSemaError
WaitTimeout(unsigned long milliseconds
);
544 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
548 if ( (initialcount
< 0 || maxcount
< 0) ||
549 ((maxcount
> 0) && (initialcount
> maxcount
)) )
551 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
557 m_maxcount
= (size_t)maxcount
;
558 m_count
= (size_t)initialcount
;
561 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
564 wxSemaError
wxSemaphoreInternal::Wait()
566 wxMutexLocker
locker(m_mutex
);
568 while ( m_count
== 0 )
570 wxLogTrace(TRACE_SEMA
,
571 _T("Thread %ld waiting for semaphore to become signalled"),
572 wxThread::GetCurrentId());
574 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
575 return wxSEMA_MISC_ERROR
;
577 wxLogTrace(TRACE_SEMA
,
578 _T("Thread %ld finished waiting for semaphore, count = %lu"),
579 wxThread::GetCurrentId(), (unsigned long)m_count
);
584 return wxSEMA_NO_ERROR
;
587 wxSemaError
wxSemaphoreInternal::TryWait()
589 wxMutexLocker
locker(m_mutex
);
596 return wxSEMA_NO_ERROR
;
599 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
601 wxMutexLocker
locker(m_mutex
);
603 wxLongLong startTime
= wxGetLocalTimeMillis();
605 while ( m_count
== 0 )
607 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
608 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
609 if ( remainingTime
<= 0 )
612 return wxSEMA_TIMEOUT
;
615 switch ( m_cond
.WaitTimeout(remainingTime
) )
618 return wxSEMA_TIMEOUT
;
621 return wxSEMA_MISC_ERROR
;
623 case wxCOND_NO_ERROR
:
630 return wxSEMA_NO_ERROR
;
633 wxSemaError
wxSemaphoreInternal::Post()
635 wxMutexLocker
locker(m_mutex
);
637 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
639 return wxSEMA_OVERFLOW
;
644 wxLogTrace(TRACE_SEMA
,
645 _T("Thread %ld about to signal semaphore, count = %lu"),
646 wxThread::GetCurrentId(), (unsigned long)m_count
);
648 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
652 // ===========================================================================
653 // wxThread implementation
654 // ===========================================================================
656 // the thread callback functions must have the C linkage
660 #ifdef wxHAVE_PTHREAD_CLEANUP
661 // thread exit function
662 void wxPthreadCleanup(void *ptr
);
663 #endif // wxHAVE_PTHREAD_CLEANUP
665 void *wxPthreadStart(void *ptr
);
669 // ----------------------------------------------------------------------------
671 // ----------------------------------------------------------------------------
673 class wxThreadInternal
679 // thread entry function
680 static void *PthreadStart(wxThread
*thread
);
685 // unblock the thread allowing it to run
686 void SignalRun() { m_semRun
.Post(); }
687 // ask the thread to terminate
689 // go to sleep until Resume() is called
696 int GetPriority() const { return m_prio
; }
697 void SetPriority(int prio
) { m_prio
= prio
; }
699 wxThreadState
GetState() const { return m_state
; }
700 void SetState(wxThreadState state
)
703 static const wxChar
*stateNames
[] =
711 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
712 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
713 #endif // __WXDEBUG__
718 pthread_t
GetId() const { return m_threadId
; }
719 pthread_t
*GetIdPtr() { return &m_threadId
; }
721 void SetCancelFlag() { m_cancelled
= true; }
722 bool WasCancelled() const { return m_cancelled
; }
724 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
725 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
728 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
729 bool IsReallyPaused() const { return m_isPaused
; }
731 // tell the thread that it is a detached one
734 wxCriticalSectionLocker
lock(m_csJoinFlag
);
736 m_shouldBeJoined
= false;
740 #ifdef wxHAVE_PTHREAD_CLEANUP
741 // this is used by wxPthreadCleanup() only
742 static void Cleanup(wxThread
*thread
);
743 #endif // wxHAVE_PTHREAD_CLEANUP
746 pthread_t m_threadId
; // id of the thread
747 wxThreadState m_state
; // see wxThreadState enum
748 int m_prio
; // in wxWidgets units: from 0 to 100
750 // this flag is set when the thread should terminate
753 // this flag is set when the thread is blocking on m_semSuspend
756 // the thread exit code - only used for joinable (!detached) threads and
757 // is only valid after the thread termination
758 wxThread::ExitCode m_exitcode
;
760 // many threads may call Wait(), but only one of them should call
761 // pthread_join(), so we have to keep track of this
762 wxCriticalSection m_csJoinFlag
;
763 bool m_shouldBeJoined
;
766 // this semaphore is posted by Run() and the threads Entry() is not
767 // called before it is done
768 wxSemaphore m_semRun
;
770 // this one is signaled when the thread should resume after having been
772 wxSemaphore m_semSuspend
;
775 // ----------------------------------------------------------------------------
776 // thread startup and exit functions
777 // ----------------------------------------------------------------------------
779 void *wxPthreadStart(void *ptr
)
781 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
784 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
786 wxThreadInternal
*pthread
= thread
->m_internal
;
788 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
790 // associate the thread pointer with the newly created thread so that
791 // wxThread::This() will work
792 int rc
= pthread_setspecific(gs_keySelf
, thread
);
795 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
800 // have to declare this before pthread_cleanup_push() which defines a
804 #ifdef wxHAVE_PTHREAD_CLEANUP
805 // install the cleanup handler which will be called if the thread is
807 pthread_cleanup_push(wxPthreadCleanup
, thread
);
808 #endif // wxHAVE_PTHREAD_CLEANUP
810 // wait for the semaphore to be posted from Run()
811 pthread
->m_semRun
.Wait();
813 // test whether we should run the run at all - may be it was deleted
814 // before it started to Run()?
816 wxCriticalSectionLocker
lock(thread
->m_critsect
);
818 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
819 pthread
->WasCancelled();
824 // call the main entry
825 wxLogTrace(TRACE_THREADS
,
826 _T("Thread %ld about to enter its Entry()."),
829 pthread
->m_exitcode
= thread
->Entry();
831 wxLogTrace(TRACE_THREADS
,
832 _T("Thread %ld Entry() returned %lu."),
833 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
836 wxCriticalSectionLocker
lock(thread
->m_critsect
);
838 // change the state of the thread to "exited" so that
839 // wxPthreadCleanup handler won't do anything from now (if it's
840 // called before we do pthread_cleanup_pop below)
841 pthread
->SetState(STATE_EXITED
);
845 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
846 // '}' for the '{' in push, so they must be used in the same block!
847 #ifdef wxHAVE_PTHREAD_CLEANUP
849 // under Tru64 we get a warning from macro expansion
851 #pragma message disable(declbutnotref)
854 // remove the cleanup handler without executing it
855 pthread_cleanup_pop(FALSE
);
858 #pragma message restore
860 #endif // wxHAVE_PTHREAD_CLEANUP
864 // FIXME: deleting a possibly joinable thread here???
867 return EXITCODE_CANCELLED
;
871 // terminate the thread
872 thread
->Exit(pthread
->m_exitcode
);
874 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
880 #ifdef wxHAVE_PTHREAD_CLEANUP
882 // this handler is called when the thread is cancelled
883 extern "C" void wxPthreadCleanup(void *ptr
)
885 wxThreadInternal::Cleanup((wxThread
*)ptr
);
888 void wxThreadInternal::Cleanup(wxThread
*thread
)
890 if (pthread_getspecific(gs_keySelf
) == 0) return;
892 wxCriticalSectionLocker
lock(thread
->m_critsect
);
893 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
895 // thread is already considered as finished.
900 // exit the thread gracefully
901 thread
->Exit(EXITCODE_CANCELLED
);
904 #endif // wxHAVE_PTHREAD_CLEANUP
906 // ----------------------------------------------------------------------------
908 // ----------------------------------------------------------------------------
910 wxThreadInternal::wxThreadInternal()
914 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
918 // set to true only when the thread starts waiting on m_semSuspend
921 // defaults for joinable threads
922 m_shouldBeJoined
= true;
923 m_isDetached
= false;
926 wxThreadInternal::~wxThreadInternal()
930 wxThreadError
wxThreadInternal::Run()
932 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
933 wxT("thread may only be started once after Create()") );
935 SetState(STATE_RUNNING
);
937 // wake up threads waiting for our start
940 return wxTHREAD_NO_ERROR
;
943 void wxThreadInternal::Wait()
945 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
947 // if the thread we're waiting for is waiting for the GUI mutex, we will
948 // deadlock so make sure we release it temporarily
949 if ( wxThread::IsMain() )
952 wxLogTrace(TRACE_THREADS
,
953 _T("Starting to wait for thread %ld to exit."),
956 // to avoid memory leaks we should call pthread_join(), but it must only be
957 // done once so use a critical section to serialize the code below
959 wxCriticalSectionLocker
lock(m_csJoinFlag
);
961 if ( m_shouldBeJoined
)
963 // FIXME shouldn't we set cancellation type to DISABLED here? If
964 // we're cancelled inside pthread_join(), things will almost
965 // certainly break - but if we disable the cancellation, we
967 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
969 // this is a serious problem, so use wxLogError and not
970 // wxLogDebug: it is possible to bring the system to its knees
971 // by creating too many threads and not joining them quite
973 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
976 m_shouldBeJoined
= false;
980 // reacquire GUI mutex
981 if ( wxThread::IsMain() )
985 void wxThreadInternal::Pause()
987 // the state is set from the thread which pauses us first, this function
988 // is called later so the state should have been already set
989 wxCHECK_RET( m_state
== STATE_PAUSED
,
990 wxT("thread must first be paused with wxThread::Pause().") );
992 wxLogTrace(TRACE_THREADS
,
993 _T("Thread %ld goes to sleep."), THR_ID(this));
995 // wait until the semaphore is Post()ed from Resume()
999 void wxThreadInternal::Resume()
1001 wxCHECK_RET( m_state
== STATE_PAUSED
,
1002 wxT("can't resume thread which is not suspended.") );
1004 // the thread might be not actually paused yet - if there were no call to
1005 // TestDestroy() since the last call to Pause() for example
1006 if ( IsReallyPaused() )
1008 wxLogTrace(TRACE_THREADS
,
1009 _T("Waking up thread %ld"), THR_ID(this));
1012 m_semSuspend
.Post();
1015 SetReallyPaused(false);
1019 wxLogTrace(TRACE_THREADS
,
1020 _T("Thread %ld is not yet really paused"), THR_ID(this));
1023 SetState(STATE_RUNNING
);
1026 // -----------------------------------------------------------------------------
1027 // wxThread static functions
1028 // -----------------------------------------------------------------------------
1030 wxThread
*wxThread::This()
1032 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1035 bool wxThread::IsMain()
1037 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
1040 void wxThread::Yield()
1042 #ifdef HAVE_SCHED_YIELD
1047 void wxThread::Sleep(unsigned long milliseconds
)
1049 wxMilliSleep(milliseconds
);
1052 int wxThread::GetCPUCount()
1054 #if defined(_SC_NPROCESSORS_ONLN)
1055 // this works for Solaris and Linux 2.6
1056 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1061 #elif defined(__LINUX__) && wxUSE_FFILE
1062 // read from proc (can't use wxTextFile here because it's a special file:
1063 // it has 0 size but still can be read from)
1066 wxFFile
file(_T("/proc/cpuinfo"));
1067 if ( file
.IsOpened() )
1069 // slurp the whole file
1071 if ( file
.ReadAll(&s
) )
1073 // (ab)use Replace() to find the number of "processor: num" strings
1074 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1080 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1084 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1087 #endif // different ways to get number of CPUs
1093 // VMS is a 64 bit system and threads have 64 bit pointers.
1094 // FIXME: also needed for other systems????
1096 unsigned long long wxThread::GetCurrentId()
1098 return (unsigned long long)pthread_self();
1103 unsigned long wxThread::GetCurrentId()
1105 return (unsigned long)pthread_self();
1108 #endif // __VMS/!__VMS
1111 bool wxThread::SetConcurrency(size_t level
)
1113 #ifdef HAVE_THR_SETCONCURRENCY
1114 int rc
= thr_setconcurrency(level
);
1117 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1121 #else // !HAVE_THR_SETCONCURRENCY
1122 // ok only for the default value
1124 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1127 // -----------------------------------------------------------------------------
1129 // -----------------------------------------------------------------------------
1131 wxThread::wxThread(wxThreadKind kind
)
1133 // add this thread to the global list of all threads
1135 wxMutexLocker
lock(*gs_mutexAllThreads
);
1137 gs_allThreads
.Add(this);
1140 m_internal
= new wxThreadInternal();
1142 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1145 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1146 #define WXUNUSED_STACKSIZE(identifier) identifier
1148 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1151 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1153 if ( m_internal
->GetState() != STATE_NEW
)
1155 // don't recreate thread
1156 return wxTHREAD_RUNNING
;
1159 // set up the thread attribute: right now, we only set thread priority
1160 pthread_attr_t attr
;
1161 pthread_attr_init(&attr
);
1163 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1165 pthread_attr_setstacksize(&attr
, stackSize
);
1168 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1170 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1172 wxLogError(_("Cannot retrieve thread scheduling policy."));
1176 /* the pthread.h contains too many spaces. This is a work-around */
1177 # undef sched_get_priority_max
1178 #undef sched_get_priority_min
1179 #define sched_get_priority_max(_pol_) \
1180 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1181 #define sched_get_priority_min(_pol_) \
1182 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1185 int max_prio
= sched_get_priority_max(policy
),
1186 min_prio
= sched_get_priority_min(policy
),
1187 prio
= m_internal
->GetPriority();
1189 if ( min_prio
== -1 || max_prio
== -1 )
1191 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1194 else if ( max_prio
== min_prio
)
1196 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1198 // notify the programmer that this doesn't work here
1199 wxLogWarning(_("Thread priority setting is ignored."));
1201 //else: we have default priority, so don't complain
1203 // anyhow, don't do anything because priority is just ignored
1207 struct sched_param sp
;
1208 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1210 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1213 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1215 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1217 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1220 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1222 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1223 // this will make the threads created by this process really concurrent
1224 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1226 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1228 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1230 // VZ: assume that this one is always available (it's rather fundamental),
1231 // if this function is ever missing we should try to use
1232 // pthread_detach() instead (after thread creation)
1235 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1237 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1240 // never try to join detached threads
1241 m_internal
->Detach();
1243 //else: threads are created joinable by default, it's ok
1245 // create the new OS thread object
1246 int rc
= pthread_create
1248 m_internal
->GetIdPtr(),
1254 if ( pthread_attr_destroy(&attr
) != 0 )
1256 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1261 m_internal
->SetState(STATE_EXITED
);
1263 return wxTHREAD_NO_RESOURCE
;
1266 return wxTHREAD_NO_ERROR
;
1269 wxThreadError
wxThread::Run()
1271 wxCriticalSectionLocker
lock(m_critsect
);
1273 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1274 wxT("must call wxThread::Create() first") );
1276 return m_internal
->Run();
1279 // -----------------------------------------------------------------------------
1281 // -----------------------------------------------------------------------------
1283 void wxThread::SetPriority(unsigned int prio
)
1285 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1286 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1287 wxT("invalid thread priority") );
1289 wxCriticalSectionLocker
lock(m_critsect
);
1291 switch ( m_internal
->GetState() )
1294 // thread not yet started, priority will be set when it is
1295 m_internal
->SetPriority(prio
);
1300 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1301 #if defined(__LINUX__)
1302 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1303 // a priority other than 0. Instead, we use the BSD setpriority
1304 // which alllows us to set a 'nice' value between 20 to -20. Only
1305 // super user can set a value less than zero (more negative yields
1306 // higher priority). setpriority set the static priority of a
1307 // process, but this is OK since Linux is configured as a thread
1310 // FIXME this is not true for 2.6!!
1312 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1313 // to Unix priorities 20..-20
1314 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1316 wxLogError(_("Failed to set thread priority %d."), prio
);
1320 struct sched_param sparam
;
1321 sparam
.sched_priority
= prio
;
1323 if ( pthread_setschedparam(m_internal
->GetId(),
1324 SCHED_OTHER
, &sparam
) != 0 )
1326 wxLogError(_("Failed to set thread priority %d."), prio
);
1330 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1335 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1339 unsigned int wxThread::GetPriority() const
1341 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1343 return m_internal
->GetPriority();
1346 wxThreadIdType
wxThread::GetId() const
1348 return (wxThreadIdType
) m_internal
->GetId();
1351 // -----------------------------------------------------------------------------
1353 // -----------------------------------------------------------------------------
1355 wxThreadError
wxThread::Pause()
1357 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1358 _T("a thread can't pause itself") );
1360 wxCriticalSectionLocker
lock(m_critsect
);
1362 if ( m_internal
->GetState() != STATE_RUNNING
)
1364 wxLogDebug(wxT("Can't pause thread which is not running."));
1366 return wxTHREAD_NOT_RUNNING
;
1369 // just set a flag, the thread will be really paused only during the next
1370 // call to TestDestroy()
1371 m_internal
->SetState(STATE_PAUSED
);
1373 return wxTHREAD_NO_ERROR
;
1376 wxThreadError
wxThread::Resume()
1378 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1379 _T("a thread can't resume itself") );
1381 wxCriticalSectionLocker
lock(m_critsect
);
1383 wxThreadState state
= m_internal
->GetState();
1388 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1391 m_internal
->Resume();
1393 return wxTHREAD_NO_ERROR
;
1396 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1398 return wxTHREAD_NO_ERROR
;
1401 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1403 return wxTHREAD_MISC_ERROR
;
1407 // -----------------------------------------------------------------------------
1409 // -----------------------------------------------------------------------------
1411 wxThread::ExitCode
wxThread::Wait()
1413 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1414 _T("a thread can't wait for itself") );
1416 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1417 _T("can't wait for detached thread") );
1421 return m_internal
->GetExitCode();
1424 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1426 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1427 _T("a thread can't delete itself") );
1429 bool isDetached
= m_isDetached
;
1432 wxThreadState state
= m_internal
->GetState();
1434 // ask the thread to stop
1435 m_internal
->SetCancelFlag();
1442 // we need to wake up the thread so that PthreadStart() will
1443 // terminate - right now it's blocking on run semaphore in
1445 m_internal
->SignalRun();
1454 // resume the thread first
1455 m_internal
->Resume();
1462 // wait until the thread stops
1467 // return the exit code of the thread
1468 *rc
= m_internal
->GetExitCode();
1471 //else: can't wait for detached threads
1474 return wxTHREAD_NO_ERROR
;
1477 wxThreadError
wxThread::Kill()
1479 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1480 _T("a thread can't kill itself") );
1482 switch ( m_internal
->GetState() )
1486 return wxTHREAD_NOT_RUNNING
;
1489 // resume the thread first
1495 #ifdef HAVE_PTHREAD_CANCEL
1496 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1497 #endif // HAVE_PTHREAD_CANCEL
1499 wxLogError(_("Failed to terminate a thread."));
1501 return wxTHREAD_MISC_ERROR
;
1504 #ifdef HAVE_PTHREAD_CANCEL
1507 // if we use cleanup function, this will be done from
1508 // wxPthreadCleanup()
1509 #ifndef wxHAVE_PTHREAD_CLEANUP
1510 ScheduleThreadForDeletion();
1512 // don't call OnExit() here, it can only be called in the
1513 // threads context and we're in the context of another thread
1516 #endif // wxHAVE_PTHREAD_CLEANUP
1520 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1523 return wxTHREAD_NO_ERROR
;
1524 #endif // HAVE_PTHREAD_CANCEL
1528 void wxThread::Exit(ExitCode status
)
1530 wxASSERT_MSG( This() == this,
1531 _T("wxThread::Exit() can only be called in the context of the same thread") );
1535 // from the moment we call OnExit(), the main program may terminate at
1536 // any moment, so mark this thread as being already in process of being
1537 // deleted or wxThreadModule::OnExit() will try to delete it again
1538 ScheduleThreadForDeletion();
1541 // don't enter m_critsect before calling OnExit() because the user code
1542 // might deadlock if, for example, it signals a condition in OnExit() (a
1543 // common case) while the main thread calls any of functions entering
1544 // m_critsect on us (almost all of them do)
1547 // delete C++ thread object if this is a detached thread - user is
1548 // responsible for doing this for joinable ones
1551 // FIXME I'm feeling bad about it - what if another thread function is
1552 // called (in another thread context) now? It will try to access
1553 // half destroyed object which will probably result in something
1554 // very bad - but we can't protect this by a crit section unless
1555 // we make it a global object, but this would mean that we can
1556 // only call one thread function at a time :-(
1558 pthread_setspecific(gs_keySelf
, 0);
1563 m_internal
->SetState(STATE_EXITED
);
1567 // terminate the thread (pthread_exit() never returns)
1568 pthread_exit(status
);
1570 wxFAIL_MSG(_T("pthread_exit() failed"));
1573 // also test whether we were paused
1574 bool wxThread::TestDestroy()
1576 wxASSERT_MSG( This() == this,
1577 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1581 if ( m_internal
->GetState() == STATE_PAUSED
)
1583 m_internal
->SetReallyPaused(true);
1585 // leave the crit section or the other threads will stop too if they
1586 // try to call any of (seemingly harmless) IsXXX() functions while we
1590 m_internal
->Pause();
1594 // thread wasn't requested to pause, nothing to do
1598 return m_internal
->WasCancelled();
1601 wxThread::~wxThread()
1606 // check that the thread either exited or couldn't be created
1607 if ( m_internal
->GetState() != STATE_EXITED
&&
1608 m_internal
->GetState() != STATE_NEW
)
1610 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1615 #endif // __WXDEBUG__
1619 // remove this thread from the global array
1621 wxMutexLocker
lock(*gs_mutexAllThreads
);
1623 gs_allThreads
.Remove(this);
1627 // -----------------------------------------------------------------------------
1629 // -----------------------------------------------------------------------------
1631 bool wxThread::IsRunning() const
1633 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1635 return m_internal
->GetState() == STATE_RUNNING
;
1638 bool wxThread::IsAlive() const
1640 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1642 switch ( m_internal
->GetState() )
1653 bool wxThread::IsPaused() const
1655 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1657 return (m_internal
->GetState() == STATE_PAUSED
);
1660 //--------------------------------------------------------------------
1662 //--------------------------------------------------------------------
1664 class wxThreadModule
: public wxModule
1667 virtual bool OnInit();
1668 virtual void OnExit();
1671 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1674 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1676 bool wxThreadModule::OnInit()
1678 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1681 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1686 gs_tidMain
= pthread_self();
1688 gs_mutexAllThreads
= new wxMutex();
1690 gs_mutexGui
= new wxMutex();
1691 gs_mutexGui
->Lock();
1693 gs_mutexDeleteThread
= new wxMutex();
1694 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1699 void wxThreadModule::OnExit()
1701 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1703 // are there any threads left which are being deleted right now?
1704 size_t nThreadsBeingDeleted
;
1707 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1708 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1710 if ( nThreadsBeingDeleted
> 0 )
1712 wxLogTrace(TRACE_THREADS
,
1713 _T("Waiting for %lu threads to disappear"),
1714 (unsigned long)nThreadsBeingDeleted
);
1716 // have to wait until all of them disappear
1717 gs_condAllDeleted
->Wait();
1724 wxMutexLocker
lock(*gs_mutexAllThreads
);
1726 // terminate any threads left
1727 count
= gs_allThreads
.GetCount();
1730 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1731 (unsigned long)count
);
1733 } // unlock mutex before deleting the threads as they lock it in their dtor
1735 for ( size_t n
= 0u; n
< count
; n
++ )
1737 // Delete calls the destructor which removes the current entry. We
1738 // should only delete the first one each time.
1739 gs_allThreads
[0]->Delete();
1742 delete gs_mutexAllThreads
;
1744 // destroy GUI mutex
1745 gs_mutexGui
->Unlock();
1748 // and free TLD slot
1749 (void)pthread_key_delete(gs_keySelf
);
1751 delete gs_condAllDeleted
;
1752 delete gs_mutexDeleteThread
;
1755 // ----------------------------------------------------------------------------
1757 // ----------------------------------------------------------------------------
1759 static void ScheduleThreadForDeletion()
1761 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1763 gs_nThreadsBeingDeleted
++;
1765 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1766 (unsigned long)gs_nThreadsBeingDeleted
,
1767 gs_nThreadsBeingDeleted
== 1 ? _T("") : _T("s"));
1770 static void DeleteThread(wxThread
*This
)
1772 // gs_mutexDeleteThread should be unlocked before signalling the condition
1773 // or wxThreadModule::OnExit() would deadlock
1774 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1776 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1780 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1781 _T("no threads scheduled for deletion, yet we delete one?") );
1783 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1784 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1786 if ( !--gs_nThreadsBeingDeleted
)
1788 // no more threads left, signal it
1789 gs_condAllDeleted
->Signal();
1793 void wxMutexGuiEnter()
1795 gs_mutexGui
->Lock();
1798 void wxMutexGuiLeave()
1800 gs_mutexGui
->Unlock();
1803 // ----------------------------------------------------------------------------
1804 // include common implementation code
1805 // ----------------------------------------------------------------------------
1807 #include "wx/thrimpl.cpp"
1809 #endif // wxUSE_THREADS