1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/threadpsx.cpp
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
30 #include "wx/except.h"
34 #include "wx/dynarray.h"
39 #include "wx/stopwatch.h"
40 #include "wx/module.h"
48 #include <sys/time.h> // needed for at least __QNX__
53 #ifdef HAVE_THR_SETCONCURRENCY
57 // we use wxFFile under Linux in GetCPUCount()
60 #include <sys/resource.h> // for setpriority()
63 #define THR_ID_CAST(id) (reinterpret_cast<void*>(id))
64 #define THR_ID(thr) THR_ID_CAST((thr)->GetId())
66 // ----------------------------------------------------------------------------
68 // ----------------------------------------------------------------------------
70 // the possible states of the thread and transitions from them
73 STATE_NEW
, // didn't start execution yet (=> RUNNING)
74 STATE_RUNNING
, // running (=> PAUSED or EXITED)
75 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
76 STATE_EXITED
// thread doesn't exist any more
79 // the exit value of a thread which has been cancelled
80 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
82 // trace mask for wxThread operations
83 #define TRACE_THREADS wxT("thread")
85 // you can get additional debugging messages for the semaphore operations
86 #define TRACE_SEMA wxT("semaphore")
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 static void ScheduleThreadForDeletion();
93 static void DeleteThread(wxThread
*This
);
95 // ----------------------------------------------------------------------------
97 // ----------------------------------------------------------------------------
99 // an (non owning) array of pointers to threads
100 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
102 // an entry for a thread we can wait for
104 // -----------------------------------------------------------------------------
106 // -----------------------------------------------------------------------------
108 // we keep the list of all threads created by the application to be able to
109 // terminate them on exit if there are some left - otherwise the process would
111 static wxArrayThread gs_allThreads
;
113 // a mutex to protect gs_allThreads
114 static wxMutex
*gs_mutexAllThreads
= NULL
;
116 // the id of the main thread
118 // we suppose that 0 is not a valid pthread_t value but in principle this might
119 // be false (e.g. if it's a selector-like value), wxThread::IsMain() would need
120 // to be updated in such case
121 wxThreadIdType
wxThread::ms_idMainThread
= 0;
123 // the key for the pointer to the associated wxThread object
124 static pthread_key_t gs_keySelf
;
126 // the number of threads which are being deleted - the program won't exit
127 // until there are any left
128 static size_t gs_nThreadsBeingDeleted
= 0;
130 // a mutex to protect gs_nThreadsBeingDeleted
131 static wxMutex
*gs_mutexDeleteThread
= NULL
;
133 // and a condition variable which will be signaled when all
134 // gs_nThreadsBeingDeleted will have been deleted
135 static wxCondition
*gs_condAllDeleted
= NULL
;
138 // this mutex must be acquired before any call to a GUI function
139 // (it's not inside #if wxUSE_GUI because this file is compiled as part
141 static wxMutex
*gs_mutexGui
= NULL
;
144 // when we wait for a thread to exit, we're blocking on a condition which the
145 // thread signals in its SignalExit() method -- but this condition can't be a
146 // member of the thread itself as a detached thread may delete itself at any
147 // moment and accessing the condition member of the thread after this would
148 // result in a disaster
150 // so instead we maintain a global list of the structs below for the threads
151 // we're interested in waiting on
153 // ============================================================================
154 // wxMutex implementation
155 // ============================================================================
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 // this is a simple wrapper around pthread_mutex_t which provides error
163 class wxMutexInternal
166 wxMutexInternal(wxMutexType mutexType
);
170 wxMutexError
Lock(unsigned long ms
);
171 wxMutexError
TryLock();
172 wxMutexError
Unlock();
174 bool IsOk() const { return m_isOk
; }
177 // convert the result of pthread_mutex_[timed]lock() call to wx return code
178 wxMutexError
HandleLockResult(int err
);
181 pthread_mutex_t m_mutex
;
184 unsigned long m_owningThread
;
186 // wxConditionInternal uses our m_mutex
187 friend class wxConditionInternal
;
190 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
191 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
192 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
193 // in the library, otherwise we wouldn't compile this code at all)
194 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
197 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
205 case wxMUTEX_RECURSIVE
:
206 // support recursive locks like Win32, i.e. a thread can lock a
207 // mutex which it had itself already locked
209 // unfortunately initialization of recursive mutexes is non
210 // portable, so try several methods
211 #ifdef HAVE_PTHREAD_MUTEXATTR_T
213 pthread_mutexattr_t attr
;
214 pthread_mutexattr_init(&attr
);
215 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
217 err
= pthread_mutex_init(&m_mutex
, &attr
);
219 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
220 // we can use this only as initializer so we have to assign it
221 // first to a temp var - assigning directly to m_mutex wouldn't
224 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
227 #else // no recursive mutexes
229 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
233 wxFAIL_MSG( wxT("unknown mutex type") );
236 case wxMUTEX_DEFAULT
:
237 err
= pthread_mutex_init(&m_mutex
, NULL
);
244 wxLogApiError( wxT("pthread_mutex_init()"), err
);
248 wxMutexInternal::~wxMutexInternal()
252 int err
= pthread_mutex_destroy(&m_mutex
);
255 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
260 wxMutexError
wxMutexInternal::Lock()
262 if ((m_type
== wxMUTEX_DEFAULT
) && (m_owningThread
!= 0))
264 if (m_owningThread
== wxThread::GetCurrentId())
265 return wxMUTEX_DEAD_LOCK
;
268 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
271 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
273 #ifdef HAVE_PTHREAD_MUTEX_TIMEDLOCK
274 static const long MSEC_IN_SEC
= 1000;
275 static const long NSEC_IN_MSEC
= 1000000;
276 static const long NSEC_IN_USEC
= 1000;
277 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
279 time_t seconds
= ms
/MSEC_IN_SEC
;
280 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
281 timespec ts
= { 0, 0 };
283 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
284 // function is in librt and we don't link with it currently, so use
285 // gettimeofday() instead -- if it turns out that this is really too
286 // imprecise, we should modify configure to check if clock_gettime() is
287 // available and whether it requires -lrt and use it instead
289 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
294 if ( wxGetTimeOfDay(&tv
) != -1 )
296 ts
.tv_sec
= tv
.tv_sec
;
297 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
300 else // fall back on system timer
302 ts
.tv_sec
= time(NULL
);
305 ts
.tv_sec
+= seconds
;
306 ts
.tv_nsec
+= nanoseconds
;
307 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
310 ts
.tv_nsec
-= NSEC_IN_SEC
;
313 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
314 #else // !HAVE_PTHREAD_MUTEX_TIMEDLOCK
317 return wxMUTEX_MISC_ERROR
;
318 #endif // HAVE_PTHREAD_MUTEX_TIMEDLOCK/!HAVE_PTHREAD_MUTEX_TIMEDLOCK
321 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
323 // wxPrintf( "err %d\n", err );
328 // only error checking mutexes return this value and so it's an
329 // unexpected situation -- hence use assert, not wxLogDebug
330 wxFAIL_MSG( wxT("mutex deadlock prevented") );
331 return wxMUTEX_DEAD_LOCK
;
334 wxLogDebug(wxT("pthread_mutex_[timed]lock(): mutex not initialized"));
338 return wxMUTEX_TIMEOUT
;
341 if (m_type
== wxMUTEX_DEFAULT
)
342 m_owningThread
= wxThread::GetCurrentId();
343 return wxMUTEX_NO_ERROR
;
346 wxLogApiError(wxT("pthread_mutex_[timed]lock()"), err
);
349 return wxMUTEX_MISC_ERROR
;
353 wxMutexError
wxMutexInternal::TryLock()
355 int err
= pthread_mutex_trylock(&m_mutex
);
359 // not an error: mutex is already locked, but we're prepared for
364 wxLogDebug(wxT("pthread_mutex_trylock(): mutex not initialized."));
368 if (m_type
== wxMUTEX_DEFAULT
)
369 m_owningThread
= wxThread::GetCurrentId();
370 return wxMUTEX_NO_ERROR
;
373 wxLogApiError(wxT("pthread_mutex_trylock()"), err
);
376 return wxMUTEX_MISC_ERROR
;
379 wxMutexError
wxMutexInternal::Unlock()
383 int err
= pthread_mutex_unlock(&m_mutex
);
387 // we don't own the mutex
388 return wxMUTEX_UNLOCKED
;
391 wxLogDebug(wxT("pthread_mutex_unlock(): mutex not initialized."));
395 return wxMUTEX_NO_ERROR
;
398 wxLogApiError(wxT("pthread_mutex_unlock()"), err
);
401 return wxMUTEX_MISC_ERROR
;
404 // ===========================================================================
405 // wxCondition implementation
406 // ===========================================================================
408 // ---------------------------------------------------------------------------
409 // wxConditionInternal
410 // ---------------------------------------------------------------------------
412 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
413 // with a pthread_mutex_t)
414 class wxConditionInternal
417 wxConditionInternal(wxMutex
& mutex
);
418 ~wxConditionInternal();
420 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
423 wxCondError
WaitTimeout(unsigned long milliseconds
);
425 wxCondError
Signal();
426 wxCondError
Broadcast();
429 // get the POSIX mutex associated with us
430 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
433 pthread_cond_t m_cond
;
438 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
441 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
447 wxLogApiError(wxT("pthread_cond_init()"), err
);
451 wxConditionInternal::~wxConditionInternal()
455 int err
= pthread_cond_destroy(&m_cond
);
458 wxLogApiError(wxT("pthread_cond_destroy()"), err
);
463 wxCondError
wxConditionInternal::Wait()
465 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
468 wxLogApiError(wxT("pthread_cond_wait()"), err
);
470 return wxCOND_MISC_ERROR
;
473 return wxCOND_NO_ERROR
;
476 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
478 wxLongLong curtime
= wxGetLocalTimeMillis();
479 curtime
+= milliseconds
;
480 wxLongLong temp
= curtime
/ 1000;
481 int sec
= temp
.GetLo();
483 temp
= curtime
- temp
;
484 int millis
= temp
.GetLo();
489 tspec
.tv_nsec
= millis
* 1000L * 1000L;
491 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
495 return wxCOND_TIMEOUT
;
498 return wxCOND_NO_ERROR
;
501 wxLogApiError(wxT("pthread_cond_timedwait()"), err
);
504 return wxCOND_MISC_ERROR
;
507 wxCondError
wxConditionInternal::Signal()
509 int err
= pthread_cond_signal(&m_cond
);
512 wxLogApiError(wxT("pthread_cond_signal()"), err
);
514 return wxCOND_MISC_ERROR
;
517 return wxCOND_NO_ERROR
;
520 wxCondError
wxConditionInternal::Broadcast()
522 int err
= pthread_cond_broadcast(&m_cond
);
525 wxLogApiError(wxT("pthread_cond_broadcast()"), err
);
527 return wxCOND_MISC_ERROR
;
530 return wxCOND_NO_ERROR
;
533 // ===========================================================================
534 // wxSemaphore implementation
535 // ===========================================================================
537 // ---------------------------------------------------------------------------
538 // wxSemaphoreInternal
539 // ---------------------------------------------------------------------------
541 // we implement the semaphores using mutexes and conditions instead of using
542 // the sem_xxx() POSIX functions because they're not widely available and also
543 // because it's impossible to implement WaitTimeout() using them
544 class wxSemaphoreInternal
547 wxSemaphoreInternal(int initialcount
, int maxcount
);
549 bool IsOk() const { return m_isOk
; }
552 wxSemaError
TryWait();
553 wxSemaError
WaitTimeout(unsigned long milliseconds
);
567 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
571 if ( (initialcount
< 0 || maxcount
< 0) ||
572 ((maxcount
> 0) && (initialcount
> maxcount
)) )
574 wxFAIL_MSG( wxT("wxSemaphore: invalid initial or maximal count") );
580 m_maxcount
= (size_t)maxcount
;
581 m_count
= (size_t)initialcount
;
584 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
587 wxSemaError
wxSemaphoreInternal::Wait()
589 wxMutexLocker
locker(m_mutex
);
591 while ( m_count
== 0 )
593 wxLogTrace(TRACE_SEMA
,
594 wxT("Thread %p waiting for semaphore to become signalled"),
595 THR_ID_CAST(wxThread::GetCurrentId()));
597 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
598 return wxSEMA_MISC_ERROR
;
600 wxLogTrace(TRACE_SEMA
,
601 wxT("Thread %p finished waiting for semaphore, count = %lu"),
602 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
607 return wxSEMA_NO_ERROR
;
610 wxSemaError
wxSemaphoreInternal::TryWait()
612 wxMutexLocker
locker(m_mutex
);
619 return wxSEMA_NO_ERROR
;
622 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
624 wxMutexLocker
locker(m_mutex
);
626 wxLongLong startTime
= wxGetLocalTimeMillis();
628 while ( m_count
== 0 )
630 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
631 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
632 if ( remainingTime
<= 0 )
635 return wxSEMA_TIMEOUT
;
638 switch ( m_cond
.WaitTimeout(remainingTime
) )
641 return wxSEMA_TIMEOUT
;
644 return wxSEMA_MISC_ERROR
;
646 case wxCOND_NO_ERROR
:
653 return wxSEMA_NO_ERROR
;
656 wxSemaError
wxSemaphoreInternal::Post()
658 wxMutexLocker
locker(m_mutex
);
660 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
662 return wxSEMA_OVERFLOW
;
667 wxLogTrace(TRACE_SEMA
,
668 wxT("Thread %p about to signal semaphore, count = %lu"),
669 THR_ID_CAST(wxThread::GetCurrentId()), (unsigned long)m_count
);
671 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
675 // ===========================================================================
676 // wxThread implementation
677 // ===========================================================================
679 // the thread callback functions must have the C linkage
683 #ifdef wxHAVE_PTHREAD_CLEANUP
684 // thread exit function
685 void wxPthreadCleanup(void *ptr
);
686 #endif // wxHAVE_PTHREAD_CLEANUP
688 void *wxPthreadStart(void *ptr
);
692 // ----------------------------------------------------------------------------
694 // ----------------------------------------------------------------------------
696 class wxThreadInternal
702 // thread entry function
703 static void *PthreadStart(wxThread
*thread
);
708 // unblock the thread allowing it to run
709 void SignalRun() { m_semRun
.Post(); }
710 // ask the thread to terminate
712 // go to sleep until Resume() is called
719 int GetPriority() const { return m_prio
; }
720 void SetPriority(int prio
) { m_prio
= prio
; }
722 wxThreadState
GetState() const { return m_state
; }
723 void SetState(wxThreadState state
)
726 static const wxChar
*const stateNames
[] =
734 wxLogTrace(TRACE_THREADS
, wxT("Thread %p: %s => %s."),
735 THR_ID(this), stateNames
[m_state
], stateNames
[state
]);
736 #endif // wxUSE_LOG_TRACE
741 pthread_t
GetId() const { return m_threadId
; }
742 pthread_t
*GetIdPtr() { return &m_threadId
; }
744 void SetCancelFlag() { m_cancelled
= true; }
745 bool WasCancelled() const { return m_cancelled
; }
747 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
748 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
751 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
752 bool IsReallyPaused() const { return m_isPaused
; }
754 // tell the thread that it is a detached one
757 wxCriticalSectionLocker
lock(m_csJoinFlag
);
759 m_shouldBeJoined
= false;
763 #ifdef wxHAVE_PTHREAD_CLEANUP
764 // this is used by wxPthreadCleanup() only
765 static void Cleanup(wxThread
*thread
);
766 #endif // wxHAVE_PTHREAD_CLEANUP
769 pthread_t m_threadId
; // id of the thread
770 wxThreadState m_state
; // see wxThreadState enum
771 int m_prio
; // in wxWidgets units: from 0 to 100
773 // this flag is set when the thread should terminate
776 // this flag is set when the thread is blocking on m_semSuspend
779 // the thread exit code - only used for joinable (!detached) threads and
780 // is only valid after the thread termination
781 wxThread::ExitCode m_exitcode
;
783 // many threads may call Wait(), but only one of them should call
784 // pthread_join(), so we have to keep track of this
785 wxCriticalSection m_csJoinFlag
;
786 bool m_shouldBeJoined
;
789 // this semaphore is posted by Run() and the threads Entry() is not
790 // called before it is done
791 wxSemaphore m_semRun
;
793 // this one is signaled when the thread should resume after having been
795 wxSemaphore m_semSuspend
;
798 // ----------------------------------------------------------------------------
799 // thread startup and exit functions
800 // ----------------------------------------------------------------------------
802 void *wxPthreadStart(void *ptr
)
804 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
807 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
809 wxThreadInternal
*pthread
= thread
->m_internal
;
811 wxLogTrace(TRACE_THREADS
, wxT("Thread %p started."), THR_ID(pthread
));
813 // associate the thread pointer with the newly created thread so that
814 // wxThread::This() will work
815 int rc
= pthread_setspecific(gs_keySelf
, thread
);
818 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
823 // have to declare this before pthread_cleanup_push() which defines a
827 #ifdef wxHAVE_PTHREAD_CLEANUP
828 // install the cleanup handler which will be called if the thread is
830 pthread_cleanup_push(wxPthreadCleanup
, thread
);
831 #endif // wxHAVE_PTHREAD_CLEANUP
833 // wait for the semaphore to be posted from Run()
834 pthread
->m_semRun
.Wait();
836 // test whether we should run the run at all - may be it was deleted
837 // before it started to Run()?
839 wxCriticalSectionLocker
lock(thread
->m_critsect
);
841 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
842 pthread
->WasCancelled();
847 // call the main entry
848 wxLogTrace(TRACE_THREADS
,
849 wxT("Thread %p about to enter its Entry()."),
854 pthread
->m_exitcode
= thread
->Entry();
856 wxLogTrace(TRACE_THREADS
,
857 wxT("Thread %p Entry() returned %lu."),
858 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
860 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
863 wxCriticalSectionLocker
lock(thread
->m_critsect
);
865 // change the state of the thread to "exited" so that
866 // wxPthreadCleanup handler won't do anything from now (if it's
867 // called before we do pthread_cleanup_pop below)
868 pthread
->SetState(STATE_EXITED
);
872 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
873 // '}' for the '{' in push, so they must be used in the same block!
874 #ifdef wxHAVE_PTHREAD_CLEANUP
876 // under Tru64 we get a warning from macro expansion
878 #pragma message disable(declbutnotref)
881 // remove the cleanup handler without executing it
882 pthread_cleanup_pop(FALSE
);
885 #pragma message restore
887 #endif // wxHAVE_PTHREAD_CLEANUP
891 // FIXME: deleting a possibly joinable thread here???
894 return EXITCODE_CANCELLED
;
898 // terminate the thread
899 thread
->Exit(pthread
->m_exitcode
);
901 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
907 #ifdef wxHAVE_PTHREAD_CLEANUP
909 // this handler is called when the thread is cancelled
910 extern "C" void wxPthreadCleanup(void *ptr
)
912 wxThreadInternal::Cleanup((wxThread
*)ptr
);
915 void wxThreadInternal::Cleanup(wxThread
*thread
)
917 if (pthread_getspecific(gs_keySelf
) == 0) return;
919 wxCriticalSectionLocker
lock(thread
->m_critsect
);
920 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
922 // thread is already considered as finished.
927 // exit the thread gracefully
928 thread
->Exit(EXITCODE_CANCELLED
);
931 #endif // wxHAVE_PTHREAD_CLEANUP
933 // ----------------------------------------------------------------------------
935 // ----------------------------------------------------------------------------
937 wxThreadInternal::wxThreadInternal()
941 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
945 // set to true only when the thread starts waiting on m_semSuspend
948 // defaults for joinable threads
949 m_shouldBeJoined
= true;
950 m_isDetached
= false;
953 wxThreadInternal::~wxThreadInternal()
957 wxThreadError
wxThreadInternal::Run()
959 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
960 wxT("thread may only be started once after Create()") );
962 SetState(STATE_RUNNING
);
964 // wake up threads waiting for our start
967 return wxTHREAD_NO_ERROR
;
970 void wxThreadInternal::Wait()
972 wxCHECK_RET( !m_isDetached
, wxT("can't wait for a detached thread") );
974 // if the thread we're waiting for is waiting for the GUI mutex, we will
975 // deadlock so make sure we release it temporarily
976 if ( wxThread::IsMain() )
979 wxLogTrace(TRACE_THREADS
,
980 wxT("Starting to wait for thread %p to exit."),
983 // to avoid memory leaks we should call pthread_join(), but it must only be
984 // done once so use a critical section to serialize the code below
986 wxCriticalSectionLocker
lock(m_csJoinFlag
);
988 if ( m_shouldBeJoined
)
990 // FIXME shouldn't we set cancellation type to DISABLED here? If
991 // we're cancelled inside pthread_join(), things will almost
992 // certainly break - but if we disable the cancellation, we
994 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
996 // this is a serious problem, so use wxLogError and not
997 // wxLogDebug: it is possible to bring the system to its knees
998 // by creating too many threads and not joining them quite
1000 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
1003 m_shouldBeJoined
= false;
1007 // reacquire GUI mutex
1008 if ( wxThread::IsMain() )
1012 void wxThreadInternal::Pause()
1014 // the state is set from the thread which pauses us first, this function
1015 // is called later so the state should have been already set
1016 wxCHECK_RET( m_state
== STATE_PAUSED
,
1017 wxT("thread must first be paused with wxThread::Pause().") );
1019 wxLogTrace(TRACE_THREADS
,
1020 wxT("Thread %p goes to sleep."), THR_ID(this));
1022 // wait until the semaphore is Post()ed from Resume()
1023 m_semSuspend
.Wait();
1026 void wxThreadInternal::Resume()
1028 wxCHECK_RET( m_state
== STATE_PAUSED
,
1029 wxT("can't resume thread which is not suspended.") );
1031 // the thread might be not actually paused yet - if there were no call to
1032 // TestDestroy() since the last call to Pause() for example
1033 if ( IsReallyPaused() )
1035 wxLogTrace(TRACE_THREADS
,
1036 wxT("Waking up thread %p"), THR_ID(this));
1039 m_semSuspend
.Post();
1042 SetReallyPaused(false);
1046 wxLogTrace(TRACE_THREADS
,
1047 wxT("Thread %p is not yet really paused"), THR_ID(this));
1050 SetState(STATE_RUNNING
);
1053 // -----------------------------------------------------------------------------
1054 // wxThread static functions
1055 // -----------------------------------------------------------------------------
1057 wxThread
*wxThread::This()
1059 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1062 void wxThread::Yield()
1064 #ifdef HAVE_SCHED_YIELD
1069 int wxThread::GetCPUCount()
1071 #if defined(_SC_NPROCESSORS_ONLN)
1072 // this works for Solaris and Linux 2.6
1073 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1078 #elif defined(__LINUX__) && wxUSE_FFILE
1079 // read from proc (can't use wxTextFile here because it's a special file:
1080 // it has 0 size but still can be read from)
1083 wxFFile
file(wxT("/proc/cpuinfo"));
1084 if ( file
.IsOpened() )
1086 // slurp the whole file
1088 if ( file
.ReadAll(&s
) )
1090 // (ab)use Replace() to find the number of "processor: num" strings
1091 size_t count
= s
.Replace(wxT("processor\t:"), wxT(""));
1097 wxLogDebug(wxT("failed to parse /proc/cpuinfo"));
1101 wxLogDebug(wxT("failed to read /proc/cpuinfo"));
1104 #endif // different ways to get number of CPUs
1110 wxThreadIdType
wxThread::GetCurrentId()
1112 return (wxThreadIdType
)pthread_self();
1116 bool wxThread::SetConcurrency(size_t level
)
1118 #ifdef HAVE_THR_SETCONCURRENCY
1119 int rc
= thr_setconcurrency(level
);
1122 wxLogSysError(rc
, wxT("thr_setconcurrency() failed"));
1126 #else // !HAVE_THR_SETCONCURRENCY
1127 // ok only for the default value
1129 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1132 // -----------------------------------------------------------------------------
1134 // -----------------------------------------------------------------------------
1136 wxThread::wxThread(wxThreadKind kind
)
1138 // add this thread to the global list of all threads
1140 wxMutexLocker
lock(*gs_mutexAllThreads
);
1142 gs_allThreads
.Add(this);
1145 m_internal
= new wxThreadInternal();
1147 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1150 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1151 #define WXUNUSED_STACKSIZE(identifier) identifier
1153 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1156 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1158 if ( m_internal
->GetState() != STATE_NEW
)
1160 // don't recreate thread
1161 return wxTHREAD_RUNNING
;
1164 // set up the thread attribute: right now, we only set thread priority
1165 pthread_attr_t attr
;
1166 pthread_attr_init(&attr
);
1168 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1170 pthread_attr_setstacksize(&attr
, stackSize
);
1173 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1175 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1177 wxLogError(_("Cannot retrieve thread scheduling policy."));
1181 /* the pthread.h contains too many spaces. This is a work-around */
1182 # undef sched_get_priority_max
1183 #undef sched_get_priority_min
1184 #define sched_get_priority_max(_pol_) \
1185 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1186 #define sched_get_priority_min(_pol_) \
1187 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1190 int max_prio
= sched_get_priority_max(policy
),
1191 min_prio
= sched_get_priority_min(policy
),
1192 prio
= m_internal
->GetPriority();
1194 if ( min_prio
== -1 || max_prio
== -1 )
1196 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1199 else if ( max_prio
== min_prio
)
1201 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1203 // notify the programmer that this doesn't work here
1204 wxLogWarning(_("Thread priority setting is ignored."));
1206 //else: we have default priority, so don't complain
1208 // anyhow, don't do anything because priority is just ignored
1212 struct sched_param sp
;
1213 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1215 wxFAIL_MSG(wxT("pthread_attr_getschedparam() failed"));
1218 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1220 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1222 wxFAIL_MSG(wxT("pthread_attr_setschedparam(priority) failed"));
1225 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1227 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1228 // this will make the threads created by this process really concurrent
1229 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1231 wxFAIL_MSG(wxT("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1233 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1235 // VZ: assume that this one is always available (it's rather fundamental),
1236 // if this function is ever missing we should try to use
1237 // pthread_detach() instead (after thread creation)
1240 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1242 wxFAIL_MSG(wxT("pthread_attr_setdetachstate(DETACHED) failed"));
1245 // never try to join detached threads
1246 m_internal
->Detach();
1248 //else: threads are created joinable by default, it's ok
1250 // create the new OS thread object
1251 int rc
= pthread_create
1253 m_internal
->GetIdPtr(),
1259 if ( pthread_attr_destroy(&attr
) != 0 )
1261 wxFAIL_MSG(wxT("pthread_attr_destroy() failed"));
1266 m_internal
->SetState(STATE_EXITED
);
1268 return wxTHREAD_NO_RESOURCE
;
1271 return wxTHREAD_NO_ERROR
;
1274 wxThreadError
wxThread::Run()
1276 wxCriticalSectionLocker
lock(m_critsect
);
1278 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1279 wxT("must call wxThread::Create() first") );
1281 return m_internal
->Run();
1284 // -----------------------------------------------------------------------------
1286 // -----------------------------------------------------------------------------
1288 void wxThread::SetPriority(unsigned int prio
)
1290 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1291 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1292 wxT("invalid thread priority") );
1294 wxCriticalSectionLocker
lock(m_critsect
);
1296 switch ( m_internal
->GetState() )
1299 // thread not yet started, priority will be set when it is
1300 m_internal
->SetPriority(prio
);
1305 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1306 #if defined(__LINUX__)
1307 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1308 // a priority other than 0. Instead, we use the BSD setpriority
1309 // which alllows us to set a 'nice' value between 20 to -20. Only
1310 // super user can set a value less than zero (more negative yields
1311 // higher priority). setpriority set the static priority of a
1312 // process, but this is OK since Linux is configured as a thread
1315 // FIXME this is not true for 2.6!!
1317 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1318 // to Unix priorities 20..-20
1319 if ( setpriority(PRIO_PROCESS
, 0, -(2*(int)prio
)/5 + 20) == -1 )
1321 wxLogError(_("Failed to set thread priority %d."), prio
);
1325 struct sched_param sparam
;
1326 sparam
.sched_priority
= prio
;
1328 if ( pthread_setschedparam(m_internal
->GetId(),
1329 SCHED_OTHER
, &sparam
) != 0 )
1331 wxLogError(_("Failed to set thread priority %d."), prio
);
1335 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1340 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1344 unsigned int wxThread::GetPriority() const
1346 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1348 return m_internal
->GetPriority();
1351 wxThreadIdType
wxThread::GetId() const
1353 return (wxThreadIdType
) m_internal
->GetId();
1356 // -----------------------------------------------------------------------------
1358 // -----------------------------------------------------------------------------
1360 wxThreadError
wxThread::Pause()
1362 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1363 wxT("a thread can't pause itself") );
1365 wxCriticalSectionLocker
lock(m_critsect
);
1367 if ( m_internal
->GetState() != STATE_RUNNING
)
1369 wxLogDebug(wxT("Can't pause thread which is not running."));
1371 return wxTHREAD_NOT_RUNNING
;
1374 // just set a flag, the thread will be really paused only during the next
1375 // call to TestDestroy()
1376 m_internal
->SetState(STATE_PAUSED
);
1378 return wxTHREAD_NO_ERROR
;
1381 wxThreadError
wxThread::Resume()
1383 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1384 wxT("a thread can't resume itself") );
1386 wxCriticalSectionLocker
lock(m_critsect
);
1388 wxThreadState state
= m_internal
->GetState();
1393 wxLogTrace(TRACE_THREADS
, wxT("Thread %p suspended, resuming."),
1396 m_internal
->Resume();
1398 return wxTHREAD_NO_ERROR
;
1401 wxLogTrace(TRACE_THREADS
, wxT("Thread %p exited, won't resume."),
1403 return wxTHREAD_NO_ERROR
;
1406 wxLogDebug(wxT("Attempt to resume a thread which is not paused."));
1408 return wxTHREAD_MISC_ERROR
;
1412 // -----------------------------------------------------------------------------
1414 // -----------------------------------------------------------------------------
1416 wxThread::ExitCode
wxThread::Wait()
1418 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1419 wxT("a thread can't wait for itself") );
1421 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1422 wxT("can't wait for detached thread") );
1426 return m_internal
->GetExitCode();
1429 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1431 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1432 wxT("a thread can't delete itself") );
1434 bool isDetached
= m_isDetached
;
1437 wxThreadState state
= m_internal
->GetState();
1439 // ask the thread to stop
1440 m_internal
->SetCancelFlag();
1447 // we need to wake up the thread so that PthreadStart() will
1448 // terminate - right now it's blocking on run semaphore in
1450 m_internal
->SignalRun();
1459 // resume the thread first
1460 m_internal
->Resume();
1467 // wait until the thread stops
1472 // return the exit code of the thread
1473 *rc
= m_internal
->GetExitCode();
1476 //else: can't wait for detached threads
1479 if (state
== STATE_NEW
)
1480 return wxTHREAD_MISC_ERROR
;
1481 // for coherency with the MSW implementation, signal the user that
1482 // Delete() was called on a thread which didn't start to run yet.
1484 return wxTHREAD_NO_ERROR
;
1487 wxThreadError
wxThread::Kill()
1489 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1490 wxT("a thread can't kill itself") );
1492 switch ( m_internal
->GetState() )
1496 return wxTHREAD_NOT_RUNNING
;
1499 // resume the thread first
1505 #ifdef HAVE_PTHREAD_CANCEL
1506 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1507 #endif // HAVE_PTHREAD_CANCEL
1509 wxLogError(_("Failed to terminate a thread."));
1511 return wxTHREAD_MISC_ERROR
;
1514 #ifdef HAVE_PTHREAD_CANCEL
1517 // if we use cleanup function, this will be done from
1518 // wxPthreadCleanup()
1519 #ifndef wxHAVE_PTHREAD_CLEANUP
1520 ScheduleThreadForDeletion();
1522 // don't call OnExit() here, it can only be called in the
1523 // threads context and we're in the context of another thread
1526 #endif // wxHAVE_PTHREAD_CLEANUP
1530 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1533 return wxTHREAD_NO_ERROR
;
1534 #endif // HAVE_PTHREAD_CANCEL
1538 void wxThread::Exit(ExitCode status
)
1540 wxASSERT_MSG( This() == this,
1541 wxT("wxThread::Exit() can only be called in the context of the same thread") );
1545 // from the moment we call OnExit(), the main program may terminate at
1546 // any moment, so mark this thread as being already in process of being
1547 // deleted or wxThreadModule::OnExit() will try to delete it again
1548 ScheduleThreadForDeletion();
1551 // don't enter m_critsect before calling OnExit() because the user code
1552 // might deadlock if, for example, it signals a condition in OnExit() (a
1553 // common case) while the main thread calls any of functions entering
1554 // m_critsect on us (almost all of them do)
1559 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
1561 // delete C++ thread object if this is a detached thread - user is
1562 // responsible for doing this for joinable ones
1565 // FIXME I'm feeling bad about it - what if another thread function is
1566 // called (in another thread context) now? It will try to access
1567 // half destroyed object which will probably result in something
1568 // very bad - but we can't protect this by a crit section unless
1569 // we make it a global object, but this would mean that we can
1570 // only call one thread function at a time :-(
1572 pthread_setspecific(gs_keySelf
, 0);
1577 m_internal
->SetState(STATE_EXITED
);
1581 // terminate the thread (pthread_exit() never returns)
1582 pthread_exit(status
);
1584 wxFAIL_MSG(wxT("pthread_exit() failed"));
1587 // also test whether we were paused
1588 bool wxThread::TestDestroy()
1590 wxASSERT_MSG( This() == this,
1591 wxT("wxThread::TestDestroy() can only be called in the context of the same thread") );
1595 if ( m_internal
->GetState() == STATE_PAUSED
)
1597 m_internal
->SetReallyPaused(true);
1599 // leave the crit section or the other threads will stop too if they
1600 // try to call any of (seemingly harmless) IsXXX() functions while we
1604 m_internal
->Pause();
1608 // thread wasn't requested to pause, nothing to do
1612 return m_internal
->WasCancelled();
1615 wxThread::~wxThread()
1619 // check that the thread either exited or couldn't be created
1620 if ( m_internal
->GetState() != STATE_EXITED
&&
1621 m_internal
->GetState() != STATE_NEW
)
1623 wxLogDebug(wxT("The thread %p is being destroyed although it is still running! The application may crash."),
1631 // remove this thread from the global array
1633 wxMutexLocker
lock(*gs_mutexAllThreads
);
1635 gs_allThreads
.Remove(this);
1639 // -----------------------------------------------------------------------------
1641 // -----------------------------------------------------------------------------
1643 bool wxThread::IsRunning() const
1645 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1647 return m_internal
->GetState() == STATE_RUNNING
;
1650 bool wxThread::IsAlive() const
1652 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1654 switch ( m_internal
->GetState() )
1665 bool wxThread::IsPaused() const
1667 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1669 return (m_internal
->GetState() == STATE_PAUSED
);
1672 //--------------------------------------------------------------------
1674 //--------------------------------------------------------------------
1677 void wxOSXThreadModuleOnInit();
1678 void wxOSXThreadModuleOnExit();
1681 class wxThreadModule
: public wxModule
1684 virtual bool OnInit();
1685 virtual void OnExit();
1688 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1691 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1693 bool wxThreadModule::OnInit()
1695 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1698 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1703 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1705 gs_mutexAllThreads
= new wxMutex();
1708 wxOSXThreadModuleOnInit();
1710 gs_mutexGui
= new wxMutex();
1711 gs_mutexGui
->Lock();
1714 gs_mutexDeleteThread
= new wxMutex();
1715 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1720 void wxThreadModule::OnExit()
1722 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1724 // are there any threads left which are being deleted right now?
1725 size_t nThreadsBeingDeleted
;
1728 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1729 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1731 if ( nThreadsBeingDeleted
> 0 )
1733 wxLogTrace(TRACE_THREADS
,
1734 wxT("Waiting for %lu threads to disappear"),
1735 (unsigned long)nThreadsBeingDeleted
);
1737 // have to wait until all of them disappear
1738 gs_condAllDeleted
->Wait();
1745 wxMutexLocker
lock(*gs_mutexAllThreads
);
1747 // terminate any threads left
1748 count
= gs_allThreads
.GetCount();
1751 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1752 (unsigned long)count
);
1754 } // unlock mutex before deleting the threads as they lock it in their dtor
1756 for ( size_t n
= 0u; n
< count
; n
++ )
1758 // Delete calls the destructor which removes the current entry. We
1759 // should only delete the first one each time.
1760 gs_allThreads
[0]->Delete();
1763 delete gs_mutexAllThreads
;
1766 wxOSXThreadModuleOnExit();
1768 // destroy GUI mutex
1769 gs_mutexGui
->Unlock();
1773 // and free TLD slot
1774 (void)pthread_key_delete(gs_keySelf
);
1776 delete gs_condAllDeleted
;
1777 delete gs_mutexDeleteThread
;
1780 // ----------------------------------------------------------------------------
1782 // ----------------------------------------------------------------------------
1784 static void ScheduleThreadForDeletion()
1786 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1788 gs_nThreadsBeingDeleted
++;
1790 wxLogTrace(TRACE_THREADS
, wxT("%lu thread%s waiting to be deleted"),
1791 (unsigned long)gs_nThreadsBeingDeleted
,
1792 gs_nThreadsBeingDeleted
== 1 ? wxT("") : wxT("s"));
1795 static void DeleteThread(wxThread
*This
)
1797 wxLogTrace(TRACE_THREADS
, wxT("Thread %p auto deletes."), THR_ID(This
));
1801 // only lock gs_mutexDeleteThread after deleting the thread to avoid
1802 // calling out into user code with it locked as this may result in
1803 // deadlocks if the thread dtor deletes another thread (see #11501)
1804 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1806 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1807 wxT("no threads scheduled for deletion, yet we delete one?") );
1809 wxLogTrace(TRACE_THREADS
, wxT("%lu threads remain scheduled for deletion."),
1810 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1812 if ( !--gs_nThreadsBeingDeleted
)
1814 // no more threads left, signal it
1815 gs_condAllDeleted
->Signal();
1821 void wxMutexGuiEnterImpl()
1823 gs_mutexGui
->Lock();
1826 void wxMutexGuiLeaveImpl()
1828 gs_mutexGui
->Unlock();
1833 // ----------------------------------------------------------------------------
1834 // include common implementation code
1835 // ----------------------------------------------------------------------------
1837 #include "wx/thrimpl.cpp"
1839 #endif // wxUSE_THREADS