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()
64 #define THR_ID(thr) ((long long)(thr)->GetId())
66 #define THR_ID(thr) ((long)(thr)->GetId())
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // the possible states of the thread and transitions from them
76 STATE_NEW
, // didn't start execution yet (=> RUNNING)
77 STATE_RUNNING
, // running (=> PAUSED or EXITED)
78 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
79 STATE_EXITED
// thread doesn't exist any more
82 // the exit value of a thread which has been cancelled
83 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
85 // trace mask for wxThread operations
86 #define TRACE_THREADS wxT("thread")
88 // you can get additional debugging messages for the semaphore operations
89 #define TRACE_SEMA wxT("semaphore")
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 static void ScheduleThreadForDeletion();
96 static void DeleteThread(wxThread
*This
);
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 // an (non owning) array of pointers to threads
103 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
105 // an entry for a thread we can wait for
107 // -----------------------------------------------------------------------------
109 // -----------------------------------------------------------------------------
111 // we keep the list of all threads created by the application to be able to
112 // terminate them on exit if there are some left - otherwise the process would
114 static wxArrayThread gs_allThreads
;
116 // a mutex to protect gs_allThreads
117 static wxMutex
*gs_mutexAllThreads
= NULL
;
119 // the id of the main thread
121 // we suppose that 0 is not a valid pthread_t value but in principle this might
122 // be false (e.g. if it's a selector-like value), wxThread::IsMain() would need
123 // to be updated in such case
124 wxThreadIdType
wxThread::ms_idMainThread
= 0;
126 // the key for the pointer to the associated wxThread object
127 static pthread_key_t gs_keySelf
;
129 // the number of threads which are being deleted - the program won't exit
130 // until there are any left
131 static size_t gs_nThreadsBeingDeleted
= 0;
133 // a mutex to protect gs_nThreadsBeingDeleted
134 static wxMutex
*gs_mutexDeleteThread
= NULL
;
136 // and a condition variable which will be signaled when all
137 // gs_nThreadsBeingDeleted will have been deleted
138 static wxCondition
*gs_condAllDeleted
= NULL
;
140 // this mutex must be acquired before any call to a GUI function
141 // (it's not inside #if wxUSE_GUI because this file is compiled as part
143 static wxMutex
*gs_mutexGui
= NULL
;
145 // when we wait for a thread to exit, we're blocking on a condition which the
146 // thread signals in its SignalExit() method -- but this condition can't be a
147 // member of the thread itself as a detached thread may delete itself at any
148 // moment and accessing the condition member of the thread after this would
149 // result in a disaster
151 // so instead we maintain a global list of the structs below for the threads
152 // we're interested in waiting on
154 // ============================================================================
155 // wxMutex implementation
156 // ============================================================================
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
162 // this is a simple wrapper around pthread_mutex_t which provides error
164 class wxMutexInternal
167 wxMutexInternal(wxMutexType mutexType
);
171 wxMutexError
Lock(unsigned long ms
);
172 wxMutexError
TryLock();
173 wxMutexError
Unlock();
175 bool IsOk() const { return m_isOk
; }
178 // convert the result of pthread_mutex_[timed]lock() call to wx return code
179 wxMutexError
HandleLockResult(int err
);
182 pthread_mutex_t m_mutex
;
185 unsigned long m_owningThread
;
187 // wxConditionInternal uses our m_mutex
188 friend class wxConditionInternal
;
191 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
192 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
193 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
194 // in the library, otherwise we wouldn't compile this code at all)
195 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
198 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
206 case wxMUTEX_RECURSIVE
:
207 // support recursive locks like Win32, i.e. a thread can lock a
208 // mutex which it had itself already locked
210 // unfortunately initialization of recursive mutexes is non
211 // portable, so try several methods
212 #ifdef HAVE_PTHREAD_MUTEXATTR_T
214 pthread_mutexattr_t attr
;
215 pthread_mutexattr_init(&attr
);
216 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
218 err
= pthread_mutex_init(&m_mutex
, &attr
);
220 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
221 // we can use this only as initializer so we have to assign it
222 // first to a temp var - assigning directly to m_mutex wouldn't
225 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
228 #else // no recursive mutexes
230 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
234 wxFAIL_MSG( wxT("unknown mutex type") );
237 case wxMUTEX_DEFAULT
:
238 err
= pthread_mutex_init(&m_mutex
, NULL
);
245 wxLogApiError( wxT("pthread_mutex_init()"), err
);
249 wxMutexInternal::~wxMutexInternal()
253 int err
= pthread_mutex_destroy(&m_mutex
);
256 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
261 wxMutexError
wxMutexInternal::Lock()
263 if ((m_type
== wxMUTEX_DEFAULT
) && (m_owningThread
!= 0))
265 if (m_owningThread
== wxThread::GetCurrentId())
266 return wxMUTEX_DEAD_LOCK
;
269 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
272 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
274 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
275 static const long MSEC_IN_SEC
= 1000;
276 static const long NSEC_IN_MSEC
= 1000000;
277 static const long NSEC_IN_USEC
= 1000;
278 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
280 time_t seconds
= ms
/MSEC_IN_SEC
;
281 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
282 timespec ts
= { 0, 0 };
284 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
285 // function is in librt and we don't link with it currently, so use
286 // gettimeofday() instead -- if it turns out that this is really too
287 // imprecise, we should modify configure to check if clock_gettime() is
288 // available and whether it requires -lrt and use it instead
290 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
295 if ( wxGetTimeOfDay(&tv
) != -1 )
297 ts
.tv_sec
= tv
.tv_sec
;
298 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
301 else // fall back on system timer
303 ts
.tv_sec
= time(NULL
);
306 ts
.tv_sec
+= seconds
;
307 ts
.tv_nsec
+= nanoseconds
;
308 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
311 ts
.tv_nsec
-= NSEC_IN_SEC
;
314 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
315 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
318 return wxMUTEX_MISC_ERROR
;
319 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
322 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
324 // wxPrintf( "err %d\n", err );
329 // only error checking mutexes return this value and so it's an
330 // unexpected situation -- hence use assert, not wxLogDebug
331 wxFAIL_MSG( wxT("mutex deadlock prevented") );
332 return wxMUTEX_DEAD_LOCK
;
335 wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized"));
339 return wxMUTEX_TIMEOUT
;
342 if (m_type
== wxMUTEX_DEFAULT
)
343 m_owningThread
= wxThread::GetCurrentId();
344 return wxMUTEX_NO_ERROR
;
347 wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err
);
350 return wxMUTEX_MISC_ERROR
;
354 wxMutexError
wxMutexInternal::TryLock()
356 int err
= pthread_mutex_trylock(&m_mutex
);
360 // not an error: mutex is already locked, but we're prepared for
365 wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized."));
369 if (m_type
== wxMUTEX_DEFAULT
)
370 m_owningThread
= wxThread::GetCurrentId();
371 return wxMUTEX_NO_ERROR
;
374 wxLogApiError(wxT("pthread_mutex_trylock()"), err
);
377 return wxMUTEX_MISC_ERROR
;
380 wxMutexError
wxMutexInternal::Unlock()
384 int err
= pthread_mutex_unlock(&m_mutex
);
388 // we don't own the mutex
389 return wxMUTEX_UNLOCKED
;
392 wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized."));
396 return wxMUTEX_NO_ERROR
;
399 wxLogApiError(wxT("pthread_mutex_unlock()"), err
);
402 return wxMUTEX_MISC_ERROR
;
405 // ===========================================================================
406 // wxCondition implementation
407 // ===========================================================================
409 // ---------------------------------------------------------------------------
410 // wxConditionInternal
411 // ---------------------------------------------------------------------------
413 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
414 // with a pthread_mutex_t)
415 class wxConditionInternal
418 wxConditionInternal(wxMutex
& mutex
);
419 ~wxConditionInternal();
421 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
424 wxCondError
WaitTimeout(unsigned long milliseconds
);
426 wxCondError
Signal();
427 wxCondError
Broadcast();
430 // get the POSIX mutex associated with us
431 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
434 pthread_cond_t m_cond
;
439 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
442 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
448 wxLogApiError(wxT("pthread_cond_init()"), err
);
452 wxConditionInternal::~wxConditionInternal()
456 int err
= pthread_cond_destroy(&m_cond
);
459 wxLogApiError(wxT("pthread_cond_destroy()"), err
);
464 wxCondError
wxConditionInternal::Wait()
466 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
469 wxLogApiError(wxT("pthread_cond_wait()"), err
);
471 return wxCOND_MISC_ERROR
;
474 return wxCOND_NO_ERROR
;
477 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
479 wxLongLong curtime
= wxGetLocalTimeMillis();
480 curtime
+= milliseconds
;
481 wxLongLong temp
= curtime
/ 1000;
482 int sec
= temp
.GetLo();
484 temp
= curtime
- temp
;
485 int millis
= temp
.GetLo();
490 tspec
.tv_nsec
= millis
* 1000L * 1000L;
492 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
496 return wxCOND_TIMEOUT
;
499 return wxCOND_NO_ERROR
;
502 wxLogApiError(wxT("pthread_cond_timedwait()"), err
);
505 return wxCOND_MISC_ERROR
;
508 wxCondError
wxConditionInternal::Signal()
510 int err
= pthread_cond_signal(&m_cond
);
513 wxLogApiError(wxT("pthread_cond_signal()"), err
);
515 return wxCOND_MISC_ERROR
;
518 return wxCOND_NO_ERROR
;
521 wxCondError
wxConditionInternal::Broadcast()
523 int err
= pthread_cond_broadcast(&m_cond
);
526 wxLogApiError(wxT("pthread_cond_broadcast()"), err
);
528 return wxCOND_MISC_ERROR
;
531 return wxCOND_NO_ERROR
;
534 // ===========================================================================
535 // wxSemaphore implementation
536 // ===========================================================================
538 // ---------------------------------------------------------------------------
539 // wxSemaphoreInternal
540 // ---------------------------------------------------------------------------
542 // we implement the semaphores using mutexes and conditions instead of using
543 // the sem_xxx() POSIX functions because they're not widely available and also
544 // because it's impossible to implement WaitTimeout() using them
545 class wxSemaphoreInternal
548 wxSemaphoreInternal(int initialcount
, int maxcount
);
550 bool IsOk() const { return m_isOk
; }
553 wxSemaError
TryWait();
554 wxSemaError
WaitTimeout(unsigned long milliseconds
);
568 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
572 if ( (initialcount
< 0 || maxcount
< 0) ||
573 ((maxcount
> 0) && (initialcount
> maxcount
)) )
575 wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") );
581 m_maxcount
= (size_t)maxcount
;
582 m_count
= (size_t)initialcount
;
585 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
588 wxSemaError
wxSemaphoreInternal::Wait()
590 wxMutexLocker
locker(m_mutex
);
592 while ( m_count
== 0 )
594 wxLogTrace(TRACE_SEMA
,
595 wxT("Thread %p waiting for semaphore to become signalled"),
596 wxThread::GetCurrentId());
598 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
599 return wxSEMA_MISC_ERROR
;
601 wxLogTrace(TRACE_SEMA
,
602 wxT("Thread %p finished waiting for semaphore, count = %lu"),
603 wxThread::GetCurrentId(), (unsigned long)m_count
);
608 return wxSEMA_NO_ERROR
;
611 wxSemaError
wxSemaphoreInternal::TryWait()
613 wxMutexLocker
locker(m_mutex
);
620 return wxSEMA_NO_ERROR
;
623 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
625 wxMutexLocker
locker(m_mutex
);
627 wxLongLong startTime
= wxGetLocalTimeMillis();
629 while ( m_count
== 0 )
631 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
632 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
633 if ( remainingTime
<= 0 )
636 return wxSEMA_TIMEOUT
;
639 switch ( m_cond
.WaitTimeout(remainingTime
) )
642 return wxSEMA_TIMEOUT
;
645 return wxSEMA_MISC_ERROR
;
647 case wxCOND_NO_ERROR
:
654 return wxSEMA_NO_ERROR
;
657 wxSemaError
wxSemaphoreInternal::Post()
659 wxMutexLocker
locker(m_mutex
);
661 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
663 return wxSEMA_OVERFLOW
;
668 wxLogTrace(TRACE_SEMA
,
669 wxT("Thread %p about to signal semaphore, count = %lu"),
670 wxThread::GetCurrentId(), (unsigned long)m_count
);
672 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
676 // ===========================================================================
677 // wxThread implementation
678 // ===========================================================================
680 // the thread callback functions must have the C linkage
684 #ifdef wxHAVE_PTHREAD_CLEANUP
685 // thread exit function
686 void wxPthreadCleanup(void *ptr
);
687 #endif // wxHAVE_PTHREAD_CLEANUP
689 void *wxPthreadStart(void *ptr
);
693 // ----------------------------------------------------------------------------
695 // ----------------------------------------------------------------------------
697 class wxThreadInternal
703 // thread entry function
704 static void *PthreadStart(wxThread
*thread
);
709 // unblock the thread allowing it to run
710 void SignalRun() { m_semRun
.Post(); }
711 // ask the thread to terminate
713 // go to sleep until Resume() is called
720 int GetPriority() const { return m_prio
; }
721 void SetPriority(int prio
) { m_prio
= prio
; }
723 wxThreadState
GetState() const { return m_state
; }
724 void SetState(wxThreadState state
)
727 static const wxChar
*const stateNames
[] =
735 wxLogTrace(TRACE_THREADS
, wxT("Thread %p: %s => %s."),
736 GetId(), stateNames
[m_state
], stateNames
[state
]);
737 #endif // wxUSE_LOG_TRACE
742 pthread_t
GetId() const { return m_threadId
; }
743 pthread_t
*GetIdPtr() { return &m_threadId
; }
745 void SetCancelFlag() { m_cancelled
= true; }
746 bool WasCancelled() const { return m_cancelled
; }
748 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
749 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
752 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
753 bool IsReallyPaused() const { return m_isPaused
; }
755 // tell the thread that it is a detached one
758 wxCriticalSectionLocker
lock(m_csJoinFlag
);
760 m_shouldBeJoined
= false;
764 #ifdef wxHAVE_PTHREAD_CLEANUP
765 // this is used by wxPthreadCleanup() only
766 static void Cleanup(wxThread
*thread
);
767 #endif // wxHAVE_PTHREAD_CLEANUP
770 pthread_t m_threadId
; // id of the thread
771 wxThreadState m_state
; // see wxThreadState enum
772 int m_prio
; // in wxWidgets units: from 0 to 100
774 // this flag is set when the thread should terminate
777 // this flag is set when the thread is blocking on m_semSuspend
780 // the thread exit code - only used for joinable (!detached) threads and
781 // is only valid after the thread termination
782 wxThread::ExitCode m_exitcode
;
784 // many threads may call Wait(), but only one of them should call
785 // pthread_join(), so we have to keep track of this
786 wxCriticalSection m_csJoinFlag
;
787 bool m_shouldBeJoined
;
790 // this semaphore is posted by Run() and the threads Entry() is not
791 // called before it is done
792 wxSemaphore m_semRun
;
794 // this one is signaled when the thread should resume after having been
796 wxSemaphore m_semSuspend
;
799 // ----------------------------------------------------------------------------
800 // thread startup and exit functions
801 // ----------------------------------------------------------------------------
803 void *wxPthreadStart(void *ptr
)
805 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
808 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
810 wxThreadInternal
*pthread
= thread
->m_internal
;
812 wxLogTrace(TRACE_THREADS
, wxT("Thread %p started."), THR_ID(pthread
));
814 // associate the thread pointer with the newly created thread so that
815 // wxThread::This() will work
816 int rc
= pthread_setspecific(gs_keySelf
, thread
);
819 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
824 // have to declare this before pthread_cleanup_push() which defines a
828 #ifdef wxHAVE_PTHREAD_CLEANUP
829 // install the cleanup handler which will be called if the thread is
831 pthread_cleanup_push(wxPthreadCleanup
, thread
);
832 #endif // wxHAVE_PTHREAD_CLEANUP
834 // wait for the semaphore to be posted from Run()
835 pthread
->m_semRun
.Wait();
837 // test whether we should run the run at all - may be it was deleted
838 // before it started to Run()?
840 wxCriticalSectionLocker
lock(thread
->m_critsect
);
842 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
843 pthread
->WasCancelled();
848 // call the main entry
849 wxLogTrace(TRACE_THREADS
,
850 wxT("Thread %p about to enter its Entry()."),
855 pthread
->m_exitcode
= thread
->Entry();
857 wxLogTrace(TRACE_THREADS
,
858 wxT("Thread %p Entry() returned %lu."),
859 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
861 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
864 wxCriticalSectionLocker
lock(thread
->m_critsect
);
866 // change the state of the thread to "exited" so that
867 // wxPthreadCleanup handler won't do anything from now (if it's
868 // called before we do pthread_cleanup_pop below)
869 pthread
->SetState(STATE_EXITED
);
873 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
874 // '}' for the '{' in push, so they must be used in the same block!
875 #ifdef wxHAVE_PTHREAD_CLEANUP
877 // under Tru64 we get a warning from macro expansion
879 #pragma message disable(declbutnotref)
882 // remove the cleanup handler without executing it
883 pthread_cleanup_pop(FALSE
);
886 #pragma message restore
888 #endif // wxHAVE_PTHREAD_CLEANUP
892 // FIXME: deleting a possibly joinable thread here???
895 return EXITCODE_CANCELLED
;
899 // terminate the thread
900 thread
->Exit(pthread
->m_exitcode
);
902 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
908 #ifdef wxHAVE_PTHREAD_CLEANUP
910 // this handler is called when the thread is cancelled
911 extern "C" void wxPthreadCleanup(void *ptr
)
913 wxThreadInternal::Cleanup((wxThread
*)ptr
);
916 void wxThreadInternal::Cleanup(wxThread
*thread
)
918 if (pthread_getspecific(gs_keySelf
) == 0) return;
920 wxCriticalSectionLocker
lock(thread
->m_critsect
);
921 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
923 // thread is already considered as finished.
928 // exit the thread gracefully
929 thread
->Exit(EXITCODE_CANCELLED
);
932 #endif // wxHAVE_PTHREAD_CLEANUP
934 // ----------------------------------------------------------------------------
936 // ----------------------------------------------------------------------------
938 wxThreadInternal::wxThreadInternal()
942 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
946 // set to true only when the thread starts waiting on m_semSuspend
949 // defaults for joinable threads
950 m_shouldBeJoined
= true;
951 m_isDetached
= false;
954 wxThreadInternal::~wxThreadInternal()
958 wxThreadError
wxThreadInternal::Run()
960 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
961 wxT("thread may only be started once after Create()") );
963 SetState(STATE_RUNNING
);
965 // wake up threads waiting for our start
968 return wxTHREAD_NO_ERROR
;
971 void wxThreadInternal::Wait()
973 wxCHECK_RET( !m_isDetached
, wxT("can't wait for a detached thread") );
975 // if the thread we're waiting for is waiting for the GUI mutex, we will
976 // deadlock so make sure we release it temporarily
977 if ( wxThread::IsMain() )
980 wxLogTrace(TRACE_THREADS
,
981 wxT("Starting to wait for thread %p to exit."),
984 // to avoid memory leaks we should call pthread_join(), but it must only be
985 // done once so use a critical section to serialize the code below
987 wxCriticalSectionLocker
lock(m_csJoinFlag
);
989 if ( m_shouldBeJoined
)
991 // FIXME shouldn't we set cancellation type to DISABLED here? If
992 // we're cancelled inside pthread_join(), things will almost
993 // certainly break - but if we disable the cancellation, we
995 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
997 // this is a serious problem, so use wxLogError and not
998 // wxLogDebug: it is possible to bring the system to its knees
999 // by creating too many threads and not joining them quite
1001 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
1004 m_shouldBeJoined
= false;
1008 // reacquire GUI mutex
1009 if ( wxThread::IsMain() )
1013 void wxThreadInternal::Pause()
1015 // the state is set from the thread which pauses us first, this function
1016 // is called later so the state should have been already set
1017 wxCHECK_RET( m_state
== STATE_PAUSED
,
1018 wxT("thread must first be paused with wxThread::Pause().") );
1020 wxLogTrace(TRACE_THREADS
,
1021 wxT("Thread %p goes to sleep."), THR_ID(this));
1023 // wait until the semaphore is Post()ed from Resume()
1024 m_semSuspend
.Wait();
1027 void wxThreadInternal::Resume()
1029 wxCHECK_RET( m_state
== STATE_PAUSED
,
1030 wxT("can't resume thread which is not suspended.") );
1032 // the thread might be not actually paused yet - if there were no call to
1033 // TestDestroy() since the last call to Pause() for example
1034 if ( IsReallyPaused() )
1036 wxLogTrace(TRACE_THREADS
,
1037 wxT("Waking up thread %p"), THR_ID(this));
1040 m_semSuspend
.Post();
1043 SetReallyPaused(false);
1047 wxLogTrace(TRACE_THREADS
,
1048 wxT("Thread %p is not yet really paused"), THR_ID(this));
1051 SetState(STATE_RUNNING
);
1054 // -----------------------------------------------------------------------------
1055 // wxThread static functions
1056 // -----------------------------------------------------------------------------
1058 wxThread
*wxThread::This()
1060 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1063 void wxThread::Yield()
1065 #ifdef HAVE_SCHED_YIELD
1070 int wxThread::GetCPUCount()
1072 #if defined(_SC_NPROCESSORS_ONLN)
1073 // this works for Solaris and Linux 2.6
1074 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1079 #elif defined(__LINUX__) && wxUSE_FFILE
1080 // read from proc (can't use wxTextFile here because it's a special file:
1081 // it has 0 size but still can be read from)
1084 wxFFile
file(wxT("/proc/cpuinfo"));
1085 if ( file
.IsOpened() )
1087 // slurp the whole file
1089 if ( file
.ReadAll(&s
) )
1091 // (ab)use Replace() to find the number of "processor: num" strings
1092 size_t count
= s
.Replace(wxT("processor\t:"), wxT(""));
1098 wxLogDebug(wxT("failed to parse /proc/cpuinfo"));
1102 wxLogDebug(wxT("failed to read /proc/cpuinfo"));
1105 #endif // different ways to get number of CPUs
1111 wxThreadIdType
wxThread::GetCurrentId()
1113 return (wxThreadIdType
)pthread_self();
1117 bool wxThread::SetConcurrency(size_t level
)
1119 #ifdef HAVE_THR_SETCONCURRENCY
1120 int rc
= thr_setconcurrency(level
);
1123 wxLogSysError(rc
, wxT("thr_setconcurrency() failed"));
1127 #else // !HAVE_THR_SETCONCURRENCY
1128 // ok only for the default value
1130 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1133 // -----------------------------------------------------------------------------
1135 // -----------------------------------------------------------------------------
1137 wxThread::wxThread(wxThreadKind kind
)
1139 // add this thread to the global list of all threads
1141 wxMutexLocker
lock(*gs_mutexAllThreads
);
1143 gs_allThreads
.Add(this);
1146 m_internal
= new wxThreadInternal();
1148 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1151 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1152 #define WXUNUSED_STACKSIZE(identifier) identifier
1154 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1157 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1159 if ( m_internal
->GetState() != STATE_NEW
)
1161 // don't recreate thread
1162 return wxTHREAD_RUNNING
;
1165 // set up the thread attribute: right now, we only set thread priority
1166 pthread_attr_t attr
;
1167 pthread_attr_init(&attr
);
1169 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1171 pthread_attr_setstacksize(&attr
, stackSize
);
1174 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1176 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1178 wxLogError(_("Cannot retrieve thread scheduling policy."));
1182 /* the pthread.h contains too many spaces. This is a work-around */
1183 # undef sched_get_priority_max
1184 #undef sched_get_priority_min
1185 #define sched_get_priority_max(_pol_) \
1186 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1187 #define sched_get_priority_min(_pol_) \
1188 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1191 int max_prio
= sched_get_priority_max(policy
),
1192 min_prio
= sched_get_priority_min(policy
),
1193 prio
= m_internal
->GetPriority();
1195 if ( min_prio
== -1 || max_prio
== -1 )
1197 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1200 else if ( max_prio
== min_prio
)
1202 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1204 // notify the programmer that this doesn't work here
1205 wxLogWarning(_("Thread priority setting is ignored."));
1207 //else: we have default priority, so don't complain
1209 // anyhow, don't do anything because priority is just ignored
1213 struct sched_param sp
;
1214 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1216 wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed"));
1219 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1221 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1223 wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed"));
1226 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1228 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1229 // this will make the threads created by this process really concurrent
1230 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1232 wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1234 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1236 // VZ: assume that this one is always available (it's rather fundamental),
1237 // if this function is ever missing we should try to use
1238 // pthread_detach() instead (after thread creation)
1241 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1243 wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed"));
1246 // never try to join detached threads
1247 m_internal
->Detach();
1249 //else: threads are created joinable by default, it's ok
1251 // create the new OS thread object
1252 int rc
= pthread_create
1254 m_internal
->GetIdPtr(),
1260 if ( pthread_attr_destroy(&attr
) != 0 )
1262 wxFAIL_MSG(wxT("pthread_attr_destroy() failed"));
1267 m_internal
->SetState(STATE_EXITED
);
1269 return wxTHREAD_NO_RESOURCE
;
1272 return wxTHREAD_NO_ERROR
;
1275 wxThreadError
wxThread::Run()
1277 wxCriticalSectionLocker
lock(m_critsect
);
1279 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1280 wxT("must call wxThread::Create() first") );
1282 return m_internal
->Run();
1285 // -----------------------------------------------------------------------------
1287 // -----------------------------------------------------------------------------
1289 void wxThread::SetPriority(unsigned int prio
)
1291 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1292 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1293 wxT("invalid thread priority") );
1295 wxCriticalSectionLocker
lock(m_critsect
);
1297 switch ( m_internal
->GetState() )
1300 // thread not yet started, priority will be set when it is
1301 m_internal
->SetPriority(prio
);
1306 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1307 #if defined(__LINUX__)
1308 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1309 // a priority other than 0. Instead, we use the BSD setpriority
1310 // which alllows us to set a 'nice' value between 20 to -20. Only
1311 // super user can set a value less than zero (more negative yields
1312 // higher priority). setpriority set the static priority of a
1313 // process, but this is OK since Linux is configured as a thread
1316 // FIXME this is not true for 2.6!!
1318 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1319 // to Unix priorities 20..-20
1320 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1322 wxLogError(_("Failed to set thread priority %d."), prio
);
1326 struct sched_param sparam
;
1327 sparam
.sched_priority
= prio
;
1329 if ( pthread_setschedparam(m_internal
->GetId(),
1330 SCHED_OTHER
, &sparam
) != 0 )
1332 wxLogError(_("Failed to set thread priority %d."), prio
);
1336 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1341 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1345 unsigned int wxThread::GetPriority() const
1347 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1349 return m_internal
->GetPriority();
1352 wxThreadIdType
wxThread::GetId() const
1354 return (wxThreadIdType
) m_internal
->GetId();
1357 // -----------------------------------------------------------------------------
1359 // -----------------------------------------------------------------------------
1361 wxThreadError
wxThread::Pause()
1363 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1364 wxT("a thread can't pause itself") );
1366 wxCriticalSectionLocker
lock(m_critsect
);
1368 if ( m_internal
->GetState() != STATE_RUNNING
)
1370 wxLogDebug(wxT("Can't pause thread which is not running."));
1372 return wxTHREAD_NOT_RUNNING
;
1375 // just set a flag, the thread will be really paused only during the next
1376 // call to TestDestroy()
1377 m_internal
->SetState(STATE_PAUSED
);
1379 return wxTHREAD_NO_ERROR
;
1382 wxThreadError
wxThread::Resume()
1384 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1385 wxT("a thread can't resume itself") );
1387 wxCriticalSectionLocker
lock(m_critsect
);
1389 wxThreadState state
= m_internal
->GetState();
1394 wxLogTrace(TRACE_THREADS
, wxT("Thread %p suspended, resuming."),
1397 m_internal
->Resume();
1399 return wxTHREAD_NO_ERROR
;
1402 wxLogTrace(TRACE_THREADS
, wxT("Thread %p exited, won't resume."),
1404 return wxTHREAD_NO_ERROR
;
1407 wxLogDebug(wxT("Attempt to resume a thread which is not paused."));
1409 return wxTHREAD_MISC_ERROR
;
1413 // -----------------------------------------------------------------------------
1415 // -----------------------------------------------------------------------------
1417 wxThread::ExitCode
wxThread::Wait()
1419 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1420 wxT("a thread can't wait for itself") );
1422 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1423 wxT("can't wait for detached thread") );
1427 return m_internal
->GetExitCode();
1430 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1432 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1433 wxT("a thread can't delete itself") );
1435 bool isDetached
= m_isDetached
;
1438 wxThreadState state
= m_internal
->GetState();
1440 // ask the thread to stop
1441 m_internal
->SetCancelFlag();
1448 // we need to wake up the thread so that PthreadStart() will
1449 // terminate - right now it's blocking on run semaphore in
1451 m_internal
->SignalRun();
1460 // resume the thread first
1461 m_internal
->Resume();
1468 // wait until the thread stops
1473 // return the exit code of the thread
1474 *rc
= m_internal
->GetExitCode();
1477 //else: can't wait for detached threads
1480 return wxTHREAD_NO_ERROR
;
1483 wxThreadError
wxThread::Kill()
1485 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1486 wxT("a thread can't kill itself") );
1488 switch ( m_internal
->GetState() )
1492 return wxTHREAD_NOT_RUNNING
;
1495 // resume the thread first
1501 #ifdef HAVE_PTHREAD_CANCEL
1502 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1503 #endif // HAVE_PTHREAD_CANCEL
1505 wxLogError(_("Failed to terminate a thread."));
1507 return wxTHREAD_MISC_ERROR
;
1510 #ifdef HAVE_PTHREAD_CANCEL
1513 // if we use cleanup function, this will be done from
1514 // wxPthreadCleanup()
1515 #ifndef wxHAVE_PTHREAD_CLEANUP
1516 ScheduleThreadForDeletion();
1518 // don't call OnExit() here, it can only be called in the
1519 // threads context and we're in the context of another thread
1522 #endif // wxHAVE_PTHREAD_CLEANUP
1526 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1529 return wxTHREAD_NO_ERROR
;
1530 #endif // HAVE_PTHREAD_CANCEL
1534 void wxThread::Exit(ExitCode status
)
1536 wxASSERT_MSG( This() == this,
1537 wxT("wxThread::Exit() can only be called in the context of the same thread") );
1541 // from the moment we call OnExit(), the main program may terminate at
1542 // any moment, so mark this thread as being already in process of being
1543 // deleted or wxThreadModule::OnExit() will try to delete it again
1544 ScheduleThreadForDeletion();
1547 // don't enter m_critsect before calling OnExit() because the user code
1548 // might deadlock if, for example, it signals a condition in OnExit() (a
1549 // common case) while the main thread calls any of functions entering
1550 // m_critsect on us (almost all of them do)
1555 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1557 // delete C++ thread object if this is a detached thread - user is
1558 // responsible for doing this for joinable ones
1561 // FIXME I'm feeling bad about it - what if another thread function is
1562 // called (in another thread context) now? It will try to access
1563 // half destroyed object which will probably result in something
1564 // very bad - but we can't protect this by a crit section unless
1565 // we make it a global object, but this would mean that we can
1566 // only call one thread function at a time :-(
1568 pthread_setspecific(gs_keySelf
, 0);
1573 m_internal
->SetState(STATE_EXITED
);
1577 // terminate the thread (pthread_exit() never returns)
1578 pthread_exit(status
);
1580 wxFAIL_MSG(wxT("pthread_exit() failed"));
1583 // also test whether we were paused
1584 bool wxThread::TestDestroy()
1586 wxASSERT_MSG( This() == this,
1587 wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
1591 if ( m_internal
->GetState() == STATE_PAUSED
)
1593 m_internal
->SetReallyPaused(true);
1595 // leave the crit section or the other threads will stop too if they
1596 // try to call any of (seemingly harmless) IsXXX() functions while we
1600 m_internal
->Pause();
1604 // thread wasn't requested to pause, nothing to do
1608 return m_internal
->WasCancelled();
1611 wxThread::~wxThread()
1615 // check that the thread either exited or couldn't be created
1616 if ( m_internal
->GetState() != STATE_EXITED
&&
1617 m_internal
->GetState() != STATE_NEW
)
1619 wxLogDebug(wxT("The thread %ld is being destroyed although it is still running! The application may crash."),
1627 // remove this thread from the global array
1629 wxMutexLocker
lock(*gs_mutexAllThreads
);
1631 gs_allThreads
.Remove(this);
1635 // -----------------------------------------------------------------------------
1637 // -----------------------------------------------------------------------------
1639 bool wxThread::IsRunning() const
1641 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1643 return m_internal
->GetState() == STATE_RUNNING
;
1646 bool wxThread::IsAlive() const
1648 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1650 switch ( m_internal
->GetState() )
1661 bool wxThread::IsPaused() const
1663 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1665 return (m_internal
->GetState() == STATE_PAUSED
);
1668 //--------------------------------------------------------------------
1670 //--------------------------------------------------------------------
1672 class wxThreadModule
: public wxModule
1675 virtual bool OnInit();
1676 virtual void OnExit();
1679 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1682 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1684 bool wxThreadModule::OnInit()
1686 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1689 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1694 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1696 gs_mutexAllThreads
= new wxMutex();
1698 gs_mutexGui
= new wxMutex();
1699 gs_mutexGui
->Lock();
1701 gs_mutexDeleteThread
= new wxMutex();
1702 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1707 void wxThreadModule::OnExit()
1709 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1711 // are there any threads left which are being deleted right now?
1712 size_t nThreadsBeingDeleted
;
1715 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1716 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1718 if ( nThreadsBeingDeleted
> 0 )
1720 wxLogTrace(TRACE_THREADS
,
1721 wxT("Waiting for %lu threads to disappear"),
1722 (unsigned long)nThreadsBeingDeleted
);
1724 // have to wait until all of them disappear
1725 gs_condAllDeleted
->Wait();
1732 wxMutexLocker
lock(*gs_mutexAllThreads
);
1734 // terminate any threads left
1735 count
= gs_allThreads
.GetCount();
1738 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1739 (unsigned long)count
);
1741 } // unlock mutex before deleting the threads as they lock it in their dtor
1743 for ( size_t n
= 0u; n
< count
; n
++ )
1745 // Delete calls the destructor which removes the current entry. We
1746 // should only delete the first one each time.
1747 gs_allThreads
[0]->Delete();
1750 delete gs_mutexAllThreads
;
1752 // destroy GUI mutex
1753 gs_mutexGui
->Unlock();
1756 // and free TLD slot
1757 (void)pthread_key_delete(gs_keySelf
);
1759 delete gs_condAllDeleted
;
1760 delete gs_mutexDeleteThread
;
1763 // ----------------------------------------------------------------------------
1765 // ----------------------------------------------------------------------------
1767 static void ScheduleThreadForDeletion()
1769 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1771 gs_nThreadsBeingDeleted
++;
1773 wxLogTrace(TRACE_THREADS
, wxT("%lu thread%s waiting to be deleted"),
1774 (unsigned long)gs_nThreadsBeingDeleted
,
1775 gs_nThreadsBeingDeleted
== 1 ? wxT("") : wxT("s"));
1778 static void DeleteThread(wxThread
*This
)
1780 wxLogTrace(TRACE_THREADS
, wxT("Thread %p auto deletes."), This
->GetId());
1784 // only lock gs_mutexDeleteThread after deleting the thread to avoid
1785 // calling out into user code with it locked as this may result in
1786 // deadlocks if the thread dtor deletes another thread (see #11501)
1787 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1789 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1790 wxT("no threads scheduled for deletion, yet we delete one?") );
1792 wxLogTrace(TRACE_THREADS
, wxT("%lu threads remain scheduled for deletion."),
1793 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1795 if ( !--gs_nThreadsBeingDeleted
)
1797 // no more threads left, signal it
1798 gs_condAllDeleted
->Signal();
1802 void wxMutexGuiEnterImpl()
1804 gs_mutexGui
->Lock();
1807 void wxMutexGuiLeaveImpl()
1809 gs_mutexGui
->Unlock();
1812 // ----------------------------------------------------------------------------
1813 // include common implementation code
1814 // ----------------------------------------------------------------------------
1816 #include "wx/thrimpl.cpp"
1818 #endif // wxUSE_THREADS