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 #ifdef HAVE_ABI_FORCEDUNWIND
61 // we use wxFFile under Linux in GetCPUCount()
64 #include <sys/resource.h> // for setpriority()
67 #define THR_ID_CAST(id) (reinterpret_cast<void*>(id))
68 #define THR_ID(thr) THR_ID_CAST((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
;
142 // this mutex must be acquired before any call to a GUI function
143 // (it's not inside #if wxUSE_GUI because this file is compiled as part
145 static wxMutex
*gs_mutexGui
= NULL
;
148 // when we wait for a thread to exit, we're blocking on a condition which the
149 // thread signals in its SignalExit() method -- but this condition can't be a
150 // member of the thread itself as a detached thread may delete itself at any
151 // moment and accessing the condition member of the thread after this would
152 // result in a disaster
154 // so instead we maintain a global list of the structs below for the threads
155 // we're interested in waiting on
157 // ============================================================================
158 // wxMutex implementation
159 // ============================================================================
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 // this is a simple wrapper around pthread_mutex_t which provides error
167 class wxMutexInternal
170 wxMutexInternal(wxMutexType mutexType
);
174 wxMutexError
Lock(unsigned long ms
);
175 wxMutexError
TryLock();
176 wxMutexError
Unlock();
178 bool IsOk() const { return m_isOk
; }
181 // convert the result of pthread_mutex_[timed]lock() call to wx return code
182 wxMutexError
HandleLockResult(int err
);
185 pthread_mutex_t m_mutex
;
188 unsigned long m_owningThread
;
190 // wxConditionInternal uses our m_mutex
191 friend class wxConditionInternal
;
194 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
195 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
196 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
197 // in the library, otherwise we wouldn't compile this code at all)
198 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
201 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
209 case wxMUTEX_RECURSIVE
:
210 // support recursive locks like Win32, i.e. a thread can lock a
211 // mutex which it had itself already locked
213 // unfortunately initialization of recursive mutexes is non
214 // portable, so try several methods
215 #ifdef HAVE_PTHREAD_MUTEXATTR_T
217 pthread_mutexattr_t attr
;
218 pthread_mutexattr_init(&attr
);
219 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
221 err
= pthread_mutex_init(&m_mutex
, &attr
);
223 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
224 // we can use this only as initializer so we have to assign it
225 // first to a temp var - assigning directly to m_mutex wouldn't
228 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
231 #else // no recursive mutexes
233 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
237 wxFAIL_MSG( wxT("unknown mutex type") );
240 case wxMUTEX_DEFAULT
:
241 err
= pthread_mutex_init(&m_mutex
, NULL
);
248 wxLogApiError( wxT("pthread_mutex_init()"), err
);
252 wxMutexInternal::~wxMutexInternal()
256 int err
= pthread_mutex_destroy(&m_mutex
);
259 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
264 wxMutexError
wxMutexInternal::Lock()
266 if ((m_type
== wxMUTEX_DEFAULT
) && (m_owningThread
!= 0))
268 if (m_owningThread
== wxThread::GetCurrentId())
269 return wxMUTEX_DEAD_LOCK
;
272 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
275 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
277 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
278 static const long MSEC_IN_SEC
= 1000;
279 static const long NSEC_IN_MSEC
= 1000000;
280 static const long NSEC_IN_USEC
= 1000;
281 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
283 time_t seconds
= ms
/MSEC_IN_SEC
;
284 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
285 timespec ts
= { 0, 0 };
287 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
288 // function is in librt and we don't link with it currently, so use
289 // gettimeofday() instead -- if it turns out that this is really too
290 // imprecise, we should modify configure to check if clock_gettime() is
291 // available and whether it requires -lrt and use it instead
293 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
298 if ( wxGetTimeOfDay(&tv
) != -1 )
300 ts
.tv_sec
= tv
.tv_sec
;
301 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
304 else // fall back on system timer
306 ts
.tv_sec
= time(NULL
);
309 ts
.tv_sec
+= seconds
;
310 ts
.tv_nsec
+= nanoseconds
;
311 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
314 ts
.tv_nsec
-= NSEC_IN_SEC
;
317 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
318 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
321 return wxMUTEX_MISC_ERROR
;
322 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
325 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
327 // wxPrintf( "err %d\n", err );
332 // only error checking mutexes return this value and so it's an
333 // unexpected situation -- hence use assert, not wxLogDebug
334 wxFAIL_MSG( wxT("mutex deadlock prevented") );
335 return wxMUTEX_DEAD_LOCK
;
338 wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized"));
342 return wxMUTEX_TIMEOUT
;
345 if (m_type
== wxMUTEX_DEFAULT
)
346 m_owningThread
= wxThread::GetCurrentId();
347 return wxMUTEX_NO_ERROR
;
350 wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err
);
353 return wxMUTEX_MISC_ERROR
;
357 wxMutexError
wxMutexInternal::TryLock()
359 int err
= pthread_mutex_trylock(&m_mutex
);
363 // not an error: mutex is already locked, but we're prepared for
368 wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized."));
372 if (m_type
== wxMUTEX_DEFAULT
)
373 m_owningThread
= wxThread::GetCurrentId();
374 return wxMUTEX_NO_ERROR
;
377 wxLogApiError(wxT("pthread_mutex_trylock()"), err
);
380 return wxMUTEX_MISC_ERROR
;
383 wxMutexError
wxMutexInternal::Unlock()
387 int err
= pthread_mutex_unlock(&m_mutex
);
391 // we don't own the mutex
392 return wxMUTEX_UNLOCKED
;
395 wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized."));
399 return wxMUTEX_NO_ERROR
;
402 wxLogApiError(wxT("pthread_mutex_unlock()"), err
);
405 return wxMUTEX_MISC_ERROR
;
408 // ===========================================================================
409 // wxCondition implementation
410 // ===========================================================================
412 // ---------------------------------------------------------------------------
413 // wxConditionInternal
414 // ---------------------------------------------------------------------------
416 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
417 // with a pthread_mutex_t)
418 class wxConditionInternal
421 wxConditionInternal(wxMutex
& mutex
);
422 ~wxConditionInternal();
424 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
427 wxCondError
WaitTimeout(unsigned long milliseconds
);
429 wxCondError
Signal();
430 wxCondError
Broadcast();
433 // get the POSIX mutex associated with us
434 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
437 pthread_cond_t m_cond
;
442 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
445 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
451 wxLogApiError(wxT("pthread_cond_init()"), err
);
455 wxConditionInternal::~wxConditionInternal()
459 int err
= pthread_cond_destroy(&m_cond
);
462 wxLogApiError(wxT("pthread_cond_destroy()"), err
);
467 wxCondError
wxConditionInternal::Wait()
469 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
472 wxLogApiError(wxT("pthread_cond_wait()"), err
);
474 return wxCOND_MISC_ERROR
;
477 return wxCOND_NO_ERROR
;
480 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
482 wxLongLong curtime
= wxGetUTCTimeMillis();
483 curtime
+= milliseconds
;
484 wxLongLong temp
= curtime
/ 1000;
485 int sec
= temp
.GetLo();
487 temp
= curtime
- temp
;
488 int millis
= temp
.GetLo();
493 tspec
.tv_nsec
= millis
* 1000L * 1000L;
495 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
499 return wxCOND_TIMEOUT
;
502 return wxCOND_NO_ERROR
;
505 wxLogApiError(wxT("pthread_cond_timedwait()"), err
);
508 return wxCOND_MISC_ERROR
;
511 wxCondError
wxConditionInternal::Signal()
513 int err
= pthread_cond_signal(&m_cond
);
516 wxLogApiError(wxT("pthread_cond_signal()"), err
);
518 return wxCOND_MISC_ERROR
;
521 return wxCOND_NO_ERROR
;
524 wxCondError
wxConditionInternal::Broadcast()
526 int err
= pthread_cond_broadcast(&m_cond
);
529 wxLogApiError(wxT("pthread_cond_broadcast()"), err
);
531 return wxCOND_MISC_ERROR
;
534 return wxCOND_NO_ERROR
;
537 // ===========================================================================
538 // wxSemaphore implementation
539 // ===========================================================================
541 // ---------------------------------------------------------------------------
542 // wxSemaphoreInternal
543 // ---------------------------------------------------------------------------
545 // we implement the semaphores using mutexes and conditions instead of using
546 // the sem_xxx() POSIX functions because they're not widely available and also
547 // because it's impossible to implement WaitTimeout() using them
548 class wxSemaphoreInternal
551 wxSemaphoreInternal(int initialcount
, int maxcount
);
553 bool IsOk() const { return m_isOk
; }
556 wxSemaError
TryWait();
557 wxSemaError
WaitTimeout(unsigned long milliseconds
);
571 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
575 if ( (initialcount
< 0 || maxcount
< 0) ||
576 ((maxcount
> 0) && (initialcount
> maxcount
)) )
578 wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") );
584 m_maxcount
= (size_t)maxcount
;
585 m_count
= (size_t)initialcount
;
588 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
591 wxSemaError
wxSemaphoreInternal::Wait()
593 wxMutexLocker
locker(m_mutex
);
595 while ( m_count
== 0 )
597 wxLogTrace(TRACE_SEMA
,
598 wxT("Thread %p waiting for semaphore to become signalled"),
599 THR_ID_CAST(wxThread::GetCurrentId()));
601 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
602 return wxSEMA_MISC_ERROR
;
604 wxLogTrace(TRACE_SEMA
,
605 wxT("Thread %p finished waiting for semaphore, count = %lu"),
606 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
611 return wxSEMA_NO_ERROR
;
614 wxSemaError
wxSemaphoreInternal::TryWait()
616 wxMutexLocker
locker(m_mutex
);
623 return wxSEMA_NO_ERROR
;
626 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
628 wxMutexLocker
locker(m_mutex
);
630 wxLongLong startTime
= wxGetLocalTimeMillis();
632 while ( m_count
== 0 )
634 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
635 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
636 if ( remainingTime
<= 0 )
639 return wxSEMA_TIMEOUT
;
642 switch ( m_cond
.WaitTimeout(remainingTime
) )
645 return wxSEMA_TIMEOUT
;
648 return wxSEMA_MISC_ERROR
;
650 case wxCOND_NO_ERROR
:
657 return wxSEMA_NO_ERROR
;
660 wxSemaError
wxSemaphoreInternal::Post()
662 wxMutexLocker
locker(m_mutex
);
664 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
666 return wxSEMA_OVERFLOW
;
671 wxLogTrace(TRACE_SEMA
,
672 wxT("Thread %p about to signal semaphore, count = %lu"),
673 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
675 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
679 // ===========================================================================
680 // wxThread implementation
681 // ===========================================================================
683 // the thread callback functions must have the C linkage
687 #ifdef wxHAVE_PTHREAD_CLEANUP
688 // thread exit function
689 void wxPthreadCleanup(void *ptr
);
690 #endif // wxHAVE_PTHREAD_CLEANUP
692 void *wxPthreadStart(void *ptr
);
696 // ----------------------------------------------------------------------------
698 // ----------------------------------------------------------------------------
700 class wxThreadInternal
706 // thread entry function
707 static void *PthreadStart(wxThread
*thread
);
712 // unblock the thread allowing it to run
713 void SignalRun() { m_semRun
.Post(); }
714 // ask the thread to terminate
716 // go to sleep until Resume() is called
723 int GetPriority() const { return m_prio
; }
724 void SetPriority(int prio
) { m_prio
= prio
; }
726 wxThreadState
GetState() const { return m_state
; }
727 void SetState(wxThreadState state
)
730 static const wxChar
*const stateNames
[] =
738 wxLogTrace(TRACE_THREADS
, wxT("Thread %p: %s => %s."),
739 THR_ID(this), stateNames
[m_state
], stateNames
[state
]);
740 #endif // wxUSE_LOG_TRACE
745 pthread_t
GetId() const { return m_threadId
; }
746 pthread_t
*GetIdPtr() { return &m_threadId
; }
748 void SetCancelFlag() { m_cancelled
= true; }
749 bool WasCancelled() const { return m_cancelled
; }
751 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
752 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
755 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
756 bool IsReallyPaused() const { return m_isPaused
; }
758 // tell the thread that it is a detached one
761 wxCriticalSectionLocker
lock(m_csJoinFlag
);
763 m_shouldBeJoined
= false;
767 #ifdef wxHAVE_PTHREAD_CLEANUP
768 // this is used by wxPthreadCleanup() only
769 static void Cleanup(wxThread
*thread
);
770 #endif // wxHAVE_PTHREAD_CLEANUP
773 pthread_t m_threadId
; // id of the thread
774 wxThreadState m_state
; // see wxThreadState enum
775 int m_prio
; // in wxWidgets units: from 0 to 100
777 // this flag is set when the thread should terminate
780 // this flag is set when the thread is blocking on m_semSuspend
783 // the thread exit code - only used for joinable (!detached) threads and
784 // is only valid after the thread termination
785 wxThread::ExitCode m_exitcode
;
787 // many threads may call Wait(), but only one of them should call
788 // pthread_join(), so we have to keep track of this
789 wxCriticalSection m_csJoinFlag
;
790 bool m_shouldBeJoined
;
793 // this semaphore is posted by Run() and the threads Entry() is not
794 // called before it is done
795 wxSemaphore m_semRun
;
797 // this one is signaled when the thread should resume after having been
799 wxSemaphore m_semSuspend
;
802 // ----------------------------------------------------------------------------
803 // thread startup and exit functions
804 // ----------------------------------------------------------------------------
806 void *wxPthreadStart(void *ptr
)
808 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
811 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
813 wxThreadInternal
*pthread
= thread
->m_internal
;
815 wxLogTrace(TRACE_THREADS
, wxT("Thread %p started."), THR_ID(pthread
));
817 // associate the thread pointer with the newly created thread so that
818 // wxThread::This() will work
819 int rc
= pthread_setspecific(gs_keySelf
, thread
);
822 wxLogSysError(rc
, _("Cannot start thread: error writing TLS."));
827 // have to declare this before pthread_cleanup_push() which defines a
831 #ifdef wxHAVE_PTHREAD_CLEANUP
832 // install the cleanup handler which will be called if the thread is
834 pthread_cleanup_push(wxPthreadCleanup
, thread
);
835 #endif // wxHAVE_PTHREAD_CLEANUP
837 // wait for the semaphore to be posted from Run()
838 pthread
->m_semRun
.Wait();
840 // test whether we should run the run at all - may be it was deleted
841 // before it started to Run()?
843 wxCriticalSectionLocker
lock(thread
->m_critsect
);
845 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
846 pthread
->WasCancelled();
851 // call the main entry
852 wxLogTrace(TRACE_THREADS
,
853 wxT("Thread %p about to enter its Entry()."),
858 pthread
->m_exitcode
= thread
->Entry();
860 wxLogTrace(TRACE_THREADS
,
861 wxT("Thread %p Entry() returned %lu."),
862 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
864 #ifdef HAVE_ABI_FORCEDUNWIND
865 // When using common C++ ABI under Linux we must always rethrow this
866 // special exception used to unwind the stack when the thread was
867 // cancelled, otherwise the thread library would simply terminate the
868 // program, see http://udrepper.livejournal.com/21541.html
869 catch ( abi::__forced_unwind
& )
871 wxCriticalSectionLocker
lock(thread
->m_critsect
);
872 pthread
->SetState(STATE_EXITED
);
875 #endif // HAVE_ABI_FORCEDUNWIND
876 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
879 wxCriticalSectionLocker
lock(thread
->m_critsect
);
881 // change the state of the thread to "exited" so that
882 // wxPthreadCleanup handler won't do anything from now (if it's
883 // called before we do pthread_cleanup_pop below)
884 pthread
->SetState(STATE_EXITED
);
888 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
889 // '}' for the '{' in push, so they must be used in the same block!
890 #ifdef wxHAVE_PTHREAD_CLEANUP
892 // under Tru64 we get a warning from macro expansion
894 #pragma message disable(declbutnotref)
897 // remove the cleanup handler without executing it
898 pthread_cleanup_pop(FALSE
);
901 #pragma message restore
903 #endif // wxHAVE_PTHREAD_CLEANUP
907 // FIXME: deleting a possibly joinable thread here???
910 return EXITCODE_CANCELLED
;
914 // terminate the thread
915 thread
->Exit(pthread
->m_exitcode
);
917 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
923 #ifdef wxHAVE_PTHREAD_CLEANUP
925 // this handler is called when the thread is cancelled
926 extern "C" void wxPthreadCleanup(void *ptr
)
928 wxThreadInternal::Cleanup((wxThread
*)ptr
);
931 void wxThreadInternal::Cleanup(wxThread
*thread
)
933 if (pthread_getspecific(gs_keySelf
) == 0) return;
935 wxCriticalSectionLocker
lock(thread
->m_critsect
);
936 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
938 // thread is already considered as finished.
943 // exit the thread gracefully
944 thread
->Exit(EXITCODE_CANCELLED
);
947 #endif // wxHAVE_PTHREAD_CLEANUP
949 // ----------------------------------------------------------------------------
951 // ----------------------------------------------------------------------------
953 wxThreadInternal::wxThreadInternal()
957 m_prio
= wxPRIORITY_DEFAULT
;
961 // set to true only when the thread starts waiting on m_semSuspend
964 // defaults for joinable threads
965 m_shouldBeJoined
= true;
966 m_isDetached
= false;
969 wxThreadInternal::~wxThreadInternal()
973 wxThreadError
wxThreadInternal::Run()
975 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
976 wxT("thread may only be started once after Create()") );
978 SetState(STATE_RUNNING
);
980 // wake up threads waiting for our start
983 return wxTHREAD_NO_ERROR
;
986 void wxThreadInternal::Wait()
988 wxCHECK_RET( !m_isDetached
, wxT("can't wait for a detached thread") );
990 // if the thread we're waiting for is waiting for the GUI mutex, we will
991 // deadlock so make sure we release it temporarily
992 if ( wxThread::IsMain() )
995 // give the thread we're waiting for chance to do the GUI call
996 // it might be in, we don't do this conditionally as the to be waited on
997 // thread might have to acquire the mutex later but before terminating
998 if ( wxGuiOwnedByMainThread() )
1005 wxLogTrace(TRACE_THREADS
,
1006 wxT("Starting to wait for thread %p to exit."),
1009 // to avoid memory leaks we should call pthread_join(), but it must only be
1010 // done once so use a critical section to serialize the code below
1012 wxCriticalSectionLocker
lock(m_csJoinFlag
);
1014 if ( m_shouldBeJoined
)
1016 // FIXME shouldn't we set cancellation type to DISABLED here? If
1017 // we're cancelled inside pthread_join(), things will almost
1018 // certainly break - but if we disable the cancellation, we
1020 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
1022 // this is a serious problem, so use wxLogError and not
1023 // wxLogDebug: it is possible to bring the system to its knees
1024 // by creating too many threads and not joining them quite
1026 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
1029 m_shouldBeJoined
= false;
1034 // reacquire GUI mutex
1035 if ( wxThread::IsMain() )
1040 void wxThreadInternal::Pause()
1042 // the state is set from the thread which pauses us first, this function
1043 // is called later so the state should have been already set
1044 wxCHECK_RET( m_state
== STATE_PAUSED
,
1045 wxT("thread must first be paused with wxThread::Pause().") );
1047 wxLogTrace(TRACE_THREADS
,
1048 wxT("Thread %p goes to sleep."), THR_ID(this));
1050 // wait until the semaphore is Post()ed from Resume()
1051 m_semSuspend
.Wait();
1054 void wxThreadInternal::Resume()
1056 wxCHECK_RET( m_state
== STATE_PAUSED
,
1057 wxT("can't resume thread which is not suspended.") );
1059 // the thread might be not actually paused yet - if there were no call to
1060 // TestDestroy() since the last call to Pause() for example
1061 if ( IsReallyPaused() )
1063 wxLogTrace(TRACE_THREADS
,
1064 wxT("Waking up thread %p"), THR_ID(this));
1067 m_semSuspend
.Post();
1070 SetReallyPaused(false);
1074 wxLogTrace(TRACE_THREADS
,
1075 wxT("Thread %p is not yet really paused"), THR_ID(this));
1078 SetState(STATE_RUNNING
);
1081 // -----------------------------------------------------------------------------
1082 // wxThread static functions
1083 // -----------------------------------------------------------------------------
1085 wxThread
*wxThread::This()
1087 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1090 void wxThread::Yield()
1092 #ifdef HAVE_SCHED_YIELD
1097 int wxThread::GetCPUCount()
1099 #if defined(_SC_NPROCESSORS_ONLN)
1100 // this works for Solaris and Linux 2.6
1101 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1106 #elif defined(__LINUX__) && wxUSE_FFILE
1107 // read from proc (can't use wxTextFile here because it's a special file:
1108 // it has 0 size but still can be read from)
1111 wxFFile
file(wxT("/proc/cpuinfo"));
1112 if ( file
.IsOpened() )
1114 // slurp the whole file
1116 if ( file
.ReadAll(&s
) )
1118 // (ab)use Replace() to find the number of "processor: num" strings
1119 size_t count
= s
.Replace(wxT("processor\t:"), wxT(""));
1125 wxLogDebug(wxT("failed to parse /proc/cpuinfo"));
1129 wxLogDebug(wxT("failed to read /proc/cpuinfo"));
1132 #endif // different ways to get number of CPUs
1138 wxThreadIdType
wxThread::GetCurrentId()
1140 return (wxThreadIdType
)pthread_self();
1144 bool wxThread::SetConcurrency(size_t level
)
1146 #ifdef HAVE_PTHREAD_SET_CONCURRENCY
1147 int rc
= pthread_setconcurrency( level
);
1148 #elif defined(HAVE_THR_SETCONCURRENCY)
1149 int rc
= thr_setconcurrency(level
);
1150 #else // !HAVE_THR_SETCONCURRENCY
1151 // ok only for the default value
1152 int rc
= level
== 0 ? 0 : -1;
1153 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1157 wxLogSysError(rc
, _("Failed to set thread concurrency level to %lu"),
1158 static_cast<unsigned long>(level
));
1165 // -----------------------------------------------------------------------------
1167 // -----------------------------------------------------------------------------
1169 wxThread::wxThread(wxThreadKind kind
)
1171 // add this thread to the global list of all threads
1173 wxMutexLocker
lock(*gs_mutexAllThreads
);
1175 gs_allThreads
.Add(this);
1178 m_internal
= new wxThreadInternal();
1180 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1183 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1184 #define WXUNUSED_STACKSIZE(identifier) identifier
1186 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1189 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1191 if ( m_internal
->GetState() != STATE_NEW
)
1193 // don't recreate thread
1194 return wxTHREAD_RUNNING
;
1197 // set up the thread attribute: right now, we only set thread priority
1198 pthread_attr_t attr
;
1199 pthread_attr_init(&attr
);
1201 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1203 pthread_attr_setstacksize(&attr
, stackSize
);
1206 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1208 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1210 wxLogError(_("Cannot retrieve thread scheduling policy."));
1214 /* the pthread.h contains too many spaces. This is a work-around */
1215 # undef sched_get_priority_max
1216 #undef sched_get_priority_min
1217 #define sched_get_priority_max(_pol_) \
1218 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1219 #define sched_get_priority_min(_pol_) \
1220 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1223 int max_prio
= sched_get_priority_max(policy
),
1224 min_prio
= sched_get_priority_min(policy
),
1225 prio
= m_internal
->GetPriority();
1227 if ( min_prio
== -1 || max_prio
== -1 )
1229 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1232 else if ( max_prio
== min_prio
)
1234 if ( prio
!= wxPRIORITY_DEFAULT
)
1236 // notify the programmer that this doesn't work here
1237 wxLogWarning(_("Thread priority setting is ignored."));
1239 //else: we have default priority, so don't complain
1241 // anyhow, don't do anything because priority is just ignored
1245 struct sched_param sp
;
1246 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1248 wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed"));
1251 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1253 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1255 wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed"));
1258 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1260 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1261 // this will make the threads created by this process really concurrent
1262 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1264 wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1266 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1268 // VZ: assume that this one is always available (it's rather fundamental),
1269 // if this function is ever missing we should try to use
1270 // pthread_detach() instead (after thread creation)
1273 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1275 wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed"));
1278 // never try to join detached threads
1279 m_internal
->Detach();
1281 //else: threads are created joinable by default, it's ok
1283 // create the new OS thread object
1284 int rc
= pthread_create
1286 m_internal
->GetIdPtr(),
1292 if ( pthread_attr_destroy(&attr
) != 0 )
1294 wxFAIL_MSG(wxT("pthread_attr_destroy() failed"));
1299 m_internal
->SetState(STATE_EXITED
);
1301 return wxTHREAD_NO_RESOURCE
;
1304 return wxTHREAD_NO_ERROR
;
1307 wxThreadError
wxThread::Run()
1309 wxCriticalSectionLocker
lock(m_critsect
);
1311 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1312 wxT("must call wxThread::Create() first") );
1314 return m_internal
->Run();
1317 // -----------------------------------------------------------------------------
1319 // -----------------------------------------------------------------------------
1321 void wxThread::SetPriority(unsigned int prio
)
1323 wxCHECK_RET( wxPRIORITY_MIN
<= prio
&& prio
<= wxPRIORITY_MAX
,
1324 wxT("invalid thread priority") );
1326 wxCriticalSectionLocker
lock(m_critsect
);
1328 switch ( m_internal
->GetState() )
1331 // thread not yet started, priority will be set when it is
1332 m_internal
->SetPriority(prio
);
1337 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1338 #if defined(__LINUX__)
1339 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1340 // a priority other than 0. Instead, we use the BSD setpriority
1341 // which alllows us to set a 'nice' value between 20 to -20. Only
1342 // super user can set a value less than zero (more negative yields
1343 // higher priority). setpriority set the static priority of a
1344 // process, but this is OK since Linux is configured as a thread
1347 // FIXME this is not true for 2.6!!
1349 // map wx priorites 0..100 to Unix priorities 20..-20
1350 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1352 wxLogError(_("Failed to set thread priority %d."), prio
);
1356 struct sched_param sparam
;
1357 sparam
.sched_priority
= prio
;
1359 if ( pthread_setschedparam(m_internal
->GetId(),
1360 SCHED_OTHER
, &sparam
) != 0 )
1362 wxLogError(_("Failed to set thread priority %d."), prio
);
1366 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1371 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1375 unsigned int wxThread::GetPriority() const
1377 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1379 return m_internal
->GetPriority();
1382 wxThreadIdType
wxThread::GetId() const
1384 return (wxThreadIdType
) m_internal
->GetId();
1387 // -----------------------------------------------------------------------------
1389 // -----------------------------------------------------------------------------
1391 wxThreadError
wxThread::Pause()
1393 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1394 wxT("a thread can't pause itself") );
1396 wxCriticalSectionLocker
lock(m_critsect
);
1398 if ( m_internal
->GetState() != STATE_RUNNING
)
1400 wxLogDebug(wxT("Can't pause thread which is not running."));
1402 return wxTHREAD_NOT_RUNNING
;
1405 // just set a flag, the thread will be really paused only during the next
1406 // call to TestDestroy()
1407 m_internal
->SetState(STATE_PAUSED
);
1409 return wxTHREAD_NO_ERROR
;
1412 wxThreadError
wxThread::Resume()
1414 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1415 wxT("a thread can't resume itself") );
1417 wxCriticalSectionLocker
lock(m_critsect
);
1419 wxThreadState state
= m_internal
->GetState();
1424 wxLogTrace(TRACE_THREADS
, wxT("Thread %p suspended, resuming."),
1427 m_internal
->Resume();
1429 return wxTHREAD_NO_ERROR
;
1432 wxLogTrace(TRACE_THREADS
, wxT("Thread %p exited, won't resume."),
1434 return wxTHREAD_NO_ERROR
;
1437 wxLogDebug(wxT("Attempt to resume a thread which is not paused."));
1439 return wxTHREAD_MISC_ERROR
;
1443 // -----------------------------------------------------------------------------
1445 // -----------------------------------------------------------------------------
1447 wxThread::ExitCode
wxThread::Wait(wxThreadWait
WXUNUSED(waitMode
))
1449 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1450 wxT("a thread can't wait for itself") );
1452 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1453 wxT("can't wait for detached thread") );
1457 return m_internal
->GetExitCode();
1460 wxThreadError
wxThread::Delete(ExitCode
*rc
, wxThreadWait
WXUNUSED(waitMode
))
1462 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1463 wxT("a thread can't delete itself") );
1465 bool isDetached
= m_isDetached
;
1468 wxThreadState state
= m_internal
->GetState();
1470 // ask the thread to stop
1471 m_internal
->SetCancelFlag();
1480 // we need to wake up the thread so that PthreadStart() will
1481 // terminate - right now it's blocking on run semaphore in
1483 m_internal
->SignalRun();
1492 // resume the thread first
1493 m_internal
->Resume();
1500 // wait until the thread stops
1505 // return the exit code of the thread
1506 *rc
= m_internal
->GetExitCode();
1509 //else: can't wait for detached threads
1512 if (state
== STATE_NEW
)
1513 return wxTHREAD_MISC_ERROR
;
1514 // for coherency with the MSW implementation, signal the user that
1515 // Delete() was called on a thread which didn't start to run yet.
1517 return wxTHREAD_NO_ERROR
;
1520 wxThreadError
wxThread::Kill()
1522 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1523 wxT("a thread can't kill itself") );
1527 switch ( m_internal
->GetState() )
1531 return wxTHREAD_NOT_RUNNING
;
1534 // resume the thread first
1540 #ifdef HAVE_PTHREAD_CANCEL
1541 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1542 #endif // HAVE_PTHREAD_CANCEL
1544 wxLogError(_("Failed to terminate a thread."));
1546 return wxTHREAD_MISC_ERROR
;
1549 #ifdef HAVE_PTHREAD_CANCEL
1552 // if we use cleanup function, this will be done from
1553 // wxPthreadCleanup()
1554 #ifndef wxHAVE_PTHREAD_CLEANUP
1555 ScheduleThreadForDeletion();
1557 // don't call OnExit() here, it can only be called in the
1558 // threads context and we're in the context of another thread
1561 #endif // wxHAVE_PTHREAD_CLEANUP
1565 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1568 return wxTHREAD_NO_ERROR
;
1569 #endif // HAVE_PTHREAD_CANCEL
1573 void wxThread::Exit(ExitCode status
)
1575 wxASSERT_MSG( This() == this,
1576 wxT("wxThread::Exit() can only be called in the context of the same thread") );
1580 // from the moment we call OnExit(), the main program may terminate at
1581 // any moment, so mark this thread as being already in process of being
1582 // deleted or wxThreadModule::OnExit() will try to delete it again
1583 ScheduleThreadForDeletion();
1586 // don't enter m_critsect before calling OnExit() because the user code
1587 // might deadlock if, for example, it signals a condition in OnExit() (a
1588 // common case) while the main thread calls any of functions entering
1589 // m_critsect on us (almost all of them do)
1594 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1596 // delete C++ thread object if this is a detached thread - user is
1597 // responsible for doing this for joinable ones
1600 // FIXME I'm feeling bad about it - what if another thread function is
1601 // called (in another thread context) now? It will try to access
1602 // half destroyed object which will probably result in something
1603 // very bad - but we can't protect this by a crit section unless
1604 // we make it a global object, but this would mean that we can
1605 // only call one thread function at a time :-(
1607 pthread_setspecific(gs_keySelf
, 0);
1612 m_internal
->SetState(STATE_EXITED
);
1616 // terminate the thread (pthread_exit() never returns)
1617 pthread_exit(status
);
1619 wxFAIL_MSG(wxT("pthread_exit() failed"));
1622 // also test whether we were paused
1623 bool wxThread::TestDestroy()
1625 wxASSERT_MSG( This() == this,
1626 wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
1630 if ( m_internal
->GetState() == STATE_PAUSED
)
1632 m_internal
->SetReallyPaused(true);
1634 // leave the crit section or the other threads will stop too if they
1635 // try to call any of (seemingly harmless) IsXXX() functions while we
1639 m_internal
->Pause();
1643 // thread wasn't requested to pause, nothing to do
1647 return m_internal
->WasCancelled();
1650 wxThread::~wxThread()
1654 // check that the thread either exited or couldn't be created
1655 if ( m_internal
->GetState() != STATE_EXITED
&&
1656 m_internal
->GetState() != STATE_NEW
)
1658 wxLogDebug(wxT("The thread %p is being destroyed although it is still running! The application may crash."),
1666 // remove this thread from the global array
1668 wxMutexLocker
lock(*gs_mutexAllThreads
);
1670 gs_allThreads
.Remove(this);
1674 // -----------------------------------------------------------------------------
1676 // -----------------------------------------------------------------------------
1678 bool wxThread::IsRunning() const
1680 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1682 return m_internal
->GetState() == STATE_RUNNING
;
1685 bool wxThread::IsAlive() const
1687 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1689 switch ( m_internal
->GetState() )
1700 bool wxThread::IsPaused() const
1702 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1704 return (m_internal
->GetState() == STATE_PAUSED
);
1707 //--------------------------------------------------------------------
1709 //--------------------------------------------------------------------
1712 void wxOSXThreadModuleOnInit();
1713 void wxOSXThreadModuleOnExit();
1716 class wxThreadModule
: public wxModule
1719 virtual bool OnInit();
1720 virtual void OnExit();
1723 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1726 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1728 bool wxThreadModule::OnInit()
1730 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1733 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1738 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1740 gs_mutexAllThreads
= new wxMutex();
1743 wxOSXThreadModuleOnInit();
1745 gs_mutexGui
= new wxMutex();
1746 gs_mutexGui
->Lock();
1749 gs_mutexDeleteThread
= new wxMutex();
1750 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1755 void wxThreadModule::OnExit()
1757 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1759 // are there any threads left which are being deleted right now?
1760 size_t nThreadsBeingDeleted
;
1763 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1764 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1766 if ( nThreadsBeingDeleted
> 0 )
1768 wxLogTrace(TRACE_THREADS
,
1769 wxT("Waiting for %lu threads to disappear"),
1770 (unsigned long)nThreadsBeingDeleted
);
1772 // have to wait until all of them disappear
1773 gs_condAllDeleted
->Wait();
1780 wxMutexLocker
lock(*gs_mutexAllThreads
);
1782 // terminate any threads left
1783 count
= gs_allThreads
.GetCount();
1786 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1787 (unsigned long)count
);
1789 } // unlock mutex before deleting the threads as they lock it in their dtor
1791 for ( size_t n
= 0u; n
< count
; n
++ )
1793 // Delete calls the destructor which removes the current entry. We
1794 // should only delete the first one each time.
1795 gs_allThreads
[0]->Delete();
1798 delete gs_mutexAllThreads
;
1801 wxOSXThreadModuleOnExit();
1803 // destroy GUI mutex
1804 gs_mutexGui
->Unlock();
1808 // and free TLD slot
1809 (void)pthread_key_delete(gs_keySelf
);
1811 delete gs_condAllDeleted
;
1812 delete gs_mutexDeleteThread
;
1815 // ----------------------------------------------------------------------------
1817 // ----------------------------------------------------------------------------
1819 static void ScheduleThreadForDeletion()
1821 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1823 gs_nThreadsBeingDeleted
++;
1825 wxLogTrace(TRACE_THREADS
, wxT("%lu thread%s waiting to be deleted"),
1826 (unsigned long)gs_nThreadsBeingDeleted
,
1827 gs_nThreadsBeingDeleted
== 1 ? wxT("") : wxT("s"));
1830 static void DeleteThread(wxThread
*This
)
1832 wxLogTrace(TRACE_THREADS
, wxT("Thread %p auto deletes."), THR_ID(This
));
1836 // only lock gs_mutexDeleteThread after deleting the thread to avoid
1837 // calling out into user code with it locked as this may result in
1838 // deadlocks if the thread dtor deletes another thread (see #11501)
1839 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1841 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1842 wxT("no threads scheduled for deletion, yet we delete one?") );
1844 wxLogTrace(TRACE_THREADS
, wxT("%lu threads remain scheduled for deletion."),
1845 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1847 if ( !--gs_nThreadsBeingDeleted
)
1849 // no more threads left, signal it
1850 gs_condAllDeleted
->Signal();
1856 void wxMutexGuiEnterImpl()
1858 gs_mutexGui
->Lock();
1861 void wxMutexGuiLeaveImpl()
1863 gs_mutexGui
->Unlock();
1868 // ----------------------------------------------------------------------------
1869 // include common implementation code
1870 // ----------------------------------------------------------------------------
1872 #include "wx/thrimpl.cpp"
1874 #endif // wxUSE_THREADS