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"
32 #include "wx/dynarray.h"
37 #include "wx/stopwatch.h"
38 #include "wx/module.h"
50 #ifdef HAVE_THR_SETCONCURRENCY
54 // we use wxFFile under Linux in GetCPUCount()
59 #include <sys/resource.h>
63 #define THR_ID(thr) ((long long)(thr)->GetId())
65 #define THR_ID(thr) ((long)(thr)->GetId())
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // the possible states of the thread and transitions from them
75 STATE_NEW
, // didn't start execution yet (=> RUNNING)
76 STATE_RUNNING
, // running (=> PAUSED or EXITED)
77 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
78 STATE_EXITED
// thread doesn't exist any more
81 // the exit value of a thread which has been cancelled
82 static const wxThread
::ExitCode EXITCODE_CANCELLED
= (wxThread
::ExitCode
)-1;
84 // trace mask for wxThread operations
85 #define TRACE_THREADS _T("thread")
87 // you can get additional debugging messages for the semaphore operations
88 #define TRACE_SEMA _T("semaphore")
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 static void ScheduleThreadForDeletion();
95 static void DeleteThread(wxThread
*This
);
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 // an (non owning) array of pointers to threads
102 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
104 // an entry for a thread we can wait for
106 // -----------------------------------------------------------------------------
108 // -----------------------------------------------------------------------------
110 // we keep the list of all threads created by the application to be able to
111 // terminate them on exit if there are some left - otherwise the process would
113 static wxArrayThread gs_allThreads
;
115 // a mutex to protect gs_allThreads
116 static wxMutex
*gs_mutexAllThreads
= NULL
;
118 // the id of the main thread
119 static pthread_t gs_tidMain
= (pthread_t
)-1;
121 // the key for the pointer to the associated wxThread object
122 static pthread_key_t gs_keySelf
;
124 // the number of threads which are being deleted - the program won't exit
125 // until there are any left
126 static size_t gs_nThreadsBeingDeleted
= 0;
128 // a mutex to protect gs_nThreadsBeingDeleted
129 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
131 // and a condition variable which will be signaled when all
132 // gs_nThreadsBeingDeleted will have been deleted
133 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
135 // this mutex must be acquired before any call to a GUI function
136 // (it's not inside #if wxUSE_GUI because this file is compiled as part
138 static wxMutex
*gs_mutexGui
= NULL
;
140 // when we wait for a thread to exit, we're blocking on a condition which the
141 // thread signals in its SignalExit() method -- but this condition can't be a
142 // member of the thread itself as a detached thread may delete itself at any
143 // moment and accessing the condition member of the thread after this would
144 // result in a disaster
146 // so instead we maintain a global list of the structs below for the threads
147 // we're interested in waiting on
149 // ============================================================================
150 // wxMutex implementation
151 // ============================================================================
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // this is a simple wrapper around pthread_mutex_t which provides error
159 class wxMutexInternal
162 wxMutexInternal(wxMutexType mutexType
);
166 wxMutexError
Lock(unsigned long ms
);
167 wxMutexError
TryLock();
168 wxMutexError
Unlock();
170 bool IsOk() const { return m_isOk
; }
173 // convert the result of pthread_mutex_[timed]lock() call to wx return code
174 wxMutexError
HandleLockResult(int err
);
177 pthread_mutex_t m_mutex
;
180 // wxConditionInternal uses our m_mutex
181 friend class wxConditionInternal
;
184 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
185 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
186 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
187 // in the library, otherwise we wouldn't compile this code at all)
188 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
191 wxMutexInternal
::wxMutexInternal(wxMutexType mutexType
)
196 case wxMUTEX_RECURSIVE
:
197 // support recursive locks like Win32, i.e. a thread can lock a
198 // mutex which it had itself already locked
200 // unfortunately initialization of recursive mutexes is non
201 // portable, so try several methods
202 #ifdef HAVE_PTHREAD_MUTEXATTR_T
204 pthread_mutexattr_t attr
;
205 pthread_mutexattr_init(&attr
);
206 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
208 err
= pthread_mutex_init(&m_mutex
, &attr
);
210 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
211 // we can use this only as initializer so we have to assign it
212 // first to a temp var - assigning directly to m_mutex wouldn't
215 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
218 #else // no recursive mutexes
220 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
224 wxFAIL_MSG( _T("unknown mutex type") );
227 case wxMUTEX_DEFAULT
:
228 err
= pthread_mutex_init(&m_mutex
, NULL
);
235 wxLogApiError( wxT("pthread_mutex_init()"), err
);
239 wxMutexInternal
::~wxMutexInternal()
243 int err
= pthread_mutex_destroy(&m_mutex
);
246 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
251 wxMutexError wxMutexInternal
::Lock()
253 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
256 wxMutexError wxMutexInternal
::Lock(unsigned long ms
)
258 static const long MSEC_IN_SEC
= 1000;
259 static const long NSEC_IN_MSEC
= 1000000;
260 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
262 time_t seconds
= ms
/MSEC_IN_SEC
;
263 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
264 timespec ts
= { 0, 0 };
266 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
268 ts
.tv_sec
+= seconds
;
269 ts
.tv_nsec
+= nanoseconds
;
270 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
273 ts
.tv_nsec
-= NSEC_IN_SEC
;
276 else // fall back on system timer
278 wxLogDebug(_T("clock_gettime(CLOCK_REALTIME) failed"));
279 ts
.tv_sec
= time(NULL
) + seconds
;
280 ts
.tv_nsec
= nanoseconds
;
283 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
286 wxMutexError wxMutexInternal
::HandleLockResult(int err
)
291 // only error checking mutexes return this value and so it's an
292 // unexpected situation -- hence use assert, not wxLogDebug
293 wxFAIL_MSG( _T("mutex deadlock prevented") );
294 return wxMUTEX_DEAD_LOCK
;
297 wxLogDebug(_T("pthread_mutex_[timed]lock(): mutex not initialized"));
301 return wxMUTEX_TIMEOUT
;
304 return wxMUTEX_NO_ERROR
;
307 wxLogApiError(_T("pthread_mutex_[timed]lock()"), err
);
310 return wxMUTEX_MISC_ERROR
;
314 wxMutexError wxMutexInternal
::TryLock()
316 int err
= pthread_mutex_trylock(&m_mutex
);
320 // not an error: mutex is already locked, but we're prepared for
325 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
329 return wxMUTEX_NO_ERROR
;
332 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
335 return wxMUTEX_MISC_ERROR
;
338 wxMutexError wxMutexInternal
::Unlock()
340 int err
= pthread_mutex_unlock(&m_mutex
);
344 // we don't own the mutex
345 return wxMUTEX_UNLOCKED
;
348 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
352 return wxMUTEX_NO_ERROR
;
355 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
358 return wxMUTEX_MISC_ERROR
;
361 // ===========================================================================
362 // wxCondition implementation
363 // ===========================================================================
365 // ---------------------------------------------------------------------------
366 // wxConditionInternal
367 // ---------------------------------------------------------------------------
369 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
370 // with a pthread_mutex_t)
371 class wxConditionInternal
374 wxConditionInternal(wxMutex
& mutex
);
375 ~wxConditionInternal();
377 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
380 wxCondError
WaitTimeout(unsigned long milliseconds
);
382 wxCondError
Signal();
383 wxCondError
Broadcast();
386 // get the POSIX mutex associated with us
387 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
390 pthread_cond_t m_cond
;
395 wxConditionInternal
::wxConditionInternal(wxMutex
& mutex
)
398 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
404 wxLogApiError(_T("pthread_cond_init()"), err
);
408 wxConditionInternal
::~wxConditionInternal()
412 int err
= pthread_cond_destroy(&m_cond
);
415 wxLogApiError(_T("pthread_cond_destroy()"), err
);
420 wxCondError wxConditionInternal
::Wait()
422 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
425 wxLogApiError(_T("pthread_cond_wait()"), err
);
427 return wxCOND_MISC_ERROR
;
430 return wxCOND_NO_ERROR
;
433 wxCondError wxConditionInternal
::WaitTimeout(unsigned long milliseconds
)
435 wxLongLong curtime
= wxGetLocalTimeMillis();
436 curtime
+= milliseconds
;
437 wxLongLong temp
= curtime
/ 1000;
438 int sec
= temp
.GetLo();
440 temp
= curtime
- temp
;
441 int millis
= temp
.GetLo();
446 tspec
.tv_nsec
= millis
* 1000L * 1000L;
448 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
452 return wxCOND_TIMEOUT
;
455 return wxCOND_NO_ERROR
;
458 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
461 return wxCOND_MISC_ERROR
;
464 wxCondError wxConditionInternal
::Signal()
466 int err
= pthread_cond_signal(&m_cond
);
469 wxLogApiError(_T("pthread_cond_signal()"), err
);
471 return wxCOND_MISC_ERROR
;
474 return wxCOND_NO_ERROR
;
477 wxCondError wxConditionInternal
::Broadcast()
479 int err
= pthread_cond_broadcast(&m_cond
);
482 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
484 return wxCOND_MISC_ERROR
;
487 return wxCOND_NO_ERROR
;
490 // ===========================================================================
491 // wxSemaphore implementation
492 // ===========================================================================
494 // ---------------------------------------------------------------------------
495 // wxSemaphoreInternal
496 // ---------------------------------------------------------------------------
498 // we implement the semaphores using mutexes and conditions instead of using
499 // the sem_xxx() POSIX functions because they're not widely available and also
500 // because it's impossible to implement WaitTimeout() using them
501 class wxSemaphoreInternal
504 wxSemaphoreInternal(int initialcount
, int maxcount
);
506 bool IsOk() const { return m_isOk
; }
509 wxSemaError
TryWait();
510 wxSemaError
WaitTimeout(unsigned long milliseconds
);
524 wxSemaphoreInternal
::wxSemaphoreInternal(int initialcount
, int maxcount
)
528 if ( (initialcount
< 0 || maxcount
< 0) ||
529 ((maxcount
> 0) && (initialcount
> maxcount
)) )
531 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
537 m_maxcount
= (size_t)maxcount
;
538 m_count
= (size_t)initialcount
;
541 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
544 wxSemaError wxSemaphoreInternal
::Wait()
546 wxMutexLocker
locker(m_mutex
);
548 while ( m_count
== 0 )
550 wxLogTrace(TRACE_SEMA
,
551 _T("Thread %ld waiting for semaphore to become signalled"),
552 wxThread
::GetCurrentId());
554 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
555 return wxSEMA_MISC_ERROR
;
557 wxLogTrace(TRACE_SEMA
,
558 _T("Thread %ld finished waiting for semaphore, count = %lu"),
559 wxThread
::GetCurrentId(), (unsigned long)m_count
);
564 return wxSEMA_NO_ERROR
;
567 wxSemaError wxSemaphoreInternal
::TryWait()
569 wxMutexLocker
locker(m_mutex
);
576 return wxSEMA_NO_ERROR
;
579 wxSemaError wxSemaphoreInternal
::WaitTimeout(unsigned long milliseconds
)
581 wxMutexLocker
locker(m_mutex
);
583 wxLongLong startTime
= wxGetLocalTimeMillis();
585 while ( m_count
== 0 )
587 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
588 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
589 if ( remainingTime
<= 0 )
592 return wxSEMA_TIMEOUT
;
595 switch ( m_cond
.WaitTimeout(remainingTime
) )
598 return wxSEMA_TIMEOUT
;
601 return wxSEMA_MISC_ERROR
;
603 case wxCOND_NO_ERROR
:
610 return wxSEMA_NO_ERROR
;
613 wxSemaError wxSemaphoreInternal
::Post()
615 wxMutexLocker
locker(m_mutex
);
617 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
619 return wxSEMA_OVERFLOW
;
624 wxLogTrace(TRACE_SEMA
,
625 _T("Thread %ld about to signal semaphore, count = %lu"),
626 wxThread
::GetCurrentId(), (unsigned long)m_count
);
628 return m_cond
.Signal() == wxCOND_NO_ERROR ? wxSEMA_NO_ERROR
632 // ===========================================================================
633 // wxThread implementation
634 // ===========================================================================
636 // the thread callback functions must have the C linkage
640 #ifdef wxHAVE_PTHREAD_CLEANUP
641 // thread exit function
642 void wxPthreadCleanup(void *ptr
);
643 #endif // wxHAVE_PTHREAD_CLEANUP
645 void *wxPthreadStart(void *ptr
);
649 // ----------------------------------------------------------------------------
651 // ----------------------------------------------------------------------------
653 class wxThreadInternal
659 // thread entry function
660 static void *PthreadStart(wxThread
*thread
);
665 // unblock the thread allowing it to run
666 void SignalRun() { m_semRun
.Post(); }
667 // ask the thread to terminate
669 // go to sleep until Resume() is called
676 int GetPriority() const { return m_prio
; }
677 void SetPriority(int prio
) { m_prio
= prio
; }
679 wxThreadState
GetState() const { return m_state
; }
680 void SetState(wxThreadState state
)
683 static const wxChar
*stateNames
[] =
691 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
692 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
693 #endif // __WXDEBUG__
698 pthread_t
GetId() const { return m_threadId
; }
699 pthread_t
*GetIdPtr() { return &m_threadId
; }
701 void SetCancelFlag() { m_cancelled
= true; }
702 bool WasCancelled() const { return m_cancelled
; }
704 void SetExitCode(wxThread
::ExitCode exitcode
) { m_exitcode
= exitcode
; }
705 wxThread
::ExitCode
GetExitCode() const { return m_exitcode
; }
708 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
709 bool IsReallyPaused() const { return m_isPaused
; }
711 // tell the thread that it is a detached one
714 wxCriticalSectionLocker
lock(m_csJoinFlag
);
716 m_shouldBeJoined
= false;
720 #ifdef wxHAVE_PTHREAD_CLEANUP
721 // this is used by wxPthreadCleanup() only
722 static void Cleanup(wxThread
*thread
);
723 #endif // wxHAVE_PTHREAD_CLEANUP
726 pthread_t m_threadId
; // id of the thread
727 wxThreadState m_state
; // see wxThreadState enum
728 int m_prio
; // in wxWidgets units: from 0 to 100
730 // this flag is set when the thread should terminate
733 // this flag is set when the thread is blocking on m_semSuspend
736 // the thread exit code - only used for joinable (!detached) threads and
737 // is only valid after the thread termination
738 wxThread
::ExitCode m_exitcode
;
740 // many threads may call Wait(), but only one of them should call
741 // pthread_join(), so we have to keep track of this
742 wxCriticalSection m_csJoinFlag
;
743 bool m_shouldBeJoined
;
746 // this semaphore is posted by Run() and the threads Entry() is not
747 // called before it is done
748 wxSemaphore m_semRun
;
750 // this one is signaled when the thread should resume after having been
752 wxSemaphore m_semSuspend
;
755 // ----------------------------------------------------------------------------
756 // thread startup and exit functions
757 // ----------------------------------------------------------------------------
759 void *wxPthreadStart(void *ptr
)
761 return wxThreadInternal
::PthreadStart((wxThread
*)ptr
);
764 void *wxThreadInternal
::PthreadStart(wxThread
*thread
)
766 wxThreadInternal
*pthread
= thread
->m_internal
;
768 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
770 // associate the thread pointer with the newly created thread so that
771 // wxThread::This() will work
772 int rc
= pthread_setspecific(gs_keySelf
, thread
);
775 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
780 // have to declare this before pthread_cleanup_push() which defines a
784 #ifdef wxHAVE_PTHREAD_CLEANUP
785 // install the cleanup handler which will be called if the thread is
787 pthread_cleanup_push(wxPthreadCleanup
, thread
);
788 #endif // wxHAVE_PTHREAD_CLEANUP
790 // wait for the semaphore to be posted from Run()
791 pthread
->m_semRun
.Wait();
793 // test whether we should run the run at all - may be it was deleted
794 // before it started to Run()?
796 wxCriticalSectionLocker
lock(thread
->m_critsect
);
798 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
799 pthread
->WasCancelled();
804 // call the main entry
805 wxLogTrace(TRACE_THREADS
,
806 _T("Thread %ld about to enter its Entry()."),
809 pthread
->m_exitcode
= thread
->Entry();
811 wxLogTrace(TRACE_THREADS
,
812 _T("Thread %ld Entry() returned %lu."),
813 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
816 wxCriticalSectionLocker
lock(thread
->m_critsect
);
818 // change the state of the thread to "exited" so that
819 // wxPthreadCleanup handler won't do anything from now (if it's
820 // called before we do pthread_cleanup_pop below)
821 pthread
->SetState(STATE_EXITED
);
825 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
826 // '}' for the '{' in push, so they must be used in the same block!
827 #ifdef wxHAVE_PTHREAD_CLEANUP
829 // under Tru64 we get a warning from macro expansion
831 #pragma message disable(declbutnotref)
834 // remove the cleanup handler without executing it
835 pthread_cleanup_pop(FALSE
);
838 #pragma message restore
840 #endif // wxHAVE_PTHREAD_CLEANUP
844 // FIXME: deleting a possibly joinable thread here???
847 return EXITCODE_CANCELLED
;
851 // terminate the thread
852 thread
->Exit(pthread
->m_exitcode
);
854 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
860 #ifdef wxHAVE_PTHREAD_CLEANUP
862 // this handler is called when the thread is cancelled
863 extern "C" void wxPthreadCleanup(void *ptr
)
865 wxThreadInternal
::Cleanup((wxThread
*)ptr
);
868 void wxThreadInternal
::Cleanup(wxThread
*thread
)
870 if (pthread_getspecific(gs_keySelf
) == 0) return;
872 wxCriticalSectionLocker
lock(thread
->m_critsect
);
873 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
875 // thread is already considered as finished.
880 // exit the thread gracefully
881 thread
->Exit(EXITCODE_CANCELLED
);
884 #endif // wxHAVE_PTHREAD_CLEANUP
886 // ----------------------------------------------------------------------------
888 // ----------------------------------------------------------------------------
890 wxThreadInternal
::wxThreadInternal()
894 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
898 // set to true only when the thread starts waiting on m_semSuspend
901 // defaults for joinable threads
902 m_shouldBeJoined
= true;
903 m_isDetached
= false;
906 wxThreadInternal
::~wxThreadInternal()
910 wxThreadError wxThreadInternal
::Run()
912 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
913 wxT("thread may only be started once after Create()") );
915 SetState(STATE_RUNNING
);
917 // wake up threads waiting for our start
920 return wxTHREAD_NO_ERROR
;
923 void wxThreadInternal
::Wait()
925 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
927 // if the thread we're waiting for is waiting for the GUI mutex, we will
928 // deadlock so make sure we release it temporarily
929 if ( wxThread
::IsMain() )
932 wxLogTrace(TRACE_THREADS
,
933 _T("Starting to wait for thread %ld to exit."),
936 // to avoid memory leaks we should call pthread_join(), but it must only be
937 // done once so use a critical section to serialize the code below
939 wxCriticalSectionLocker
lock(m_csJoinFlag
);
941 if ( m_shouldBeJoined
)
943 // FIXME shouldn't we set cancellation type to DISABLED here? If
944 // we're cancelled inside pthread_join(), things will almost
945 // certainly break - but if we disable the cancellation, we
947 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
949 // this is a serious problem, so use wxLogError and not
950 // wxLogDebug: it is possible to bring the system to its knees
951 // by creating too many threads and not joining them quite
953 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
956 m_shouldBeJoined
= false;
960 // reacquire GUI mutex
961 if ( wxThread
::IsMain() )
965 void wxThreadInternal
::Pause()
967 // the state is set from the thread which pauses us first, this function
968 // is called later so the state should have been already set
969 wxCHECK_RET( m_state
== STATE_PAUSED
,
970 wxT("thread must first be paused with wxThread::Pause().") );
972 wxLogTrace(TRACE_THREADS
,
973 _T("Thread %ld goes to sleep."), THR_ID(this));
975 // wait until the semaphore is Post()ed from Resume()
979 void wxThreadInternal
::Resume()
981 wxCHECK_RET( m_state
== STATE_PAUSED
,
982 wxT("can't resume thread which is not suspended.") );
984 // the thread might be not actually paused yet - if there were no call to
985 // TestDestroy() since the last call to Pause() for example
986 if ( IsReallyPaused() )
988 wxLogTrace(TRACE_THREADS
,
989 _T("Waking up thread %ld"), THR_ID(this));
995 SetReallyPaused(false);
999 wxLogTrace(TRACE_THREADS
,
1000 _T("Thread %ld is not yet really paused"), THR_ID(this));
1003 SetState(STATE_RUNNING
);
1006 // -----------------------------------------------------------------------------
1007 // wxThread static functions
1008 // -----------------------------------------------------------------------------
1010 wxThread
*wxThread
::This()
1012 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1015 bool wxThread
::IsMain()
1017 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
1020 void wxThread
::Yield()
1022 #ifdef HAVE_SCHED_YIELD
1027 void wxThread
::Sleep(unsigned long milliseconds
)
1029 wxMilliSleep(milliseconds
);
1032 int wxThread
::GetCPUCount()
1034 #if defined(_SC_NPROCESSORS_ONLN)
1035 // this works for Solaris and Linux 2.6
1036 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1041 #elif defined(__LINUX__) && wxUSE_FFILE
1042 // read from proc (can't use wxTextFile here because it's a special file:
1043 // it has 0 size but still can be read from)
1046 wxFFile
file(_T("/proc/cpuinfo"));
1047 if ( file
.IsOpened() )
1049 // slurp the whole file
1051 if ( file
.ReadAll(&s
) )
1053 // (ab)use Replace() to find the number of "processor: num" strings
1054 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1060 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1064 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1067 #endif // different ways to get number of CPUs
1073 // VMS is a 64 bit system and threads have 64 bit pointers.
1074 // FIXME: also needed for other systems????
1076 unsigned long long wxThread
::GetCurrentId()
1078 return (unsigned long long)pthread_self();
1083 unsigned long wxThread
::GetCurrentId()
1085 return (unsigned long)pthread_self();
1088 #endif // __VMS/!__VMS
1091 bool wxThread
::SetConcurrency(size_t level
)
1093 #ifdef HAVE_THR_SETCONCURRENCY
1094 int rc
= thr_setconcurrency(level
);
1097 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1101 #else // !HAVE_THR_SETCONCURRENCY
1102 // ok only for the default value
1104 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1107 // -----------------------------------------------------------------------------
1109 // -----------------------------------------------------------------------------
1111 wxThread
::wxThread(wxThreadKind kind
)
1113 // add this thread to the global list of all threads
1115 wxMutexLocker
lock(*gs_mutexAllThreads
);
1117 gs_allThreads
.Add(this);
1120 m_internal
= new wxThreadInternal();
1122 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1125 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1126 #define WXUNUSED_STACKSIZE(identifier) identifier
1128 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1131 wxThreadError wxThread
::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1133 if ( m_internal
->GetState() != STATE_NEW
)
1135 // don't recreate thread
1136 return wxTHREAD_RUNNING
;
1139 // set up the thread attribute: right now, we only set thread priority
1140 pthread_attr_t attr
;
1141 pthread_attr_init(&attr
);
1143 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1145 pthread_attr_setstacksize(&attr
, stackSize
);
1148 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1150 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1152 wxLogError(_("Cannot retrieve thread scheduling policy."));
1156 /* the pthread.h contains too many spaces. This is a work-around */
1157 # undef sched_get_priority_max
1158 #undef sched_get_priority_min
1159 #define sched_get_priority_max(_pol_) \
1160 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1161 #define sched_get_priority_min(_pol_) \
1162 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1165 int max_prio
= sched_get_priority_max(policy
),
1166 min_prio
= sched_get_priority_min(policy
),
1167 prio
= m_internal
->GetPriority();
1169 if ( min_prio
== -1 || max_prio
== -1 )
1171 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1174 else if ( max_prio
== min_prio
)
1176 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1178 // notify the programmer that this doesn't work here
1179 wxLogWarning(_("Thread priority setting is ignored."));
1181 //else: we have default priority, so don't complain
1183 // anyhow, don't do anything because priority is just ignored
1187 struct sched_param sp
;
1188 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1190 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1193 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1195 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1197 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1200 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1202 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1203 // this will make the threads created by this process really concurrent
1204 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1206 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1208 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1210 // VZ: assume that this one is always available (it's rather fundamental),
1211 // if this function is ever missing we should try to use
1212 // pthread_detach() instead (after thread creation)
1215 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1217 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1220 // never try to join detached threads
1221 m_internal
->Detach();
1223 //else: threads are created joinable by default, it's ok
1225 // create the new OS thread object
1226 int rc
= pthread_create
1228 m_internal
->GetIdPtr(),
1234 if ( pthread_attr_destroy(&attr
) != 0 )
1236 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1241 m_internal
->SetState(STATE_EXITED
);
1243 return wxTHREAD_NO_RESOURCE
;
1246 return wxTHREAD_NO_ERROR
;
1249 wxThreadError wxThread
::Run()
1251 wxCriticalSectionLocker
lock(m_critsect
);
1253 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1254 wxT("must call wxThread::Create() first") );
1256 return m_internal
->Run();
1259 // -----------------------------------------------------------------------------
1261 // -----------------------------------------------------------------------------
1263 void wxThread
::SetPriority(unsigned int prio
)
1265 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1266 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1267 wxT("invalid thread priority") );
1269 wxCriticalSectionLocker
lock(m_critsect
);
1271 switch ( m_internal
->GetState() )
1274 // thread not yet started, priority will be set when it is
1275 m_internal
->SetPriority(prio
);
1280 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1281 #if defined(__LINUX__)
1282 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1283 // a priority other than 0. Instead, we use the BSD setpriority
1284 // which alllows us to set a 'nice' value between 20 to -20. Only
1285 // super user can set a value less than zero (more negative yields
1286 // higher priority). setpriority set the static priority of a
1287 // process, but this is OK since Linux is configured as a thread
1290 // FIXME this is not true for 2.6!!
1292 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1293 // to Unix priorities 20..-20
1294 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1296 wxLogError(_("Failed to set thread priority %d."), prio
);
1300 struct sched_param sparam
;
1301 sparam
.sched_priority
= prio
;
1303 if ( pthread_setschedparam(m_internal
->GetId(),
1304 SCHED_OTHER
, &sparam
) != 0 )
1306 wxLogError(_("Failed to set thread priority %d."), prio
);
1310 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1315 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1319 unsigned int wxThread
::GetPriority() const
1321 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1323 return m_internal
->GetPriority();
1326 wxThreadIdType wxThread
::GetId() const
1328 return (wxThreadIdType
) m_internal
->GetId();
1331 // -----------------------------------------------------------------------------
1333 // -----------------------------------------------------------------------------
1335 wxThreadError wxThread
::Pause()
1337 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1338 _T("a thread can't pause itself") );
1340 wxCriticalSectionLocker
lock(m_critsect
);
1342 if ( m_internal
->GetState() != STATE_RUNNING
)
1344 wxLogDebug(wxT("Can't pause thread which is not running."));
1346 return wxTHREAD_NOT_RUNNING
;
1349 // just set a flag, the thread will be really paused only during the next
1350 // call to TestDestroy()
1351 m_internal
->SetState(STATE_PAUSED
);
1353 return wxTHREAD_NO_ERROR
;
1356 wxThreadError wxThread
::Resume()
1358 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1359 _T("a thread can't resume itself") );
1361 wxCriticalSectionLocker
lock(m_critsect
);
1363 wxThreadState state
= m_internal
->GetState();
1368 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1371 m_internal
->Resume();
1373 return wxTHREAD_NO_ERROR
;
1376 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1378 return wxTHREAD_NO_ERROR
;
1381 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1383 return wxTHREAD_MISC_ERROR
;
1387 // -----------------------------------------------------------------------------
1389 // -----------------------------------------------------------------------------
1391 wxThread
::ExitCode wxThread
::Wait()
1393 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1394 _T("a thread can't wait for itself") );
1396 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1397 _T("can't wait for detached thread") );
1401 return m_internal
->GetExitCode();
1404 wxThreadError wxThread
::Delete(ExitCode
*rc
)
1406 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1407 _T("a thread can't delete itself") );
1409 bool isDetached
= m_isDetached
;
1412 wxThreadState state
= m_internal
->GetState();
1414 // ask the thread to stop
1415 m_internal
->SetCancelFlag();
1422 // we need to wake up the thread so that PthreadStart() will
1423 // terminate - right now it's blocking on run semaphore in
1425 m_internal
->SignalRun();
1434 // resume the thread first
1435 m_internal
->Resume();
1442 // wait until the thread stops
1447 // return the exit code of the thread
1448 *rc
= m_internal
->GetExitCode();
1451 //else: can't wait for detached threads
1454 return wxTHREAD_NO_ERROR
;
1457 wxThreadError wxThread
::Kill()
1459 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1460 _T("a thread can't kill itself") );
1462 switch ( m_internal
->GetState() )
1466 return wxTHREAD_NOT_RUNNING
;
1469 // resume the thread first
1475 #ifdef HAVE_PTHREAD_CANCEL
1476 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1477 #endif // HAVE_PTHREAD_CANCEL
1479 wxLogError(_("Failed to terminate a thread."));
1481 return wxTHREAD_MISC_ERROR
;
1484 #ifdef HAVE_PTHREAD_CANCEL
1487 // if we use cleanup function, this will be done from
1488 // wxPthreadCleanup()
1489 #ifndef wxHAVE_PTHREAD_CLEANUP
1490 ScheduleThreadForDeletion();
1492 // don't call OnExit() here, it can only be called in the
1493 // threads context and we're in the context of another thread
1496 #endif // wxHAVE_PTHREAD_CLEANUP
1500 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1503 return wxTHREAD_NO_ERROR
;
1504 #endif // HAVE_PTHREAD_CANCEL
1508 void wxThread
::Exit(ExitCode status
)
1510 wxASSERT_MSG( This() == this,
1511 _T("wxThread::Exit() can only be called in the context of the same thread") );
1515 // from the moment we call OnExit(), the main program may terminate at
1516 // any moment, so mark this thread as being already in process of being
1517 // deleted or wxThreadModule::OnExit() will try to delete it again
1518 ScheduleThreadForDeletion();
1521 // don't enter m_critsect before calling OnExit() because the user code
1522 // might deadlock if, for example, it signals a condition in OnExit() (a
1523 // common case) while the main thread calls any of functions entering
1524 // m_critsect on us (almost all of them do)
1527 // delete C++ thread object if this is a detached thread - user is
1528 // responsible for doing this for joinable ones
1531 // FIXME I'm feeling bad about it - what if another thread function is
1532 // called (in another thread context) now? It will try to access
1533 // half destroyed object which will probably result in something
1534 // very bad - but we can't protect this by a crit section unless
1535 // we make it a global object, but this would mean that we can
1536 // only call one thread function at a time :-(
1538 pthread_setspecific(gs_keySelf
, 0);
1543 m_internal
->SetState(STATE_EXITED
);
1547 // terminate the thread (pthread_exit() never returns)
1548 pthread_exit(status
);
1550 wxFAIL_MSG(_T("pthread_exit() failed"));
1553 // also test whether we were paused
1554 bool wxThread
::TestDestroy()
1556 wxASSERT_MSG( This() == this,
1557 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1561 if ( m_internal
->GetState() == STATE_PAUSED
)
1563 m_internal
->SetReallyPaused(true);
1565 // leave the crit section or the other threads will stop too if they
1566 // try to call any of (seemingly harmless) IsXXX() functions while we
1570 m_internal
->Pause();
1574 // thread wasn't requested to pause, nothing to do
1578 return m_internal
->WasCancelled();
1581 wxThread
::~wxThread()
1586 // check that the thread either exited or couldn't be created
1587 if ( m_internal
->GetState() != STATE_EXITED
&&
1588 m_internal
->GetState() != STATE_NEW
)
1590 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1595 #endif // __WXDEBUG__
1599 // remove this thread from the global array
1601 wxMutexLocker
lock(*gs_mutexAllThreads
);
1603 gs_allThreads
.Remove(this);
1607 // -----------------------------------------------------------------------------
1609 // -----------------------------------------------------------------------------
1611 bool wxThread
::IsRunning() const
1613 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1615 return m_internal
->GetState() == STATE_RUNNING
;
1618 bool wxThread
::IsAlive() const
1620 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1622 switch ( m_internal
->GetState() )
1633 bool wxThread
::IsPaused() const
1635 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1637 return (m_internal
->GetState() == STATE_PAUSED
);
1640 //--------------------------------------------------------------------
1642 //--------------------------------------------------------------------
1644 class wxThreadModule
: public wxModule
1647 virtual bool OnInit();
1648 virtual void OnExit();
1651 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1654 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1656 bool wxThreadModule
::OnInit()
1658 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1661 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1666 gs_tidMain
= pthread_self();
1668 gs_mutexAllThreads
= new wxMutex();
1670 gs_mutexGui
= new wxMutex();
1671 gs_mutexGui
->Lock();
1673 gs_mutexDeleteThread
= new wxMutex();
1674 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1679 void wxThreadModule
::OnExit()
1681 wxASSERT_MSG( wxThread
::IsMain(), wxT("only main thread can be here") );
1683 // are there any threads left which are being deleted right now?
1684 size_t nThreadsBeingDeleted
;
1687 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1688 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1690 if ( nThreadsBeingDeleted
> 0 )
1692 wxLogTrace(TRACE_THREADS
,
1693 _T("Waiting for %lu threads to disappear"),
1694 (unsigned long)nThreadsBeingDeleted
);
1696 // have to wait until all of them disappear
1697 gs_condAllDeleted
->Wait();
1704 wxMutexLocker
lock(*gs_mutexAllThreads
);
1706 // terminate any threads left
1707 count
= gs_allThreads
.GetCount();
1710 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1711 (unsigned long)count
);
1713 } // unlock mutex before deleting the threads as they lock it in their dtor
1715 for ( size_t n
= 0u; n
< count
; n
++ )
1717 // Delete calls the destructor which removes the current entry. We
1718 // should only delete the first one each time.
1719 gs_allThreads
[0]->Delete();
1722 delete gs_mutexAllThreads
;
1724 // destroy GUI mutex
1725 gs_mutexGui
->Unlock();
1728 // and free TLD slot
1729 (void)pthread_key_delete(gs_keySelf
);
1731 delete gs_condAllDeleted
;
1732 delete gs_mutexDeleteThread
;
1735 // ----------------------------------------------------------------------------
1737 // ----------------------------------------------------------------------------
1739 static void ScheduleThreadForDeletion()
1741 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1743 gs_nThreadsBeingDeleted
++;
1745 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1746 (unsigned long)gs_nThreadsBeingDeleted
,
1747 gs_nThreadsBeingDeleted
== 1 ?
_T("") : _T("s"));
1750 static void DeleteThread(wxThread
*This
)
1752 // gs_mutexDeleteThread should be unlocked before signalling the condition
1753 // or wxThreadModule::OnExit() would deadlock
1754 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1756 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1760 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1761 _T("no threads scheduled for deletion, yet we delete one?") );
1763 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1764 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1766 if ( !--gs_nThreadsBeingDeleted
)
1768 // no more threads left, signal it
1769 gs_condAllDeleted
->Signal();
1773 void wxMutexGuiEnter()
1775 gs_mutexGui
->Lock();
1778 void wxMutexGuiLeave()
1780 gs_mutexGui
->Unlock();
1783 // ----------------------------------------------------------------------------
1784 // include common implementation code
1785 // ----------------------------------------------------------------------------
1787 #include "wx/thrimpl.cpp"
1789 #endif // wxUSE_THREADS