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"
48 #include <sys/time.h> // needed for at least __QNX__
53 #ifdef HAVE_THR_SETCONCURRENCY
57 // we use wxFFile under Linux in GetCPUCount()
60 #include <sys/resource.h> // for setpriority()
63 #define THR_ID_CAST(id) (reinterpret_cast<void*>(id))
64 #define THR_ID(thr) THR_ID_CAST((thr)->GetId())
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
70 // the possible states of the thread and transitions from them
73 STATE_NEW
, // didn't start execution yet (=> RUNNING)
74 STATE_RUNNING
, // running (=> PAUSED or EXITED)
75 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
76 STATE_EXITED
// thread doesn't exist any more
79 // the exit value of a thread which has been cancelled
80 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
82 // trace mask for wxThread operations
83 #define TRACE_THREADS wxT("thread")
85 // you can get additional debugging messages for the semaphore operations
86 #define TRACE_SEMA wxT("semaphore")
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 static void ScheduleThreadForDeletion();
93 static void DeleteThread(wxThread
*This
);
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
99 // an (non owning) array of pointers to threads
100 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
102 // an entry for a thread we can wait for
104 // -----------------------------------------------------------------------------
106 // -----------------------------------------------------------------------------
108 // we keep the list of all threads created by the application to be able to
109 // terminate them on exit if there are some left - otherwise the process would
111 static wxArrayThread gs_allThreads
;
113 // a mutex to protect gs_allThreads
114 static wxMutex
*gs_mutexAllThreads
= NULL
;
116 // the id of the main thread
118 // we suppose that 0 is not a valid pthread_t value but in principle this might
119 // be false (e.g. if it's a selector-like value), wxThread::IsMain() would need
120 // to be updated in such case
121 wxThreadIdType
wxThread::ms_idMainThread
= 0;
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
= NULL
;
133 // and a condition variable which will be signaled when all
134 // gs_nThreadsBeingDeleted will have been deleted
135 static wxCondition
*gs_condAllDeleted
= 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 unsigned long m_owningThread
;
184 // wxConditionInternal uses our m_mutex
185 friend class wxConditionInternal
;
188 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
189 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
190 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
191 // in the library, otherwise we wouldn't compile this code at all)
192 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
195 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
203 case wxMUTEX_RECURSIVE
:
204 // support recursive locks like Win32, i.e. a thread can lock a
205 // mutex which it had itself already locked
207 // unfortunately initialization of recursive mutexes is non
208 // portable, so try several methods
209 #ifdef HAVE_PTHREAD_MUTEXATTR_T
211 pthread_mutexattr_t attr
;
212 pthread_mutexattr_init(&attr
);
213 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
215 err
= pthread_mutex_init(&m_mutex
, &attr
);
217 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
218 // we can use this only as initializer so we have to assign it
219 // first to a temp var - assigning directly to m_mutex wouldn't
222 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
225 #else // no recursive mutexes
227 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
231 wxFAIL_MSG( wxT("unknown mutex type") );
234 case wxMUTEX_DEFAULT
:
235 err
= pthread_mutex_init(&m_mutex
, NULL
);
242 wxLogApiError( wxT("pthread_mutex_init()"), err
);
246 wxMutexInternal::~wxMutexInternal()
250 int err
= pthread_mutex_destroy(&m_mutex
);
253 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
258 wxMutexError
wxMutexInternal::Lock()
260 if ((m_type
== wxMUTEX_DEFAULT
) && (m_owningThread
!= 0))
262 if (m_owningThread
== wxThread::GetCurrentId())
263 return wxMUTEX_DEAD_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
)
321 // wxPrintf( "err %d\n", err );
326 // only error checking mutexes return this value and so it's an
327 // unexpected situation -- hence use assert, not wxLogDebug
328 wxFAIL_MSG( wxT("mutex deadlock prevented") );
329 return wxMUTEX_DEAD_LOCK
;
332 wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized"));
336 return wxMUTEX_TIMEOUT
;
339 if (m_type
== wxMUTEX_DEFAULT
)
340 m_owningThread
= wxThread::GetCurrentId();
341 return wxMUTEX_NO_ERROR
;
344 wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err
);
347 return wxMUTEX_MISC_ERROR
;
351 wxMutexError
wxMutexInternal::TryLock()
353 int err
= pthread_mutex_trylock(&m_mutex
);
357 // not an error: mutex is already locked, but we're prepared for
362 wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized."));
366 if (m_type
== wxMUTEX_DEFAULT
)
367 m_owningThread
= wxThread::GetCurrentId();
368 return wxMUTEX_NO_ERROR
;
371 wxLogApiError(wxT("pthread_mutex_trylock()"), err
);
374 return wxMUTEX_MISC_ERROR
;
377 wxMutexError
wxMutexInternal::Unlock()
381 int err
= pthread_mutex_unlock(&m_mutex
);
385 // we don't own the mutex
386 return wxMUTEX_UNLOCKED
;
389 wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized."));
393 return wxMUTEX_NO_ERROR
;
396 wxLogApiError(wxT("pthread_mutex_unlock()"), err
);
399 return wxMUTEX_MISC_ERROR
;
402 // ===========================================================================
403 // wxCondition implementation
404 // ===========================================================================
406 // ---------------------------------------------------------------------------
407 // wxConditionInternal
408 // ---------------------------------------------------------------------------
410 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
411 // with a pthread_mutex_t)
412 class wxConditionInternal
415 wxConditionInternal(wxMutex
& mutex
);
416 ~wxConditionInternal();
418 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
421 wxCondError
WaitTimeout(unsigned long milliseconds
);
423 wxCondError
Signal();
424 wxCondError
Broadcast();
427 // get the POSIX mutex associated with us
428 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
431 pthread_cond_t m_cond
;
436 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
439 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
445 wxLogApiError(wxT("pthread_cond_init()"), err
);
449 wxConditionInternal::~wxConditionInternal()
453 int err
= pthread_cond_destroy(&m_cond
);
456 wxLogApiError(wxT("pthread_cond_destroy()"), err
);
461 wxCondError
wxConditionInternal::Wait()
463 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
466 wxLogApiError(wxT("pthread_cond_wait()"), err
);
468 return wxCOND_MISC_ERROR
;
471 return wxCOND_NO_ERROR
;
474 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
476 wxLongLong curtime
= wxGetLocalTimeMillis();
477 curtime
+= milliseconds
;
478 wxLongLong temp
= curtime
/ 1000;
479 int sec
= temp
.GetLo();
481 temp
= curtime
- temp
;
482 int millis
= temp
.GetLo();
487 tspec
.tv_nsec
= millis
* 1000L * 1000L;
489 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
493 return wxCOND_TIMEOUT
;
496 return wxCOND_NO_ERROR
;
499 wxLogApiError(wxT("pthread_cond_timedwait()"), err
);
502 return wxCOND_MISC_ERROR
;
505 wxCondError
wxConditionInternal::Signal()
507 int err
= pthread_cond_signal(&m_cond
);
510 wxLogApiError(wxT("pthread_cond_signal()"), err
);
512 return wxCOND_MISC_ERROR
;
515 return wxCOND_NO_ERROR
;
518 wxCondError
wxConditionInternal::Broadcast()
520 int err
= pthread_cond_broadcast(&m_cond
);
523 wxLogApiError(wxT("pthread_cond_broadcast()"), err
);
525 return wxCOND_MISC_ERROR
;
528 return wxCOND_NO_ERROR
;
531 // ===========================================================================
532 // wxSemaphore implementation
533 // ===========================================================================
535 // ---------------------------------------------------------------------------
536 // wxSemaphoreInternal
537 // ---------------------------------------------------------------------------
539 // we implement the semaphores using mutexes and conditions instead of using
540 // the sem_xxx() POSIX functions because they're not widely available and also
541 // because it's impossible to implement WaitTimeout() using them
542 class wxSemaphoreInternal
545 wxSemaphoreInternal(int initialcount
, int maxcount
);
547 bool IsOk() const { return m_isOk
; }
550 wxSemaError
TryWait();
551 wxSemaError
WaitTimeout(unsigned long milliseconds
);
565 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
569 if ( (initialcount
< 0 || maxcount
< 0) ||
570 ((maxcount
> 0) && (initialcount
> maxcount
)) )
572 wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") );
578 m_maxcount
= (size_t)maxcount
;
579 m_count
= (size_t)initialcount
;
582 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
585 wxSemaError
wxSemaphoreInternal::Wait()
587 wxMutexLocker
locker(m_mutex
);
589 while ( m_count
== 0 )
591 wxLogTrace(TRACE_SEMA
,
592 wxT("Thread %p waiting for semaphore to become signalled"),
593 THR_ID_CAST(wxThread::GetCurrentId()));
595 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
596 return wxSEMA_MISC_ERROR
;
598 wxLogTrace(TRACE_SEMA
,
599 wxT("Thread %p finished waiting for semaphore, count = %lu"),
600 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
605 return wxSEMA_NO_ERROR
;
608 wxSemaError
wxSemaphoreInternal::TryWait()
610 wxMutexLocker
locker(m_mutex
);
617 return wxSEMA_NO_ERROR
;
620 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
622 wxMutexLocker
locker(m_mutex
);
624 wxLongLong startTime
= wxGetLocalTimeMillis();
626 while ( m_count
== 0 )
628 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
629 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
630 if ( remainingTime
<= 0 )
633 return wxSEMA_TIMEOUT
;
636 switch ( m_cond
.WaitTimeout(remainingTime
) )
639 return wxSEMA_TIMEOUT
;
642 return wxSEMA_MISC_ERROR
;
644 case wxCOND_NO_ERROR
:
651 return wxSEMA_NO_ERROR
;
654 wxSemaError
wxSemaphoreInternal::Post()
656 wxMutexLocker
locker(m_mutex
);
658 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
660 return wxSEMA_OVERFLOW
;
665 wxLogTrace(TRACE_SEMA
,
666 wxT("Thread %p about to signal semaphore, count = %lu"),
667 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
669 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
673 // ===========================================================================
674 // wxThread implementation
675 // ===========================================================================
677 // the thread callback functions must have the C linkage
681 #ifdef wxHAVE_PTHREAD_CLEANUP
682 // thread exit function
683 void wxPthreadCleanup(void *ptr
);
684 #endif // wxHAVE_PTHREAD_CLEANUP
686 void *wxPthreadStart(void *ptr
);
690 // ----------------------------------------------------------------------------
692 // ----------------------------------------------------------------------------
694 class wxThreadInternal
700 // thread entry function
701 static void *PthreadStart(wxThread
*thread
);
706 // unblock the thread allowing it to run
707 void SignalRun() { m_semRun
.Post(); }
708 // ask the thread to terminate
710 // go to sleep until Resume() is called
717 int GetPriority() const { return m_prio
; }
718 void SetPriority(int prio
) { m_prio
= prio
; }
720 wxThreadState
GetState() const { return m_state
; }
721 void SetState(wxThreadState state
)
724 static const wxChar
*const stateNames
[] =
732 wxLogTrace(TRACE_THREADS
, wxT("Thread %p: %s => %s."),
733 THR_ID(this), stateNames
[m_state
], stateNames
[state
]);
734 #endif // wxUSE_LOG_TRACE
739 pthread_t
GetId() const { return m_threadId
; }
740 pthread_t
*GetIdPtr() { return &m_threadId
; }
742 void SetCancelFlag() { m_cancelled
= true; }
743 bool WasCancelled() const { return m_cancelled
; }
745 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
746 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
749 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
750 bool IsReallyPaused() const { return m_isPaused
; }
752 // tell the thread that it is a detached one
755 wxCriticalSectionLocker
lock(m_csJoinFlag
);
757 m_shouldBeJoined
= false;
761 #ifdef wxHAVE_PTHREAD_CLEANUP
762 // this is used by wxPthreadCleanup() only
763 static void Cleanup(wxThread
*thread
);
764 #endif // wxHAVE_PTHREAD_CLEANUP
767 pthread_t m_threadId
; // id of the thread
768 wxThreadState m_state
; // see wxThreadState enum
769 int m_prio
; // in wxWidgets units: from 0 to 100
771 // this flag is set when the thread should terminate
774 // this flag is set when the thread is blocking on m_semSuspend
777 // the thread exit code - only used for joinable (!detached) threads and
778 // is only valid after the thread termination
779 wxThread::ExitCode m_exitcode
;
781 // many threads may call Wait(), but only one of them should call
782 // pthread_join(), so we have to keep track of this
783 wxCriticalSection m_csJoinFlag
;
784 bool m_shouldBeJoined
;
787 // this semaphore is posted by Run() and the threads Entry() is not
788 // called before it is done
789 wxSemaphore m_semRun
;
791 // this one is signaled when the thread should resume after having been
793 wxSemaphore m_semSuspend
;
796 // ----------------------------------------------------------------------------
797 // thread startup and exit functions
798 // ----------------------------------------------------------------------------
800 void *wxPthreadStart(void *ptr
)
802 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
805 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
807 wxThreadInternal
*pthread
= thread
->m_internal
;
809 wxLogTrace(TRACE_THREADS
, wxT("Thread %p started."), THR_ID(pthread
));
811 // associate the thread pointer with the newly created thread so that
812 // wxThread::This() will work
813 int rc
= pthread_setspecific(gs_keySelf
, thread
);
816 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
821 // have to declare this before pthread_cleanup_push() which defines a
825 #ifdef wxHAVE_PTHREAD_CLEANUP
826 // install the cleanup handler which will be called if the thread is
828 pthread_cleanup_push(wxPthreadCleanup
, thread
);
829 #endif // wxHAVE_PTHREAD_CLEANUP
831 // wait for the semaphore to be posted from Run()
832 pthread
->m_semRun
.Wait();
834 // test whether we should run the run at all - may be it was deleted
835 // before it started to Run()?
837 wxCriticalSectionLocker
lock(thread
->m_critsect
);
839 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
840 pthread
->WasCancelled();
845 // call the main entry
846 wxLogTrace(TRACE_THREADS
,
847 wxT("Thread %p about to enter its Entry()."),
852 pthread
->m_exitcode
= thread
->Entry();
854 wxLogTrace(TRACE_THREADS
,
855 wxT("Thread %p Entry() returned %lu."),
856 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
858 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
861 wxCriticalSectionLocker
lock(thread
->m_critsect
);
863 // change the state of the thread to "exited" so that
864 // wxPthreadCleanup handler won't do anything from now (if it's
865 // called before we do pthread_cleanup_pop below)
866 pthread
->SetState(STATE_EXITED
);
870 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
871 // '}' for the '{' in push, so they must be used in the same block!
872 #ifdef wxHAVE_PTHREAD_CLEANUP
874 // under Tru64 we get a warning from macro expansion
876 #pragma message disable(declbutnotref)
879 // remove the cleanup handler without executing it
880 pthread_cleanup_pop(FALSE
);
883 #pragma message restore
885 #endif // wxHAVE_PTHREAD_CLEANUP
889 // FIXME: deleting a possibly joinable thread here???
892 return EXITCODE_CANCELLED
;
896 // terminate the thread
897 thread
->Exit(pthread
->m_exitcode
);
899 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
905 #ifdef wxHAVE_PTHREAD_CLEANUP
907 // this handler is called when the thread is cancelled
908 extern "C" void wxPthreadCleanup(void *ptr
)
910 wxThreadInternal::Cleanup((wxThread
*)ptr
);
913 void wxThreadInternal::Cleanup(wxThread
*thread
)
915 if (pthread_getspecific(gs_keySelf
) == 0) return;
917 wxCriticalSectionLocker
lock(thread
->m_critsect
);
918 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
920 // thread is already considered as finished.
925 // exit the thread gracefully
926 thread
->Exit(EXITCODE_CANCELLED
);
929 #endif // wxHAVE_PTHREAD_CLEANUP
931 // ----------------------------------------------------------------------------
933 // ----------------------------------------------------------------------------
935 wxThreadInternal::wxThreadInternal()
939 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
943 // set to true only when the thread starts waiting on m_semSuspend
946 // defaults for joinable threads
947 m_shouldBeJoined
= true;
948 m_isDetached
= false;
951 wxThreadInternal::~wxThreadInternal()
955 wxThreadError
wxThreadInternal::Run()
957 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
958 wxT("thread may only be started once after Create()") );
960 SetState(STATE_RUNNING
);
962 // wake up threads waiting for our start
965 return wxTHREAD_NO_ERROR
;
968 void wxThreadInternal::Wait()
970 wxCHECK_RET( !m_isDetached
, wxT("can't wait for a detached thread") );
972 // if the thread we're waiting for is waiting for the GUI mutex, we will
973 // deadlock so make sure we release it temporarily
974 if ( wxThread::IsMain() )
977 wxLogTrace(TRACE_THREADS
,
978 wxT("Starting to wait for thread %p to exit."),
981 // to avoid memory leaks we should call pthread_join(), but it must only be
982 // done once so use a critical section to serialize the code below
984 wxCriticalSectionLocker
lock(m_csJoinFlag
);
986 if ( m_shouldBeJoined
)
988 // FIXME shouldn't we set cancellation type to DISABLED here? If
989 // we're cancelled inside pthread_join(), things will almost
990 // certainly break - but if we disable the cancellation, we
992 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
994 // this is a serious problem, so use wxLogError and not
995 // wxLogDebug: it is possible to bring the system to its knees
996 // by creating too many threads and not joining them quite
998 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
1001 m_shouldBeJoined
= false;
1005 // reacquire GUI mutex
1006 if ( wxThread::IsMain() )
1010 void wxThreadInternal::Pause()
1012 // the state is set from the thread which pauses us first, this function
1013 // is called later so the state should have been already set
1014 wxCHECK_RET( m_state
== STATE_PAUSED
,
1015 wxT("thread must first be paused with wxThread::Pause().") );
1017 wxLogTrace(TRACE_THREADS
,
1018 wxT("Thread %p goes to sleep."), THR_ID(this));
1020 // wait until the semaphore is Post()ed from Resume()
1021 m_semSuspend
.Wait();
1024 void wxThreadInternal::Resume()
1026 wxCHECK_RET( m_state
== STATE_PAUSED
,
1027 wxT("can't resume thread which is not suspended.") );
1029 // the thread might be not actually paused yet - if there were no call to
1030 // TestDestroy() since the last call to Pause() for example
1031 if ( IsReallyPaused() )
1033 wxLogTrace(TRACE_THREADS
,
1034 wxT("Waking up thread %p"), THR_ID(this));
1037 m_semSuspend
.Post();
1040 SetReallyPaused(false);
1044 wxLogTrace(TRACE_THREADS
,
1045 wxT("Thread %p is not yet really paused"), THR_ID(this));
1048 SetState(STATE_RUNNING
);
1051 // -----------------------------------------------------------------------------
1052 // wxThread static functions
1053 // -----------------------------------------------------------------------------
1055 wxThread
*wxThread::This()
1057 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1060 void wxThread::Yield()
1062 #ifdef HAVE_SCHED_YIELD
1067 int wxThread::GetCPUCount()
1069 #if defined(_SC_NPROCESSORS_ONLN)
1070 // this works for Solaris and Linux 2.6
1071 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1076 #elif defined(__LINUX__) && wxUSE_FFILE
1077 // read from proc (can't use wxTextFile here because it's a special file:
1078 // it has 0 size but still can be read from)
1081 wxFFile
file(wxT("/proc/cpuinfo"));
1082 if ( file
.IsOpened() )
1084 // slurp the whole file
1086 if ( file
.ReadAll(&s
) )
1088 // (ab)use Replace() to find the number of "processor: num" strings
1089 size_t count
= s
.Replace(wxT("processor\t:"), wxT(""));
1095 wxLogDebug(wxT("failed to parse /proc/cpuinfo"));
1099 wxLogDebug(wxT("failed to read /proc/cpuinfo"));
1102 #endif // different ways to get number of CPUs
1108 wxThreadIdType
wxThread::GetCurrentId()
1110 return (wxThreadIdType
)pthread_self();
1114 bool wxThread::SetConcurrency(size_t level
)
1116 #ifdef HAVE_THR_SETCONCURRENCY
1117 int rc
= thr_setconcurrency(level
);
1120 wxLogSysError(rc
, wxT("thr_setconcurrency() failed"));
1124 #else // !HAVE_THR_SETCONCURRENCY
1125 // ok only for the default value
1127 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1130 // -----------------------------------------------------------------------------
1132 // -----------------------------------------------------------------------------
1134 wxThread::wxThread(wxThreadKind kind
)
1136 // add this thread to the global list of all threads
1138 wxMutexLocker
lock(*gs_mutexAllThreads
);
1140 gs_allThreads
.Add(this);
1143 m_internal
= new wxThreadInternal();
1145 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1148 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1149 #define WXUNUSED_STACKSIZE(identifier) identifier
1151 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1154 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1156 if ( m_internal
->GetState() != STATE_NEW
)
1158 // don't recreate thread
1159 return wxTHREAD_RUNNING
;
1162 // set up the thread attribute: right now, we only set thread priority
1163 pthread_attr_t attr
;
1164 pthread_attr_init(&attr
);
1166 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1168 pthread_attr_setstacksize(&attr
, stackSize
);
1171 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1173 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1175 wxLogError(_("Cannot retrieve thread scheduling policy."));
1179 /* the pthread.h contains too many spaces. This is a work-around */
1180 # undef sched_get_priority_max
1181 #undef sched_get_priority_min
1182 #define sched_get_priority_max(_pol_) \
1183 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1184 #define sched_get_priority_min(_pol_) \
1185 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1188 int max_prio
= sched_get_priority_max(policy
),
1189 min_prio
= sched_get_priority_min(policy
),
1190 prio
= m_internal
->GetPriority();
1192 if ( min_prio
== -1 || max_prio
== -1 )
1194 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1197 else if ( max_prio
== min_prio
)
1199 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1201 // notify the programmer that this doesn't work here
1202 wxLogWarning(_("Thread priority setting is ignored."));
1204 //else: we have default priority, so don't complain
1206 // anyhow, don't do anything because priority is just ignored
1210 struct sched_param sp
;
1211 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1213 wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed"));
1216 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1218 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1220 wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed"));
1223 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1225 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1226 // this will make the threads created by this process really concurrent
1227 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1229 wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1231 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1233 // VZ: assume that this one is always available (it's rather fundamental),
1234 // if this function is ever missing we should try to use
1235 // pthread_detach() instead (after thread creation)
1238 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1240 wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed"));
1243 // never try to join detached threads
1244 m_internal
->Detach();
1246 //else: threads are created joinable by default, it's ok
1248 // create the new OS thread object
1249 int rc
= pthread_create
1251 m_internal
->GetIdPtr(),
1257 if ( pthread_attr_destroy(&attr
) != 0 )
1259 wxFAIL_MSG(wxT("pthread_attr_destroy() failed"));
1264 m_internal
->SetState(STATE_EXITED
);
1266 return wxTHREAD_NO_RESOURCE
;
1269 return wxTHREAD_NO_ERROR
;
1272 wxThreadError
wxThread::Run()
1274 wxCriticalSectionLocker
lock(m_critsect
);
1276 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1277 wxT("must call wxThread::Create() first") );
1279 return m_internal
->Run();
1282 // -----------------------------------------------------------------------------
1284 // -----------------------------------------------------------------------------
1286 void wxThread::SetPriority(unsigned int prio
)
1288 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1289 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1290 wxT("invalid thread priority") );
1292 wxCriticalSectionLocker
lock(m_critsect
);
1294 switch ( m_internal
->GetState() )
1297 // thread not yet started, priority will be set when it is
1298 m_internal
->SetPriority(prio
);
1303 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1304 #if defined(__LINUX__)
1305 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1306 // a priority other than 0. Instead, we use the BSD setpriority
1307 // which alllows us to set a 'nice' value between 20 to -20. Only
1308 // super user can set a value less than zero (more negative yields
1309 // higher priority). setpriority set the static priority of a
1310 // process, but this is OK since Linux is configured as a thread
1313 // FIXME this is not true for 2.6!!
1315 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1316 // to Unix priorities 20..-20
1317 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1319 wxLogError(_("Failed to set thread priority %d."), prio
);
1323 struct sched_param sparam
;
1324 sparam
.sched_priority
= prio
;
1326 if ( pthread_setschedparam(m_internal
->GetId(),
1327 SCHED_OTHER
, &sparam
) != 0 )
1329 wxLogError(_("Failed to set thread priority %d."), prio
);
1333 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1338 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1342 unsigned int wxThread::GetPriority() const
1344 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1346 return m_internal
->GetPriority();
1349 wxThreadIdType
wxThread::GetId() const
1351 return (wxThreadIdType
) m_internal
->GetId();
1354 // -----------------------------------------------------------------------------
1356 // -----------------------------------------------------------------------------
1358 wxThreadError
wxThread::Pause()
1360 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1361 wxT("a thread can't pause itself") );
1363 wxCriticalSectionLocker
lock(m_critsect
);
1365 if ( m_internal
->GetState() != STATE_RUNNING
)
1367 wxLogDebug(wxT("Can't pause thread which is not running."));
1369 return wxTHREAD_NOT_RUNNING
;
1372 // just set a flag, the thread will be really paused only during the next
1373 // call to TestDestroy()
1374 m_internal
->SetState(STATE_PAUSED
);
1376 return wxTHREAD_NO_ERROR
;
1379 wxThreadError
wxThread::Resume()
1381 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1382 wxT("a thread can't resume itself") );
1384 wxCriticalSectionLocker
lock(m_critsect
);
1386 wxThreadState state
= m_internal
->GetState();
1391 wxLogTrace(TRACE_THREADS
, wxT("Thread %p suspended, resuming."),
1394 m_internal
->Resume();
1396 return wxTHREAD_NO_ERROR
;
1399 wxLogTrace(TRACE_THREADS
, wxT("Thread %p exited, won't resume."),
1401 return wxTHREAD_NO_ERROR
;
1404 wxLogDebug(wxT("Attempt to resume a thread which is not paused."));
1406 return wxTHREAD_MISC_ERROR
;
1410 // -----------------------------------------------------------------------------
1412 // -----------------------------------------------------------------------------
1414 wxThread::ExitCode
wxThread::Wait()
1416 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1417 wxT("a thread can't wait for itself") );
1419 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1420 wxT("can't wait for detached thread") );
1424 return m_internal
->GetExitCode();
1427 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1429 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1430 wxT("a thread can't delete itself") );
1432 bool isDetached
= m_isDetached
;
1435 wxThreadState state
= m_internal
->GetState();
1437 // ask the thread to stop
1438 m_internal
->SetCancelFlag();
1445 // we need to wake up the thread so that PthreadStart() will
1446 // terminate - right now it's blocking on run semaphore in
1448 m_internal
->SignalRun();
1457 // resume the thread first
1458 m_internal
->Resume();
1465 // wait until the thread stops
1470 // return the exit code of the thread
1471 *rc
= m_internal
->GetExitCode();
1474 //else: can't wait for detached threads
1477 if (state
== STATE_NEW
)
1478 return wxTHREAD_MISC_ERROR
;
1479 // for coherency with the MSW implementation, signal the user that
1480 // Delete() was called on a thread which didn't start to run yet.
1482 return wxTHREAD_NO_ERROR
;
1485 wxThreadError
wxThread::Kill()
1487 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1488 wxT("a thread can't kill itself") );
1490 switch ( m_internal
->GetState() )
1494 return wxTHREAD_NOT_RUNNING
;
1497 // resume the thread first
1503 #ifdef HAVE_PTHREAD_CANCEL
1504 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1505 #endif // HAVE_PTHREAD_CANCEL
1507 wxLogError(_("Failed to terminate a thread."));
1509 return wxTHREAD_MISC_ERROR
;
1512 #ifdef HAVE_PTHREAD_CANCEL
1515 // if we use cleanup function, this will be done from
1516 // wxPthreadCleanup()
1517 #ifndef wxHAVE_PTHREAD_CLEANUP
1518 ScheduleThreadForDeletion();
1520 // don't call OnExit() here, it can only be called in the
1521 // threads context and we're in the context of another thread
1524 #endif // wxHAVE_PTHREAD_CLEANUP
1528 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1531 return wxTHREAD_NO_ERROR
;
1532 #endif // HAVE_PTHREAD_CANCEL
1536 void wxThread::Exit(ExitCode status
)
1538 wxASSERT_MSG( This() == this,
1539 wxT("wxThread::Exit() can only be called in the context of the same thread") );
1543 // from the moment we call OnExit(), the main program may terminate at
1544 // any moment, so mark this thread as being already in process of being
1545 // deleted or wxThreadModule::OnExit() will try to delete it again
1546 ScheduleThreadForDeletion();
1549 // don't enter m_critsect before calling OnExit() because the user code
1550 // might deadlock if, for example, it signals a condition in OnExit() (a
1551 // common case) while the main thread calls any of functions entering
1552 // m_critsect on us (almost all of them do)
1557 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1559 // delete C++ thread object if this is a detached thread - user is
1560 // responsible for doing this for joinable ones
1563 // FIXME I'm feeling bad about it - what if another thread function is
1564 // called (in another thread context) now? It will try to access
1565 // half destroyed object which will probably result in something
1566 // very bad - but we can't protect this by a crit section unless
1567 // we make it a global object, but this would mean that we can
1568 // only call one thread function at a time :-(
1570 pthread_setspecific(gs_keySelf
, 0);
1575 m_internal
->SetState(STATE_EXITED
);
1579 // terminate the thread (pthread_exit() never returns)
1580 pthread_exit(status
);
1582 wxFAIL_MSG(wxT("pthread_exit() failed"));
1585 // also test whether we were paused
1586 bool wxThread::TestDestroy()
1588 wxASSERT_MSG( This() == this,
1589 wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
1593 if ( m_internal
->GetState() == STATE_PAUSED
)
1595 m_internal
->SetReallyPaused(true);
1597 // leave the crit section or the other threads will stop too if they
1598 // try to call any of (seemingly harmless) IsXXX() functions while we
1602 m_internal
->Pause();
1606 // thread wasn't requested to pause, nothing to do
1610 return m_internal
->WasCancelled();
1613 wxThread::~wxThread()
1617 // check that the thread either exited or couldn't be created
1618 if ( m_internal
->GetState() != STATE_EXITED
&&
1619 m_internal
->GetState() != STATE_NEW
)
1621 wxLogDebug(wxT("The thread %p is being destroyed although it is still running! The application may crash."),
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 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
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 wxT("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
, wxT("%lu thread%s waiting to be deleted"),
1776 (unsigned long)gs_nThreadsBeingDeleted
,
1777 gs_nThreadsBeingDeleted
== 1 ? wxT("") : wxT("s"));
1780 static void DeleteThread(wxThread
*This
)
1782 wxLogTrace(TRACE_THREADS
, wxT("Thread %p auto deletes."), THR_ID(This
));
1786 // only lock gs_mutexDeleteThread after deleting the thread to avoid
1787 // calling out into user code with it locked as this may result in
1788 // deadlocks if the thread dtor deletes another thread (see #11501)
1789 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1791 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1792 wxT("no threads scheduled for deletion, yet we delete one?") );
1794 wxLogTrace(TRACE_THREADS
, wxT("%lu threads remain scheduled for deletion."),
1795 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1797 if ( !--gs_nThreadsBeingDeleted
)
1799 // no more threads left, signal it
1800 gs_condAllDeleted
->Signal();
1804 void wxMutexGuiEnterImpl()
1806 gs_mutexGui
->Lock();
1809 void wxMutexGuiLeaveImpl()
1811 gs_mutexGui
->Unlock();
1814 // ----------------------------------------------------------------------------
1815 // include common implementation code
1816 // ----------------------------------------------------------------------------
1818 #include "wx/thrimpl.cpp"
1820 #endif // wxUSE_THREADS