1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/threadpsx.cpp
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
30 #include "wx/except.h"
34 #include "wx/dynarray.h"
39 #include "wx/stopwatch.h"
40 #include "wx/module.h"
52 #ifdef HAVE_THR_SETCONCURRENCY
56 // we use wxFFile under Linux in GetCPUCount()
61 #include <sys/resource.h>
65 #define THR_ID(thr) ((long long)(thr)->GetId())
67 #define THR_ID(thr) ((long)(thr)->GetId())
70 // ----------------------------------------------------------------------------
72 // ----------------------------------------------------------------------------
74 // the possible states of the thread and transitions from them
77 STATE_NEW
, // didn't start execution yet (=> RUNNING)
78 STATE_RUNNING
, // running (=> PAUSED or EXITED)
79 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
80 STATE_EXITED
// thread doesn't exist any more
83 // the exit value of a thread which has been cancelled
84 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
86 // trace mask for wxThread operations
87 #define TRACE_THREADS wxT("thread")
89 // you can get additional debugging messages for the semaphore operations
90 #define TRACE_SEMA wxT("semaphore")
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 static void ScheduleThreadForDeletion();
97 static void DeleteThread(wxThread
*This
);
99 // ----------------------------------------------------------------------------
101 // ----------------------------------------------------------------------------
103 // an (non owning) array of pointers to threads
104 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
106 // an entry for a thread we can wait for
108 // -----------------------------------------------------------------------------
110 // -----------------------------------------------------------------------------
112 // we keep the list of all threads created by the application to be able to
113 // terminate them on exit if there are some left - otherwise the process would
115 static wxArrayThread gs_allThreads
;
117 // a mutex to protect gs_allThreads
118 static wxMutex
*gs_mutexAllThreads
= NULL
;
120 // the id of the main thread
122 // we suppose that 0 is not a valid pthread_t value but in principle this might
123 // be false (e.g. if it's a selector-like value), wxThread::IsMain() would need
124 // to be updated in such case
125 wxThreadIdType
wxThread::ms_idMainThread
= 0;
127 // the key for the pointer to the associated wxThread object
128 static pthread_key_t gs_keySelf
;
130 // the number of threads which are being deleted - the program won't exit
131 // until there are any left
132 static size_t gs_nThreadsBeingDeleted
= 0;
134 // a mutex to protect gs_nThreadsBeingDeleted
135 static wxMutex
*gs_mutexDeleteThread
= NULL
;
137 // and a condition variable which will be signaled when all
138 // gs_nThreadsBeingDeleted will have been deleted
139 static wxCondition
*gs_condAllDeleted
= NULL
;
141 // this mutex must be acquired before any call to a GUI function
142 // (it's not inside #if wxUSE_GUI because this file is compiled as part
144 static wxMutex
*gs_mutexGui
= NULL
;
146 // when we wait for a thread to exit, we're blocking on a condition which the
147 // thread signals in its SignalExit() method -- but this condition can't be a
148 // member of the thread itself as a detached thread may delete itself at any
149 // moment and accessing the condition member of the thread after this would
150 // result in a disaster
152 // so instead we maintain a global list of the structs below for the threads
153 // we're interested in waiting on
155 // ============================================================================
156 // wxMutex implementation
157 // ============================================================================
159 // ----------------------------------------------------------------------------
161 // ----------------------------------------------------------------------------
163 // this is a simple wrapper around pthread_mutex_t which provides error
165 class wxMutexInternal
168 wxMutexInternal(wxMutexType mutexType
);
172 wxMutexError
Lock(unsigned long ms
);
173 wxMutexError
TryLock();
174 wxMutexError
Unlock();
176 bool IsOk() const { return m_isOk
; }
179 // convert the result of pthread_mutex_[timed]lock() call to wx return code
180 wxMutexError
HandleLockResult(int err
);
183 pthread_mutex_t m_mutex
;
186 unsigned long m_owningThread
;
188 // wxConditionInternal uses our m_mutex
189 friend class wxConditionInternal
;
192 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
193 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
194 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
195 // in the library, otherwise we wouldn't compile this code at all)
196 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
199 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
207 case wxMUTEX_RECURSIVE
:
208 // support recursive locks like Win32, i.e. a thread can lock a
209 // mutex which it had itself already locked
211 // unfortunately initialization of recursive mutexes is non
212 // portable, so try several methods
213 #ifdef HAVE_PTHREAD_MUTEXATTR_T
215 pthread_mutexattr_t attr
;
216 pthread_mutexattr_init(&attr
);
217 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
219 err
= pthread_mutex_init(&m_mutex
, &attr
);
221 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
222 // we can use this only as initializer so we have to assign it
223 // first to a temp var - assigning directly to m_mutex wouldn't
226 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
229 #else // no recursive mutexes
231 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
235 wxFAIL_MSG( wxT("unknown mutex type") );
238 case wxMUTEX_DEFAULT
:
239 err
= pthread_mutex_init(&m_mutex
, NULL
);
246 wxLogApiError( wxT("pthread_mutex_init()"), err
);
250 wxMutexInternal::~wxMutexInternal()
254 int err
= pthread_mutex_destroy(&m_mutex
);
257 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
262 wxMutexError
wxMutexInternal::Lock()
264 if ((m_type
== wxMUTEX_DEFAULT
) && (m_owningThread
!= 0))
266 if (m_owningThread
== wxThread::GetCurrentId())
267 return wxMUTEX_DEAD_LOCK
;
270 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
273 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
275 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
276 static const long MSEC_IN_SEC
= 1000;
277 static const long NSEC_IN_MSEC
= 1000000;
278 static const long NSEC_IN_USEC
= 1000;
279 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
281 time_t seconds
= ms
/MSEC_IN_SEC
;
282 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
283 timespec ts
= { 0, 0 };
285 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
286 // function is in librt and we don't link with it currently, so use
287 // gettimeofday() instead -- if it turns out that this is really too
288 // imprecise, we should modify configure to check if clock_gettime() is
289 // available and whether it requires -lrt and use it instead
291 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
296 if ( wxGetTimeOfDay(&tv
) != -1 )
298 ts
.tv_sec
= tv
.tv_sec
;
299 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
302 else // fall back on system timer
304 ts
.tv_sec
= time(NULL
);
307 ts
.tv_sec
+= seconds
;
308 ts
.tv_nsec
+= nanoseconds
;
309 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
312 ts
.tv_nsec
-= NSEC_IN_SEC
;
315 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
316 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
319 return wxMUTEX_MISC_ERROR
;
320 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
323 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
325 // wxPrintf( "err %d\n", err );
330 // only error checking mutexes return this value and so it's an
331 // unexpected situation -- hence use assert, not wxLogDebug
332 wxFAIL_MSG( wxT("mutex deadlock prevented") );
333 return wxMUTEX_DEAD_LOCK
;
336 wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized"));
340 return wxMUTEX_TIMEOUT
;
343 if (m_type
== wxMUTEX_DEFAULT
)
344 m_owningThread
= wxThread::GetCurrentId();
345 return wxMUTEX_NO_ERROR
;
348 wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err
);
351 return wxMUTEX_MISC_ERROR
;
355 wxMutexError
wxMutexInternal::TryLock()
357 int err
= pthread_mutex_trylock(&m_mutex
);
361 // not an error: mutex is already locked, but we're prepared for
366 wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized."));
370 if (m_type
== wxMUTEX_DEFAULT
)
371 m_owningThread
= wxThread::GetCurrentId();
372 return wxMUTEX_NO_ERROR
;
375 wxLogApiError(wxT("pthread_mutex_trylock()"), err
);
378 return wxMUTEX_MISC_ERROR
;
381 wxMutexError
wxMutexInternal::Unlock()
385 int err
= pthread_mutex_unlock(&m_mutex
);
389 // we don't own the mutex
390 return wxMUTEX_UNLOCKED
;
393 wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized."));
397 return wxMUTEX_NO_ERROR
;
400 wxLogApiError(wxT("pthread_mutex_unlock()"), err
);
403 return wxMUTEX_MISC_ERROR
;
406 // ===========================================================================
407 // wxCondition implementation
408 // ===========================================================================
410 // ---------------------------------------------------------------------------
411 // wxConditionInternal
412 // ---------------------------------------------------------------------------
414 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
415 // with a pthread_mutex_t)
416 class wxConditionInternal
419 wxConditionInternal(wxMutex
& mutex
);
420 ~wxConditionInternal();
422 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
425 wxCondError
WaitTimeout(unsigned long milliseconds
);
427 wxCondError
Signal();
428 wxCondError
Broadcast();
431 // get the POSIX mutex associated with us
432 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
435 pthread_cond_t m_cond
;
440 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
443 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
449 wxLogApiError(wxT("pthread_cond_init()"), err
);
453 wxConditionInternal::~wxConditionInternal()
457 int err
= pthread_cond_destroy(&m_cond
);
460 wxLogApiError(wxT("pthread_cond_destroy()"), err
);
465 wxCondError
wxConditionInternal::Wait()
467 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
470 wxLogApiError(wxT("pthread_cond_wait()"), err
);
472 return wxCOND_MISC_ERROR
;
475 return wxCOND_NO_ERROR
;
478 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
480 wxLongLong curtime
= wxGetLocalTimeMillis();
481 curtime
+= milliseconds
;
482 wxLongLong temp
= curtime
/ 1000;
483 int sec
= temp
.GetLo();
485 temp
= curtime
- temp
;
486 int millis
= temp
.GetLo();
491 tspec
.tv_nsec
= millis
* 1000L * 1000L;
493 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
497 return wxCOND_TIMEOUT
;
500 return wxCOND_NO_ERROR
;
503 wxLogApiError(wxT("pthread_cond_timedwait()"), err
);
506 return wxCOND_MISC_ERROR
;
509 wxCondError
wxConditionInternal::Signal()
511 int err
= pthread_cond_signal(&m_cond
);
514 wxLogApiError(wxT("pthread_cond_signal()"), err
);
516 return wxCOND_MISC_ERROR
;
519 return wxCOND_NO_ERROR
;
522 wxCondError
wxConditionInternal::Broadcast()
524 int err
= pthread_cond_broadcast(&m_cond
);
527 wxLogApiError(wxT("pthread_cond_broadcast()"), err
);
529 return wxCOND_MISC_ERROR
;
532 return wxCOND_NO_ERROR
;
535 // ===========================================================================
536 // wxSemaphore implementation
537 // ===========================================================================
539 // ---------------------------------------------------------------------------
540 // wxSemaphoreInternal
541 // ---------------------------------------------------------------------------
543 // we implement the semaphores using mutexes and conditions instead of using
544 // the sem_xxx() POSIX functions because they're not widely available and also
545 // because it's impossible to implement WaitTimeout() using them
546 class wxSemaphoreInternal
549 wxSemaphoreInternal(int initialcount
, int maxcount
);
551 bool IsOk() const { return m_isOk
; }
554 wxSemaError
TryWait();
555 wxSemaError
WaitTimeout(unsigned long milliseconds
);
569 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
573 if ( (initialcount
< 0 || maxcount
< 0) ||
574 ((maxcount
> 0) && (initialcount
> maxcount
)) )
576 wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") );
582 m_maxcount
= (size_t)maxcount
;
583 m_count
= (size_t)initialcount
;
586 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
589 wxSemaError
wxSemaphoreInternal::Wait()
591 wxMutexLocker
locker(m_mutex
);
593 while ( m_count
== 0 )
595 wxLogTrace(TRACE_SEMA
,
596 wxT("Thread %p waiting for semaphore to become signalled"),
597 wxThread::GetCurrentId());
599 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
600 return wxSEMA_MISC_ERROR
;
602 wxLogTrace(TRACE_SEMA
,
603 wxT("Thread %p finished waiting for semaphore, count = %lu"),
604 wxThread::GetCurrentId(), (unsigned long)m_count
);
609 return wxSEMA_NO_ERROR
;
612 wxSemaError
wxSemaphoreInternal::TryWait()
614 wxMutexLocker
locker(m_mutex
);
621 return wxSEMA_NO_ERROR
;
624 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
626 wxMutexLocker
locker(m_mutex
);
628 wxLongLong startTime
= wxGetLocalTimeMillis();
630 while ( m_count
== 0 )
632 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
633 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
634 if ( remainingTime
<= 0 )
637 return wxSEMA_TIMEOUT
;
640 switch ( m_cond
.WaitTimeout(remainingTime
) )
643 return wxSEMA_TIMEOUT
;
646 return wxSEMA_MISC_ERROR
;
648 case wxCOND_NO_ERROR
:
655 return wxSEMA_NO_ERROR
;
658 wxSemaError
wxSemaphoreInternal::Post()
660 wxMutexLocker
locker(m_mutex
);
662 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
664 return wxSEMA_OVERFLOW
;
669 wxLogTrace(TRACE_SEMA
,
670 wxT("Thread %p about to signal semaphore, count = %lu"),
671 wxThread::GetCurrentId(), (unsigned long)m_count
);
673 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
677 // ===========================================================================
678 // wxThread implementation
679 // ===========================================================================
681 // the thread callback functions must have the C linkage
685 #ifdef wxHAVE_PTHREAD_CLEANUP
686 // thread exit function
687 void wxPthreadCleanup(void *ptr
);
688 #endif // wxHAVE_PTHREAD_CLEANUP
690 void *wxPthreadStart(void *ptr
);
694 // ----------------------------------------------------------------------------
696 // ----------------------------------------------------------------------------
698 class wxThreadInternal
704 // thread entry function
705 static void *PthreadStart(wxThread
*thread
);
710 // unblock the thread allowing it to run
711 void SignalRun() { m_semRun
.Post(); }
712 // ask the thread to terminate
714 // go to sleep until Resume() is called
721 int GetPriority() const { return m_prio
; }
722 void SetPriority(int prio
) { m_prio
= prio
; }
724 wxThreadState
GetState() const { return m_state
; }
725 void SetState(wxThreadState state
)
728 static const wxChar
*stateNames
[] =
736 wxLogTrace(TRACE_THREADS
, wxT("Thread %p: %s => %s."),
737 GetId(), stateNames
[m_state
], stateNames
[state
]);
738 #endif // wxUSE_LOG_TRACE
743 pthread_t
GetId() const { return m_threadId
; }
744 pthread_t
*GetIdPtr() { return &m_threadId
; }
746 void SetCancelFlag() { m_cancelled
= true; }
747 bool WasCancelled() const { return m_cancelled
; }
749 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
750 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
753 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
754 bool IsReallyPaused() const { return m_isPaused
; }
756 // tell the thread that it is a detached one
759 wxCriticalSectionLocker
lock(m_csJoinFlag
);
761 m_shouldBeJoined
= false;
765 #ifdef wxHAVE_PTHREAD_CLEANUP
766 // this is used by wxPthreadCleanup() only
767 static void Cleanup(wxThread
*thread
);
768 #endif // wxHAVE_PTHREAD_CLEANUP
771 pthread_t m_threadId
; // id of the thread
772 wxThreadState m_state
; // see wxThreadState enum
773 int m_prio
; // in wxWidgets units: from 0 to 100
775 // this flag is set when the thread should terminate
778 // this flag is set when the thread is blocking on m_semSuspend
781 // the thread exit code - only used for joinable (!detached) threads and
782 // is only valid after the thread termination
783 wxThread::ExitCode m_exitcode
;
785 // many threads may call Wait(), but only one of them should call
786 // pthread_join(), so we have to keep track of this
787 wxCriticalSection m_csJoinFlag
;
788 bool m_shouldBeJoined
;
791 // this semaphore is posted by Run() and the threads Entry() is not
792 // called before it is done
793 wxSemaphore m_semRun
;
795 // this one is signaled when the thread should resume after having been
797 wxSemaphore m_semSuspend
;
800 // ----------------------------------------------------------------------------
801 // thread startup and exit functions
802 // ----------------------------------------------------------------------------
804 void *wxPthreadStart(void *ptr
)
806 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
809 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
811 wxThreadInternal
*pthread
= thread
->m_internal
;
813 wxLogTrace(TRACE_THREADS
, wxT("Thread %p started."), THR_ID(pthread
));
815 // associate the thread pointer with the newly created thread so that
816 // wxThread::This() will work
817 int rc
= pthread_setspecific(gs_keySelf
, thread
);
820 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
825 // have to declare this before pthread_cleanup_push() which defines a
829 #ifdef wxHAVE_PTHREAD_CLEANUP
830 // install the cleanup handler which will be called if the thread is
832 pthread_cleanup_push(wxPthreadCleanup
, thread
);
833 #endif // wxHAVE_PTHREAD_CLEANUP
835 // wait for the semaphore to be posted from Run()
836 pthread
->m_semRun
.Wait();
838 // test whether we should run the run at all - may be it was deleted
839 // before it started to Run()?
841 wxCriticalSectionLocker
lock(thread
->m_critsect
);
843 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
844 pthread
->WasCancelled();
849 // call the main entry
850 wxLogTrace(TRACE_THREADS
,
851 wxT("Thread %p about to enter its Entry()."),
856 pthread
->m_exitcode
= thread
->Entry();
858 wxLogTrace(TRACE_THREADS
,
859 wxT("Thread %p Entry() returned %lu."),
860 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
862 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
865 wxCriticalSectionLocker
lock(thread
->m_critsect
);
867 // change the state of the thread to "exited" so that
868 // wxPthreadCleanup handler won't do anything from now (if it's
869 // called before we do pthread_cleanup_pop below)
870 pthread
->SetState(STATE_EXITED
);
874 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
875 // '}' for the '{' in push, so they must be used in the same block!
876 #ifdef wxHAVE_PTHREAD_CLEANUP
878 // under Tru64 we get a warning from macro expansion
880 #pragma message disable(declbutnotref)
883 // remove the cleanup handler without executing it
884 pthread_cleanup_pop(FALSE
);
887 #pragma message restore
889 #endif // wxHAVE_PTHREAD_CLEANUP
893 // FIXME: deleting a possibly joinable thread here???
896 return EXITCODE_CANCELLED
;
900 // terminate the thread
901 thread
->Exit(pthread
->m_exitcode
);
903 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
909 #ifdef wxHAVE_PTHREAD_CLEANUP
911 // this handler is called when the thread is cancelled
912 extern "C" void wxPthreadCleanup(void *ptr
)
914 wxThreadInternal::Cleanup((wxThread
*)ptr
);
917 void wxThreadInternal::Cleanup(wxThread
*thread
)
919 if (pthread_getspecific(gs_keySelf
) == 0) return;
921 wxCriticalSectionLocker
lock(thread
->m_critsect
);
922 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
924 // thread is already considered as finished.
929 // exit the thread gracefully
930 thread
->Exit(EXITCODE_CANCELLED
);
933 #endif // wxHAVE_PTHREAD_CLEANUP
935 // ----------------------------------------------------------------------------
937 // ----------------------------------------------------------------------------
939 wxThreadInternal::wxThreadInternal()
943 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
947 // set to true only when the thread starts waiting on m_semSuspend
950 // defaults for joinable threads
951 m_shouldBeJoined
= true;
952 m_isDetached
= false;
955 wxThreadInternal::~wxThreadInternal()
959 wxThreadError
wxThreadInternal::Run()
961 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
962 wxT("thread may only be started once after Create()") );
964 SetState(STATE_RUNNING
);
966 // wake up threads waiting for our start
969 return wxTHREAD_NO_ERROR
;
972 void wxThreadInternal::Wait()
974 wxCHECK_RET( !m_isDetached
, wxT("can't wait for a detached thread") );
976 // if the thread we're waiting for is waiting for the GUI mutex, we will
977 // deadlock so make sure we release it temporarily
978 if ( wxThread::IsMain() )
981 wxLogTrace(TRACE_THREADS
,
982 wxT("Starting to wait for thread %p to exit."),
985 // to avoid memory leaks we should call pthread_join(), but it must only be
986 // done once so use a critical section to serialize the code below
988 wxCriticalSectionLocker
lock(m_csJoinFlag
);
990 if ( m_shouldBeJoined
)
992 // FIXME shouldn't we set cancellation type to DISABLED here? If
993 // we're cancelled inside pthread_join(), things will almost
994 // certainly break - but if we disable the cancellation, we
996 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
998 // this is a serious problem, so use wxLogError and not
999 // wxLogDebug: it is possible to bring the system to its knees
1000 // by creating too many threads and not joining them quite
1002 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
1005 m_shouldBeJoined
= false;
1009 // reacquire GUI mutex
1010 if ( wxThread::IsMain() )
1014 void wxThreadInternal::Pause()
1016 // the state is set from the thread which pauses us first, this function
1017 // is called later so the state should have been already set
1018 wxCHECK_RET( m_state
== STATE_PAUSED
,
1019 wxT("thread must first be paused with wxThread::Pause().") );
1021 wxLogTrace(TRACE_THREADS
,
1022 wxT("Thread %p goes to sleep."), THR_ID(this));
1024 // wait until the semaphore is Post()ed from Resume()
1025 m_semSuspend
.Wait();
1028 void wxThreadInternal::Resume()
1030 wxCHECK_RET( m_state
== STATE_PAUSED
,
1031 wxT("can't resume thread which is not suspended.") );
1033 // the thread might be not actually paused yet - if there were no call to
1034 // TestDestroy() since the last call to Pause() for example
1035 if ( IsReallyPaused() )
1037 wxLogTrace(TRACE_THREADS
,
1038 wxT("Waking up thread %p"), THR_ID(this));
1041 m_semSuspend
.Post();
1044 SetReallyPaused(false);
1048 wxLogTrace(TRACE_THREADS
,
1049 wxT("Thread %p is not yet really paused"), THR_ID(this));
1052 SetState(STATE_RUNNING
);
1055 // -----------------------------------------------------------------------------
1056 // wxThread static functions
1057 // -----------------------------------------------------------------------------
1059 wxThread
*wxThread::This()
1061 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1064 void wxThread::Yield()
1066 #ifdef HAVE_SCHED_YIELD
1071 int wxThread::GetCPUCount()
1073 #if defined(_SC_NPROCESSORS_ONLN)
1074 // this works for Solaris and Linux 2.6
1075 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1080 #elif defined(__LINUX__) && wxUSE_FFILE
1081 // read from proc (can't use wxTextFile here because it's a special file:
1082 // it has 0 size but still can be read from)
1085 wxFFile
file(wxT("/proc/cpuinfo"));
1086 if ( file
.IsOpened() )
1088 // slurp the whole file
1090 if ( file
.ReadAll(&s
) )
1092 // (ab)use Replace() to find the number of "processor: num" strings
1093 size_t count
= s
.Replace(wxT("processor\t:"), wxT(""));
1099 wxLogDebug(wxT("failed to parse /proc/cpuinfo"));
1103 wxLogDebug(wxT("failed to read /proc/cpuinfo"));
1106 #endif // different ways to get number of CPUs
1112 wxThreadIdType
wxThread::GetCurrentId()
1114 return (wxThreadIdType
)pthread_self();
1118 bool wxThread::SetConcurrency(size_t level
)
1120 #ifdef HAVE_THR_SETCONCURRENCY
1121 int rc
= thr_setconcurrency(level
);
1124 wxLogSysError(rc
, wxT("thr_setconcurrency() failed"));
1128 #else // !HAVE_THR_SETCONCURRENCY
1129 // ok only for the default value
1131 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1134 // -----------------------------------------------------------------------------
1136 // -----------------------------------------------------------------------------
1138 wxThread::wxThread(wxThreadKind kind
)
1140 // add this thread to the global list of all threads
1142 wxMutexLocker
lock(*gs_mutexAllThreads
);
1144 gs_allThreads
.Add(this);
1147 m_internal
= new wxThreadInternal();
1149 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1152 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1153 #define WXUNUSED_STACKSIZE(identifier) identifier
1155 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1158 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1160 if ( m_internal
->GetState() != STATE_NEW
)
1162 // don't recreate thread
1163 return wxTHREAD_RUNNING
;
1166 // set up the thread attribute: right now, we only set thread priority
1167 pthread_attr_t attr
;
1168 pthread_attr_init(&attr
);
1170 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1172 pthread_attr_setstacksize(&attr
, stackSize
);
1175 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1177 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1179 wxLogError(_("Cannot retrieve thread scheduling policy."));
1183 /* the pthread.h contains too many spaces. This is a work-around */
1184 # undef sched_get_priority_max
1185 #undef sched_get_priority_min
1186 #define sched_get_priority_max(_pol_) \
1187 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1188 #define sched_get_priority_min(_pol_) \
1189 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1192 int max_prio
= sched_get_priority_max(policy
),
1193 min_prio
= sched_get_priority_min(policy
),
1194 prio
= m_internal
->GetPriority();
1196 if ( min_prio
== -1 || max_prio
== -1 )
1198 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1201 else if ( max_prio
== min_prio
)
1203 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1205 // notify the programmer that this doesn't work here
1206 wxLogWarning(_("Thread priority setting is ignored."));
1208 //else: we have default priority, so don't complain
1210 // anyhow, don't do anything because priority is just ignored
1214 struct sched_param sp
;
1215 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1217 wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed"));
1220 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1222 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1224 wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed"));
1227 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1229 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1230 // this will make the threads created by this process really concurrent
1231 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1233 wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1235 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1237 // VZ: assume that this one is always available (it's rather fundamental),
1238 // if this function is ever missing we should try to use
1239 // pthread_detach() instead (after thread creation)
1242 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1244 wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed"));
1247 // never try to join detached threads
1248 m_internal
->Detach();
1250 //else: threads are created joinable by default, it's ok
1252 // create the new OS thread object
1253 int rc
= pthread_create
1255 m_internal
->GetIdPtr(),
1261 if ( pthread_attr_destroy(&attr
) != 0 )
1263 wxFAIL_MSG(wxT("pthread_attr_destroy() failed"));
1268 m_internal
->SetState(STATE_EXITED
);
1270 return wxTHREAD_NO_RESOURCE
;
1273 return wxTHREAD_NO_ERROR
;
1276 wxThreadError
wxThread::Run()
1278 wxCriticalSectionLocker
lock(m_critsect
);
1280 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1281 wxT("must call wxThread::Create() first") );
1283 return m_internal
->Run();
1286 // -----------------------------------------------------------------------------
1288 // -----------------------------------------------------------------------------
1290 void wxThread::SetPriority(unsigned int prio
)
1292 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1293 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1294 wxT("invalid thread priority") );
1296 wxCriticalSectionLocker
lock(m_critsect
);
1298 switch ( m_internal
->GetState() )
1301 // thread not yet started, priority will be set when it is
1302 m_internal
->SetPriority(prio
);
1307 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1308 #if defined(__LINUX__)
1309 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1310 // a priority other than 0. Instead, we use the BSD setpriority
1311 // which alllows us to set a 'nice' value between 20 to -20. Only
1312 // super user can set a value less than zero (more negative yields
1313 // higher priority). setpriority set the static priority of a
1314 // process, but this is OK since Linux is configured as a thread
1317 // FIXME this is not true for 2.6!!
1319 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1320 // to Unix priorities 20..-20
1321 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1323 wxLogError(_("Failed to set thread priority %d."), prio
);
1327 struct sched_param sparam
;
1328 sparam
.sched_priority
= prio
;
1330 if ( pthread_setschedparam(m_internal
->GetId(),
1331 SCHED_OTHER
, &sparam
) != 0 )
1333 wxLogError(_("Failed to set thread priority %d."), prio
);
1337 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1342 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1346 unsigned int wxThread::GetPriority() const
1348 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1350 return m_internal
->GetPriority();
1353 wxThreadIdType
wxThread::GetId() const
1355 return (wxThreadIdType
) m_internal
->GetId();
1358 // -----------------------------------------------------------------------------
1360 // -----------------------------------------------------------------------------
1362 wxThreadError
wxThread::Pause()
1364 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1365 wxT("a thread can't pause itself") );
1367 wxCriticalSectionLocker
lock(m_critsect
);
1369 if ( m_internal
->GetState() != STATE_RUNNING
)
1371 wxLogDebug(wxT("Can't pause thread which is not running."));
1373 return wxTHREAD_NOT_RUNNING
;
1376 // just set a flag, the thread will be really paused only during the next
1377 // call to TestDestroy()
1378 m_internal
->SetState(STATE_PAUSED
);
1380 return wxTHREAD_NO_ERROR
;
1383 wxThreadError
wxThread::Resume()
1385 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1386 wxT("a thread can't resume itself") );
1388 wxCriticalSectionLocker
lock(m_critsect
);
1390 wxThreadState state
= m_internal
->GetState();
1395 wxLogTrace(TRACE_THREADS
, wxT("Thread %p suspended, resuming."),
1398 m_internal
->Resume();
1400 return wxTHREAD_NO_ERROR
;
1403 wxLogTrace(TRACE_THREADS
, wxT("Thread %p exited, won't resume."),
1405 return wxTHREAD_NO_ERROR
;
1408 wxLogDebug(wxT("Attempt to resume a thread which is not paused."));
1410 return wxTHREAD_MISC_ERROR
;
1414 // -----------------------------------------------------------------------------
1416 // -----------------------------------------------------------------------------
1418 wxThread::ExitCode
wxThread::Wait()
1420 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1421 wxT("a thread can't wait for itself") );
1423 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1424 wxT("can't wait for detached thread") );
1428 return m_internal
->GetExitCode();
1431 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1433 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1434 wxT("a thread can't delete itself") );
1436 bool isDetached
= m_isDetached
;
1439 wxThreadState state
= m_internal
->GetState();
1441 // ask the thread to stop
1442 m_internal
->SetCancelFlag();
1449 // we need to wake up the thread so that PthreadStart() will
1450 // terminate - right now it's blocking on run semaphore in
1452 m_internal
->SignalRun();
1461 // resume the thread first
1462 m_internal
->Resume();
1469 // wait until the thread stops
1474 // return the exit code of the thread
1475 *rc
= m_internal
->GetExitCode();
1478 //else: can't wait for detached threads
1481 return wxTHREAD_NO_ERROR
;
1484 wxThreadError
wxThread::Kill()
1486 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1487 wxT("a thread can't kill itself") );
1489 switch ( m_internal
->GetState() )
1493 return wxTHREAD_NOT_RUNNING
;
1496 // resume the thread first
1502 #ifdef HAVE_PTHREAD_CANCEL
1503 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1504 #endif // HAVE_PTHREAD_CANCEL
1506 wxLogError(_("Failed to terminate a thread."));
1508 return wxTHREAD_MISC_ERROR
;
1511 #ifdef HAVE_PTHREAD_CANCEL
1514 // if we use cleanup function, this will be done from
1515 // wxPthreadCleanup()
1516 #ifndef wxHAVE_PTHREAD_CLEANUP
1517 ScheduleThreadForDeletion();
1519 // don't call OnExit() here, it can only be called in the
1520 // threads context and we're in the context of another thread
1523 #endif // wxHAVE_PTHREAD_CLEANUP
1527 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1530 return wxTHREAD_NO_ERROR
;
1531 #endif // HAVE_PTHREAD_CANCEL
1535 void wxThread::Exit(ExitCode status
)
1537 wxASSERT_MSG( This() == this,
1538 wxT("wxThread::Exit() can only be called in the context of the same thread") );
1542 // from the moment we call OnExit(), the main program may terminate at
1543 // any moment, so mark this thread as being already in process of being
1544 // deleted or wxThreadModule::OnExit() will try to delete it again
1545 ScheduleThreadForDeletion();
1548 // don't enter m_critsect before calling OnExit() because the user code
1549 // might deadlock if, for example, it signals a condition in OnExit() (a
1550 // common case) while the main thread calls any of functions entering
1551 // m_critsect on us (almost all of them do)
1556 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1558 // delete C++ thread object if this is a detached thread - user is
1559 // responsible for doing this for joinable ones
1562 // FIXME I'm feeling bad about it - what if another thread function is
1563 // called (in another thread context) now? It will try to access
1564 // half destroyed object which will probably result in something
1565 // very bad - but we can't protect this by a crit section unless
1566 // we make it a global object, but this would mean that we can
1567 // only call one thread function at a time :-(
1569 pthread_setspecific(gs_keySelf
, 0);
1574 m_internal
->SetState(STATE_EXITED
);
1578 // terminate the thread (pthread_exit() never returns)
1579 pthread_exit(status
);
1581 wxFAIL_MSG(wxT("pthread_exit() failed"));
1584 // also test whether we were paused
1585 bool wxThread::TestDestroy()
1587 wxASSERT_MSG( This() == this,
1588 wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
1592 if ( m_internal
->GetState() == STATE_PAUSED
)
1594 m_internal
->SetReallyPaused(true);
1596 // leave the crit section or the other threads will stop too if they
1597 // try to call any of (seemingly harmless) IsXXX() functions while we
1601 m_internal
->Pause();
1605 // thread wasn't requested to pause, nothing to do
1609 return m_internal
->WasCancelled();
1612 wxThread::~wxThread()
1616 // check that the thread either exited or couldn't be created
1617 if ( m_internal
->GetState() != STATE_EXITED
&&
1618 m_internal
->GetState() != STATE_NEW
)
1620 wxLogDebug(wxT("The thread %ld is being destroyed although it is still running! The application may crash."),
1628 // remove this thread from the global array
1630 wxMutexLocker
lock(*gs_mutexAllThreads
);
1632 gs_allThreads
.Remove(this);
1636 // -----------------------------------------------------------------------------
1638 // -----------------------------------------------------------------------------
1640 bool wxThread::IsRunning() const
1642 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1644 return m_internal
->GetState() == STATE_RUNNING
;
1647 bool wxThread::IsAlive() const
1649 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1651 switch ( m_internal
->GetState() )
1662 bool wxThread::IsPaused() const
1664 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1666 return (m_internal
->GetState() == STATE_PAUSED
);
1669 //--------------------------------------------------------------------
1671 //--------------------------------------------------------------------
1673 class wxThreadModule
: public wxModule
1676 virtual bool OnInit();
1677 virtual void OnExit();
1680 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1683 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1685 bool wxThreadModule::OnInit()
1687 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1690 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1695 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1697 gs_mutexAllThreads
= new wxMutex();
1699 gs_mutexGui
= new wxMutex();
1700 gs_mutexGui
->Lock();
1702 gs_mutexDeleteThread
= new wxMutex();
1703 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1708 void wxThreadModule::OnExit()
1710 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1712 // are there any threads left which are being deleted right now?
1713 size_t nThreadsBeingDeleted
;
1716 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1717 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1719 if ( nThreadsBeingDeleted
> 0 )
1721 wxLogTrace(TRACE_THREADS
,
1722 wxT("Waiting for %lu threads to disappear"),
1723 (unsigned long)nThreadsBeingDeleted
);
1725 // have to wait until all of them disappear
1726 gs_condAllDeleted
->Wait();
1733 wxMutexLocker
lock(*gs_mutexAllThreads
);
1735 // terminate any threads left
1736 count
= gs_allThreads
.GetCount();
1739 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1740 (unsigned long)count
);
1742 } // unlock mutex before deleting the threads as they lock it in their dtor
1744 for ( size_t n
= 0u; n
< count
; n
++ )
1746 // Delete calls the destructor which removes the current entry. We
1747 // should only delete the first one each time.
1748 gs_allThreads
[0]->Delete();
1751 delete gs_mutexAllThreads
;
1753 // destroy GUI mutex
1754 gs_mutexGui
->Unlock();
1757 // and free TLD slot
1758 (void)pthread_key_delete(gs_keySelf
);
1760 delete gs_condAllDeleted
;
1761 delete gs_mutexDeleteThread
;
1764 // ----------------------------------------------------------------------------
1766 // ----------------------------------------------------------------------------
1768 static void ScheduleThreadForDeletion()
1770 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1772 gs_nThreadsBeingDeleted
++;
1774 wxLogTrace(TRACE_THREADS
, wxT("%lu thread%s waiting to be deleted"),
1775 (unsigned long)gs_nThreadsBeingDeleted
,
1776 gs_nThreadsBeingDeleted
== 1 ? wxT("") : wxT("s"));
1779 static void DeleteThread(wxThread
*This
)
1781 // gs_mutexDeleteThread should be unlocked before signalling the condition
1782 // or wxThreadModule::OnExit() would deadlock
1783 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1785 wxLogTrace(TRACE_THREADS
, wxT("Thread %p auto deletes."), This
->GetId());
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