1 /////////////////////////////////////////////////////////////////////////////
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/module.h"
34 #include "wx/dynarray.h"
36 #include "wx/stopwatch.h"
47 #ifdef HAVE_THR_SETCONCURRENCY
51 // we use wxFFile under Linux in GetCPUCount()
56 #include <sys/resource.h>
60 #define THR_ID(thr) ((long long)(thr)->GetId())
62 #define THR_ID(thr) ((long)(thr)->GetId())
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // the possible states of the thread and transitions from them
72 STATE_NEW
, // didn't start execution yet (=> RUNNING)
73 STATE_RUNNING
, // running (=> PAUSED or EXITED)
74 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
75 STATE_EXITED
// thread doesn't exist any more
78 // the exit value of a thread which has been cancelled
79 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
81 // trace mask for wxThread operations
82 #define TRACE_THREADS _T("thread")
84 // you can get additional debugging messages for the semaphore operations
85 #define TRACE_SEMA _T("semaphore")
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 static void ScheduleThreadForDeletion();
92 static void DeleteThread(wxThread
*This
);
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
98 // an (non owning) array of pointers to threads
99 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
101 // an entry for a thread we can wait for
103 // -----------------------------------------------------------------------------
105 // -----------------------------------------------------------------------------
107 // we keep the list of all threads created by the application to be able to
108 // terminate them on exit if there are some left - otherwise the process would
110 static wxArrayThread gs_allThreads
;
112 // the id of the main thread
113 static pthread_t gs_tidMain
= (pthread_t
)-1;
115 // the key for the pointer to the associated wxThread object
116 static pthread_key_t gs_keySelf
;
118 // the number of threads which are being deleted - the program won't exit
119 // until there are any left
120 static size_t gs_nThreadsBeingDeleted
= 0;
122 // a mutex to protect gs_nThreadsBeingDeleted
123 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
125 // and a condition variable which will be signaled when all
126 // gs_nThreadsBeingDeleted will have been deleted
127 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
129 // this mutex must be acquired before any call to a GUI function
130 // (it's not inside #if wxUSE_GUI because this file is compiled as part
132 static wxMutex
*gs_mutexGui
= NULL
;
134 // when we wait for a thread to exit, we're blocking on a condition which the
135 // thread signals in its SignalExit() method -- but this condition can't be a
136 // member of the thread itself as a detached thread may delete itself at any
137 // moment and accessing the condition member of the thread after this would
138 // result in a disaster
140 // so instead we maintain a global list of the structs below for the threads
141 // we're interested in waiting on
143 // ============================================================================
144 // wxMutex implementation
145 // ============================================================================
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
151 // this is a simple wrapper around pthread_mutex_t which provides error
153 class wxMutexInternal
156 wxMutexInternal(wxMutexType mutexType
);
160 wxMutexError
TryLock();
161 wxMutexError
Unlock();
163 bool IsOk() const { return m_isOk
; }
166 pthread_mutex_t m_mutex
;
169 // wxConditionInternal uses our m_mutex
170 friend class wxConditionInternal
;
173 #ifdef HAVE_PTHREAD_MUTEXATTR_T
174 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
175 // in the library, otherwise we wouldn't compile this code at all)
176 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
179 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
184 case wxMUTEX_RECURSIVE
:
185 // support recursive locks like Win32, i.e. a thread can lock a
186 // mutex which it had itself already locked
188 // unfortunately initialization of recursive mutexes is non
189 // portable, so try several methods
190 #ifdef HAVE_PTHREAD_MUTEXATTR_T
192 pthread_mutexattr_t attr
;
193 pthread_mutexattr_init(&attr
);
194 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
196 err
= pthread_mutex_init(&m_mutex
, &attr
);
198 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
199 // we can use this only as initializer so we have to assign it
200 // first to a temp var - assigning directly to m_mutex wouldn't
203 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
206 #else // no recursive mutexes
208 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
212 wxFAIL_MSG( _T("unknown mutex type") );
215 case wxMUTEX_DEFAULT
:
216 err
= pthread_mutex_init(&m_mutex
, NULL
);
223 wxLogApiError( wxT("pthread_mutex_init()"), err
);
227 wxMutexInternal::~wxMutexInternal()
231 int err
= pthread_mutex_destroy(&m_mutex
);
234 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
239 wxMutexError
wxMutexInternal::Lock()
241 int err
= pthread_mutex_lock(&m_mutex
);
245 // only error checking mutexes return this value and so it's an
246 // unexpected situation -- hence use assert, not wxLogDebug
247 wxFAIL_MSG( _T("mutex deadlock prevented") );
248 return wxMUTEX_DEAD_LOCK
;
251 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
255 return wxMUTEX_NO_ERROR
;
258 wxLogApiError(_T("pthread_mutex_lock()"), err
);
261 return wxMUTEX_MISC_ERROR
;
264 wxMutexError
wxMutexInternal::TryLock()
266 int err
= pthread_mutex_trylock(&m_mutex
);
270 // not an error: mutex is already locked, but we're prepared for
275 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
279 return wxMUTEX_NO_ERROR
;
282 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
285 return wxMUTEX_MISC_ERROR
;
288 wxMutexError
wxMutexInternal::Unlock()
290 int err
= pthread_mutex_unlock(&m_mutex
);
294 // we don't own the mutex
295 return wxMUTEX_UNLOCKED
;
298 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
302 return wxMUTEX_NO_ERROR
;
305 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
308 return wxMUTEX_MISC_ERROR
;
311 // ===========================================================================
312 // wxCondition implementation
313 // ===========================================================================
315 // ---------------------------------------------------------------------------
316 // wxConditionInternal
317 // ---------------------------------------------------------------------------
319 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
320 // with a pthread_mutex_t)
321 class wxConditionInternal
324 wxConditionInternal(wxMutex
& mutex
);
325 ~wxConditionInternal();
327 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
330 wxCondError
WaitTimeout(unsigned long milliseconds
);
332 wxCondError
Signal();
333 wxCondError
Broadcast();
336 // get the POSIX mutex associated with us
337 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
340 pthread_cond_t m_cond
;
345 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
348 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
354 wxLogApiError(_T("pthread_cond_init()"), err
);
358 wxConditionInternal::~wxConditionInternal()
362 int err
= pthread_cond_destroy(&m_cond
);
365 wxLogApiError(_T("pthread_cond_destroy()"), err
);
370 wxCondError
wxConditionInternal::Wait()
372 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
375 wxLogApiError(_T("pthread_cond_wait()"), err
);
377 return wxCOND_MISC_ERROR
;
380 return wxCOND_NO_ERROR
;
383 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
385 wxLongLong curtime
= wxGetLocalTimeMillis();
386 curtime
+= milliseconds
;
387 wxLongLong temp
= curtime
/ 1000;
388 int sec
= temp
.GetLo();
390 temp
= curtime
- temp
;
391 int millis
= temp
.GetLo();
396 tspec
.tv_nsec
= millis
* 1000L * 1000L;
398 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
402 return wxCOND_TIMEOUT
;
405 return wxCOND_NO_ERROR
;
408 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
411 return wxCOND_MISC_ERROR
;
414 wxCondError
wxConditionInternal::Signal()
416 int err
= pthread_cond_signal(&m_cond
);
419 wxLogApiError(_T("pthread_cond_signal()"), err
);
421 return wxCOND_MISC_ERROR
;
424 return wxCOND_NO_ERROR
;
427 wxCondError
wxConditionInternal::Broadcast()
429 int err
= pthread_cond_broadcast(&m_cond
);
432 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
434 return wxCOND_MISC_ERROR
;
437 return wxCOND_NO_ERROR
;
440 // ===========================================================================
441 // wxSemaphore implementation
442 // ===========================================================================
444 // ---------------------------------------------------------------------------
445 // wxSemaphoreInternal
446 // ---------------------------------------------------------------------------
448 // we implement the semaphores using mutexes and conditions instead of using
449 // the sem_xxx() POSIX functions because they're not widely available and also
450 // because it's impossible to implement WaitTimeout() using them
451 class wxSemaphoreInternal
454 wxSemaphoreInternal(int initialcount
, int maxcount
);
456 bool IsOk() const { return m_isOk
; }
459 wxSemaError
TryWait();
460 wxSemaError
WaitTimeout(unsigned long milliseconds
);
474 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
478 if ( (initialcount
< 0 || maxcount
< 0) ||
479 ((maxcount
> 0) && (initialcount
> maxcount
)) )
481 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
487 m_maxcount
= (size_t)maxcount
;
488 m_count
= (size_t)initialcount
;
491 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
494 wxSemaError
wxSemaphoreInternal::Wait()
496 wxMutexLocker
locker(m_mutex
);
498 while ( m_count
== 0 )
500 wxLogTrace(TRACE_SEMA
,
501 _T("Thread %ld waiting for semaphore to become signalled"),
502 wxThread::GetCurrentId());
504 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
505 return wxSEMA_MISC_ERROR
;
507 wxLogTrace(TRACE_SEMA
,
508 _T("Thread %ld finished waiting for semaphore, count = %lu"),
509 wxThread::GetCurrentId(), (unsigned long)m_count
);
514 return wxSEMA_NO_ERROR
;
517 wxSemaError
wxSemaphoreInternal::TryWait()
519 wxMutexLocker
locker(m_mutex
);
526 return wxSEMA_NO_ERROR
;
529 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
531 wxMutexLocker
locker(m_mutex
);
533 wxLongLong startTime
= wxGetLocalTimeMillis();
535 while ( m_count
== 0 )
537 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
538 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
539 if ( remainingTime
<= 0 )
542 return wxSEMA_TIMEOUT
;
545 switch ( m_cond
.WaitTimeout(remainingTime
) )
548 return wxSEMA_TIMEOUT
;
551 return wxSEMA_MISC_ERROR
;
553 case wxCOND_NO_ERROR
:
560 return wxSEMA_NO_ERROR
;
563 wxSemaError
wxSemaphoreInternal::Post()
565 wxMutexLocker
locker(m_mutex
);
567 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
569 return wxSEMA_OVERFLOW
;
574 wxLogTrace(TRACE_SEMA
,
575 _T("Thread %ld about to signal semaphore, count = %lu"),
576 wxThread::GetCurrentId(), (unsigned long)m_count
);
578 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
582 // ===========================================================================
583 // wxThread implementation
584 // ===========================================================================
586 // the thread callback functions must have the C linkage
590 #ifdef wxHAVE_PTHREAD_CLEANUP
591 // thread exit function
592 void wxPthreadCleanup(void *ptr
);
593 #endif // wxHAVE_PTHREAD_CLEANUP
595 void *wxPthreadStart(void *ptr
);
599 // ----------------------------------------------------------------------------
601 // ----------------------------------------------------------------------------
603 class wxThreadInternal
609 // thread entry function
610 static void *PthreadStart(wxThread
*thread
);
615 // unblock the thread allowing it to run
616 void SignalRun() { m_semRun
.Post(); }
617 // ask the thread to terminate
619 // go to sleep until Resume() is called
626 int GetPriority() const { return m_prio
; }
627 void SetPriority(int prio
) { m_prio
= prio
; }
629 wxThreadState
GetState() const { return m_state
; }
630 void SetState(wxThreadState state
)
633 static const wxChar
*stateNames
[] =
641 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
642 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
643 #endif // __WXDEBUG__
648 pthread_t
GetId() const { return m_threadId
; }
649 pthread_t
*GetIdPtr() { return &m_threadId
; }
651 void SetCancelFlag() { m_cancelled
= TRUE
; }
652 bool WasCancelled() const { return m_cancelled
; }
654 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
655 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
658 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
659 bool IsReallyPaused() const { return m_isPaused
; }
661 // tell the thread that it is a detached one
664 wxCriticalSectionLocker
lock(m_csJoinFlag
);
666 m_shouldBeJoined
= FALSE
;
670 #ifdef wxHAVE_PTHREAD_CLEANUP
671 // this is used by wxPthreadCleanup() only
672 static void Cleanup(wxThread
*thread
);
673 #endif // wxHAVE_PTHREAD_CLEANUP
676 pthread_t m_threadId
; // id of the thread
677 wxThreadState m_state
; // see wxThreadState enum
678 int m_prio
; // in wxWidgets units: from 0 to 100
680 // this flag is set when the thread should terminate
683 // this flag is set when the thread is blocking on m_semSuspend
686 // the thread exit code - only used for joinable (!detached) threads and
687 // is only valid after the thread termination
688 wxThread::ExitCode m_exitcode
;
690 // many threads may call Wait(), but only one of them should call
691 // pthread_join(), so we have to keep track of this
692 wxCriticalSection m_csJoinFlag
;
693 bool m_shouldBeJoined
;
696 // this semaphore is posted by Run() and the threads Entry() is not
697 // called before it is done
698 wxSemaphore m_semRun
;
700 // this one is signaled when the thread should resume after having been
702 wxSemaphore m_semSuspend
;
705 // ----------------------------------------------------------------------------
706 // thread startup and exit functions
707 // ----------------------------------------------------------------------------
709 void *wxPthreadStart(void *ptr
)
711 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
714 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
716 wxThreadInternal
*pthread
= thread
->m_internal
;
718 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
720 // associate the thread pointer with the newly created thread so that
721 // wxThread::This() will work
722 int rc
= pthread_setspecific(gs_keySelf
, thread
);
725 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
730 // have to declare this before pthread_cleanup_push() which defines a
734 #ifdef wxHAVE_PTHREAD_CLEANUP
735 // install the cleanup handler which will be called if the thread is
737 pthread_cleanup_push(wxPthreadCleanup
, thread
);
738 #endif // wxHAVE_PTHREAD_CLEANUP
740 // wait for the semaphore to be posted from Run()
741 pthread
->m_semRun
.Wait();
743 // test whether we should run the run at all - may be it was deleted
744 // before it started to Run()?
746 wxCriticalSectionLocker
lock(thread
->m_critsect
);
748 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
749 pthread
->WasCancelled();
754 // call the main entry
755 wxLogTrace(TRACE_THREADS
,
756 _T("Thread %ld about to enter its Entry()."),
759 pthread
->m_exitcode
= thread
->Entry();
761 wxLogTrace(TRACE_THREADS
,
762 _T("Thread %ld Entry() returned %lu."),
763 THR_ID(pthread
), (unsigned long)pthread
->m_exitcode
);
766 wxCriticalSectionLocker
lock(thread
->m_critsect
);
768 // change the state of the thread to "exited" so that
769 // wxPthreadCleanup handler won't do anything from now (if it's
770 // called before we do pthread_cleanup_pop below)
771 pthread
->SetState(STATE_EXITED
);
775 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
776 // contains the matching '}' for the '{' in push, so they must be used
777 // in the same block!
778 #ifdef wxHAVE_PTHREAD_CLEANUP
779 // remove the cleanup handler without executing it
780 pthread_cleanup_pop(FALSE
);
781 #endif // wxHAVE_PTHREAD_CLEANUP
785 // FIXME: deleting a possibly joinable thread here???
788 return EXITCODE_CANCELLED
;
792 // terminate the thread
793 thread
->Exit(pthread
->m_exitcode
);
795 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
801 #ifdef wxHAVE_PTHREAD_CLEANUP
803 // this handler is called when the thread is cancelled
804 extern "C" void wxPthreadCleanup(void *ptr
)
806 wxThreadInternal::Cleanup((wxThread
*)ptr
);
809 void wxThreadInternal::Cleanup(wxThread
*thread
)
812 wxCriticalSectionLocker
lock(thread
->m_critsect
);
813 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
815 // thread is already considered as finished.
820 // exit the thread gracefully
821 thread
->Exit(EXITCODE_CANCELLED
);
824 #endif // wxHAVE_PTHREAD_CLEANUP
826 // ----------------------------------------------------------------------------
828 // ----------------------------------------------------------------------------
830 wxThreadInternal::wxThreadInternal()
834 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
838 // set to TRUE only when the thread starts waiting on m_semSuspend
841 // defaults for joinable threads
842 m_shouldBeJoined
= TRUE
;
843 m_isDetached
= FALSE
;
846 wxThreadInternal::~wxThreadInternal()
850 wxThreadError
wxThreadInternal::Run()
852 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
853 wxT("thread may only be started once after Create()") );
855 SetState(STATE_RUNNING
);
857 // wake up threads waiting for our start
860 return wxTHREAD_NO_ERROR
;
863 void wxThreadInternal::Wait()
865 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
867 // if the thread we're waiting for is waiting for the GUI mutex, we will
868 // deadlock so make sure we release it temporarily
869 if ( wxThread::IsMain() )
872 wxLogTrace(TRACE_THREADS
,
873 _T("Starting to wait for thread %ld to exit."),
876 // to avoid memory leaks we should call pthread_join(), but it must only be
877 // done once so use a critical section to serialize the code below
879 wxCriticalSectionLocker
lock(m_csJoinFlag
);
881 if ( m_shouldBeJoined
)
883 // FIXME shouldn't we set cancellation type to DISABLED here? If
884 // we're cancelled inside pthread_join(), things will almost
885 // certainly break - but if we disable the cancellation, we
887 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
889 // this is a serious problem, so use wxLogError and not
890 // wxLogDebug: it is possible to bring the system to its knees
891 // by creating too many threads and not joining them quite
893 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
896 m_shouldBeJoined
= FALSE
;
900 // reacquire GUI mutex
901 if ( wxThread::IsMain() )
905 void wxThreadInternal::Pause()
907 // the state is set from the thread which pauses us first, this function
908 // is called later so the state should have been already set
909 wxCHECK_RET( m_state
== STATE_PAUSED
,
910 wxT("thread must first be paused with wxThread::Pause().") );
912 wxLogTrace(TRACE_THREADS
,
913 _T("Thread %ld goes to sleep."), THR_ID(this));
915 // wait until the semaphore is Post()ed from Resume()
919 void wxThreadInternal::Resume()
921 wxCHECK_RET( m_state
== STATE_PAUSED
,
922 wxT("can't resume thread which is not suspended.") );
924 // the thread might be not actually paused yet - if there were no call to
925 // TestDestroy() since the last call to Pause() for example
926 if ( IsReallyPaused() )
928 wxLogTrace(TRACE_THREADS
,
929 _T("Waking up thread %ld"), THR_ID(this));
935 SetReallyPaused(FALSE
);
939 wxLogTrace(TRACE_THREADS
,
940 _T("Thread %ld is not yet really paused"), THR_ID(this));
943 SetState(STATE_RUNNING
);
946 // -----------------------------------------------------------------------------
947 // wxThread static functions
948 // -----------------------------------------------------------------------------
950 wxThread
*wxThread::This()
952 return (wxThread
*)pthread_getspecific(gs_keySelf
);
955 bool wxThread::IsMain()
957 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
960 void wxThread::Yield()
962 #ifdef HAVE_SCHED_YIELD
967 void wxThread::Sleep(unsigned long milliseconds
)
969 wxMilliSleep(milliseconds
);
972 int wxThread::GetCPUCount()
974 #if defined(__LINUX__) && wxUSE_FFILE
975 // read from proc (can't use wxTextFile here because it's a special file:
976 // it has 0 size but still can be read from)
979 wxFFile
file(_T("/proc/cpuinfo"));
980 if ( file
.IsOpened() )
982 // slurp the whole file
984 if ( file
.ReadAll(&s
) )
986 // (ab)use Replace() to find the number of "processor: num" strings
987 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
993 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
997 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1000 #elif defined(_SC_NPROCESSORS_ONLN)
1001 // this works for Solaris
1002 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1007 #endif // different ways to get number of CPUs
1013 // VMS is a 64 bit system and threads have 64 bit pointers.
1014 // FIXME: also needed for other systems????
1016 unsigned long long wxThread::GetCurrentId()
1018 return (unsigned long long)pthread_self();
1023 unsigned long wxThread::GetCurrentId()
1025 return (unsigned long)pthread_self();
1028 #endif // __VMS/!__VMS
1031 bool wxThread::SetConcurrency(size_t level
)
1033 #ifdef HAVE_THR_SETCONCURRENCY
1034 int rc
= thr_setconcurrency(level
);
1037 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1041 #else // !HAVE_THR_SETCONCURRENCY
1042 // ok only for the default value
1044 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1047 // -----------------------------------------------------------------------------
1049 // -----------------------------------------------------------------------------
1051 wxThread::wxThread(wxThreadKind kind
)
1053 // add this thread to the global list of all threads
1054 gs_allThreads
.Add(this);
1056 m_internal
= new wxThreadInternal();
1058 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1061 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1063 if ( m_internal
->GetState() != STATE_NEW
)
1065 // don't recreate thread
1066 return wxTHREAD_RUNNING
;
1069 // set up the thread attribute: right now, we only set thread priority
1070 pthread_attr_t attr
;
1071 pthread_attr_init(&attr
);
1073 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1075 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1077 wxLogError(_("Cannot retrieve thread scheduling policy."));
1081 /* the pthread.h contains too many spaces. This is a work-around */
1082 # undef sched_get_priority_max
1083 #undef sched_get_priority_min
1084 #define sched_get_priority_max(_pol_) \
1085 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1086 #define sched_get_priority_min(_pol_) \
1087 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1090 int max_prio
= sched_get_priority_max(policy
),
1091 min_prio
= sched_get_priority_min(policy
),
1092 prio
= m_internal
->GetPriority();
1094 if ( min_prio
== -1 || max_prio
== -1 )
1096 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1099 else if ( max_prio
== min_prio
)
1101 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1103 // notify the programmer that this doesn't work here
1104 wxLogWarning(_("Thread priority setting is ignored."));
1106 //else: we have default priority, so don't complain
1108 // anyhow, don't do anything because priority is just ignored
1112 struct sched_param sp
;
1113 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1115 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1118 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1120 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1122 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1125 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1127 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1128 // this will make the threads created by this process really concurrent
1129 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1131 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1133 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1135 // VZ: assume that this one is always available (it's rather fundamental),
1136 // if this function is ever missing we should try to use
1137 // pthread_detach() instead (after thread creation)
1140 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1142 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1145 // never try to join detached threads
1146 m_internal
->Detach();
1148 //else: threads are created joinable by default, it's ok
1150 // create the new OS thread object
1151 int rc
= pthread_create
1153 m_internal
->GetIdPtr(),
1159 if ( pthread_attr_destroy(&attr
) != 0 )
1161 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1166 m_internal
->SetState(STATE_EXITED
);
1168 return wxTHREAD_NO_RESOURCE
;
1171 return wxTHREAD_NO_ERROR
;
1174 wxThreadError
wxThread::Run()
1176 wxCriticalSectionLocker
lock(m_critsect
);
1178 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1179 wxT("must call wxThread::Create() first") );
1181 return m_internal
->Run();
1184 // -----------------------------------------------------------------------------
1186 // -----------------------------------------------------------------------------
1188 void wxThread::SetPriority(unsigned int prio
)
1190 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1191 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1192 wxT("invalid thread priority") );
1194 wxCriticalSectionLocker
lock(m_critsect
);
1196 switch ( m_internal
->GetState() )
1199 // thread not yet started, priority will be set when it is
1200 m_internal
->SetPriority(prio
);
1205 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1206 #if defined(__LINUX__)
1207 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1208 // a priority other than 0. Instead, we use the BSD setpriority
1209 // which alllows us to set a 'nice' value between 20 to -20. Only
1210 // super user can set a value less than zero (more negative yields
1211 // higher priority). setpriority set the static priority of a process,
1212 // but this is OK since Linux is configured as a thread per process.
1218 // Map Wx priorites (WXTHREAD_MIN_PRIORITY -
1219 // WXTHREAD_MAX_PRIORITY) into BSD priorities (20 - -20).
1220 // Do calculation of values instead of hard coding them
1221 // to make maintenance easier.
1223 pSpan
= ((float)(WXTHREAD_MAX_PRIORITY
- WXTHREAD_MIN_PRIORITY
)) / 2.0;
1225 // prio starts as ................... // value => (0) >= p <= (n)
1227 fPrio
= ((float)prio
) - pSpan
; // value => (-n) >= p <= (+n)
1229 fPrio
= 0.0 - fPrio
; // value => (+n) <= p >= (-n)
1231 fPrio
= fPrio
* (20. / pSpan
) + .5; // value => (20) <= p >= (-20)
1235 // Clamp prio from 20 - -20;
1236 iPrio
= (iPrio
> 20) ? 20 : iPrio
;
1237 iPrio
= (iPrio
< -20) ? -20 : iPrio
;
1239 if (setpriority(PRIO_PROCESS
, 0, iPrio
) == -1)
1241 wxLogError(_("Failed to set thread priority %d."), prio
);
1246 struct sched_param sparam
;
1247 sparam
.sched_priority
= prio
;
1249 if ( pthread_setschedparam(m_internal
->GetId(),
1250 SCHED_OTHER
, &sparam
) != 0 )
1252 wxLogError(_("Failed to set thread priority %d."), prio
);
1256 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1261 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1265 unsigned int wxThread::GetPriority() const
1267 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1269 return m_internal
->GetPriority();
1272 wxThreadIdType
wxThread::GetId() const
1274 return (wxThreadIdType
) m_internal
->GetId();
1277 // -----------------------------------------------------------------------------
1279 // -----------------------------------------------------------------------------
1281 wxThreadError
wxThread::Pause()
1283 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1284 _T("a thread can't pause itself") );
1286 wxCriticalSectionLocker
lock(m_critsect
);
1288 if ( m_internal
->GetState() != STATE_RUNNING
)
1290 wxLogDebug(wxT("Can't pause thread which is not running."));
1292 return wxTHREAD_NOT_RUNNING
;
1295 // just set a flag, the thread will be really paused only during the next
1296 // call to TestDestroy()
1297 m_internal
->SetState(STATE_PAUSED
);
1299 return wxTHREAD_NO_ERROR
;
1302 wxThreadError
wxThread::Resume()
1304 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1305 _T("a thread can't resume itself") );
1307 wxCriticalSectionLocker
lock(m_critsect
);
1309 wxThreadState state
= m_internal
->GetState();
1314 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1317 m_internal
->Resume();
1319 return wxTHREAD_NO_ERROR
;
1322 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1324 return wxTHREAD_NO_ERROR
;
1327 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1329 return wxTHREAD_MISC_ERROR
;
1333 // -----------------------------------------------------------------------------
1335 // -----------------------------------------------------------------------------
1337 wxThread::ExitCode
wxThread::Wait()
1339 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1340 _T("a thread can't wait for itself") );
1342 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1343 _T("can't wait for detached thread") );
1347 return m_internal
->GetExitCode();
1350 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1352 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1353 _T("a thread can't delete itself") );
1355 bool isDetached
= m_isDetached
;
1358 wxThreadState state
= m_internal
->GetState();
1360 // ask the thread to stop
1361 m_internal
->SetCancelFlag();
1368 // we need to wake up the thread so that PthreadStart() will
1369 // terminate - right now it's blocking on run semaphore in
1371 m_internal
->SignalRun();
1380 // resume the thread first
1381 m_internal
->Resume();
1388 // wait until the thread stops
1393 // return the exit code of the thread
1394 *rc
= m_internal
->GetExitCode();
1397 //else: can't wait for detached threads
1400 return wxTHREAD_NO_ERROR
;
1403 wxThreadError
wxThread::Kill()
1405 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1406 _T("a thread can't kill itself") );
1408 switch ( m_internal
->GetState() )
1412 return wxTHREAD_NOT_RUNNING
;
1415 // resume the thread first
1421 #ifdef HAVE_PTHREAD_CANCEL
1422 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1425 wxLogError(_("Failed to terminate a thread."));
1427 return wxTHREAD_MISC_ERROR
;
1432 // if we use cleanup function, this will be done from
1433 // wxPthreadCleanup()
1434 #ifndef wxHAVE_PTHREAD_CLEANUP
1435 ScheduleThreadForDeletion();
1437 // don't call OnExit() here, it can only be called in the
1438 // threads context and we're in the context of another thread
1441 #endif // wxHAVE_PTHREAD_CLEANUP
1445 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1448 return wxTHREAD_NO_ERROR
;
1452 void wxThread::Exit(ExitCode status
)
1454 wxASSERT_MSG( This() == this,
1455 _T("wxThread::Exit() can only be called in the context of the same thread") );
1459 // from the moment we call OnExit(), the main program may terminate at
1460 // any moment, so mark this thread as being already in process of being
1461 // deleted or wxThreadModule::OnExit() will try to delete it again
1462 ScheduleThreadForDeletion();
1465 // don't enter m_critsect before calling OnExit() because the user code
1466 // might deadlock if, for example, it signals a condition in OnExit() (a
1467 // common case) while the main thread calls any of functions entering
1468 // m_critsect on us (almost all of them do)
1471 // delete C++ thread object if this is a detached thread - user is
1472 // responsible for doing this for joinable ones
1475 // FIXME I'm feeling bad about it - what if another thread function is
1476 // called (in another thread context) now? It will try to access
1477 // half destroyed object which will probably result in something
1478 // very bad - but we can't protect this by a crit section unless
1479 // we make it a global object, but this would mean that we can
1480 // only call one thread function at a time :-(
1486 m_internal
->SetState(STATE_EXITED
);
1490 // terminate the thread (pthread_exit() never returns)
1491 pthread_exit(status
);
1493 wxFAIL_MSG(_T("pthread_exit() failed"));
1496 // also test whether we were paused
1497 bool wxThread::TestDestroy()
1499 wxASSERT_MSG( This() == this,
1500 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1504 if ( m_internal
->GetState() == STATE_PAUSED
)
1506 m_internal
->SetReallyPaused(TRUE
);
1508 // leave the crit section or the other threads will stop too if they
1509 // try to call any of (seemingly harmless) IsXXX() functions while we
1513 m_internal
->Pause();
1517 // thread wasn't requested to pause, nothing to do
1521 return m_internal
->WasCancelled();
1524 wxThread::~wxThread()
1529 // check that the thread either exited or couldn't be created
1530 if ( m_internal
->GetState() != STATE_EXITED
&&
1531 m_internal
->GetState() != STATE_NEW
)
1533 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."), GetId());
1537 #endif // __WXDEBUG__
1541 // remove this thread from the global array
1542 gs_allThreads
.Remove(this);
1545 // -----------------------------------------------------------------------------
1547 // -----------------------------------------------------------------------------
1549 bool wxThread::IsRunning() const
1551 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1553 return m_internal
->GetState() == STATE_RUNNING
;
1556 bool wxThread::IsAlive() const
1558 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1560 switch ( m_internal
->GetState() )
1571 bool wxThread::IsPaused() const
1573 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1575 return (m_internal
->GetState() == STATE_PAUSED
);
1578 //--------------------------------------------------------------------
1580 //--------------------------------------------------------------------
1582 class wxThreadModule
: public wxModule
1585 virtual bool OnInit();
1586 virtual void OnExit();
1589 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1592 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1594 bool wxThreadModule::OnInit()
1596 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1599 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1604 gs_tidMain
= pthread_self();
1606 gs_mutexGui
= new wxMutex();
1607 gs_mutexGui
->Lock();
1609 gs_mutexDeleteThread
= new wxMutex();
1610 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1615 void wxThreadModule::OnExit()
1617 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1619 // are there any threads left which are being deleted right now?
1620 size_t nThreadsBeingDeleted
;
1623 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1624 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1626 if ( nThreadsBeingDeleted
> 0 )
1628 wxLogTrace(TRACE_THREADS
,
1629 _T("Waiting for %lu threads to disappear"),
1630 (unsigned long)nThreadsBeingDeleted
);
1632 // have to wait until all of them disappear
1633 gs_condAllDeleted
->Wait();
1637 // terminate any threads left
1638 size_t count
= gs_allThreads
.GetCount();
1641 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1642 (unsigned long)count
);
1645 for ( size_t n
= 0u; n
< count
; n
++ )
1647 // Delete calls the destructor which removes the current entry. We
1648 // should only delete the first one each time.
1649 gs_allThreads
[0]->Delete();
1652 // destroy GUI mutex
1653 gs_mutexGui
->Unlock();
1656 // and free TLD slot
1657 (void)pthread_key_delete(gs_keySelf
);
1659 delete gs_condAllDeleted
;
1660 delete gs_mutexDeleteThread
;
1663 // ----------------------------------------------------------------------------
1665 // ----------------------------------------------------------------------------
1667 static void ScheduleThreadForDeletion()
1669 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1671 gs_nThreadsBeingDeleted
++;
1673 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1674 (unsigned long)gs_nThreadsBeingDeleted
,
1675 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1678 static void DeleteThread(wxThread
*This
)
1680 // gs_mutexDeleteThread should be unlocked before signalling the condition
1681 // or wxThreadModule::OnExit() would deadlock
1682 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1684 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1688 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1689 _T("no threads scheduled for deletion, yet we delete one?") );
1691 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1692 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1694 if ( !--gs_nThreadsBeingDeleted
)
1696 // no more threads left, signal it
1697 gs_condAllDeleted
->Signal();
1701 void wxMutexGuiEnter()
1703 gs_mutexGui
->Lock();
1706 void wxMutexGuiLeave()
1708 gs_mutexGui
->Unlock();
1711 // ----------------------------------------------------------------------------
1712 // include common implementation code
1713 // ----------------------------------------------------------------------------
1715 #include "wx/thrimpl.cpp"
1717 #endif // wxUSE_THREADS