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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
25 #pragma implementation "thread.h"
28 // for compilers that support precompilation, includes "wx.h".
29 #include "wx/wxprec.h"
33 #include "wx/thread.h"
34 #include "wx/module.h"
38 #include "wx/dynarray.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(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 // the id of the main thread
116 static pthread_t gs_tidMain
;
118 // the key for the pointer to the associated wxThread object
119 static pthread_key_t gs_keySelf
;
121 // the number of threads which are being deleted - the program won't exit
122 // until there are any left
123 static size_t gs_nThreadsBeingDeleted
= 0;
125 // a mutex to protect gs_nThreadsBeingDeleted
126 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
128 // and a condition variable which will be signaled when all
129 // gs_nThreadsBeingDeleted will have been deleted
130 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
132 // this mutex must be acquired before any call to a GUI function
133 // (it's not inside #if wxUSE_GUI because this file is compiled as part
135 static wxMutex
*gs_mutexGui
= NULL
;
137 // when we wait for a thread to exit, we're blocking on a condition which the
138 // thread signals in its SignalExit() method -- but this condition can't be a
139 // member of the thread itself as a detached thread may delete itself at any
140 // moment and accessing the condition member of the thread after this would
141 // result in a disaster
143 // so instead we maintain a global list of the structs below for the threads
144 // we're interested in waiting on
146 // ============================================================================
147 // wxMutex implementation
148 // ============================================================================
150 // ----------------------------------------------------------------------------
152 // ----------------------------------------------------------------------------
154 // this is a simple wrapper around pthread_mutex_t which provides error
156 class wxMutexInternal
159 wxMutexInternal(wxMutexType mutexType
);
163 wxMutexError
TryLock();
164 wxMutexError
Unlock();
166 bool IsOk() const { return m_isOk
; }
169 pthread_mutex_t m_mutex
;
172 // wxConditionInternal uses our m_mutex
173 friend class wxConditionInternal
;
176 #ifdef HAVE_PTHREAD_MUTEXATTR_T
177 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
178 // in the library, otherwise we wouldn't compile this code at all)
179 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
182 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
187 case wxMUTEX_RECURSIVE
:
188 // support recursive locks like Win32, i.e. a thread can lock a
189 // mutex which it had itself already locked
191 // unfortunately initialization of recursive mutexes is non
192 // portable, so try several methods
193 #ifdef HAVE_PTHREAD_MUTEXATTR_T
195 pthread_mutexattr_t attr
;
196 pthread_mutexattr_init(&attr
);
197 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
199 err
= pthread_mutex_init(&m_mutex
, &attr
);
201 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
202 // we can use this only as initializer so we have to assign it
203 // first to a temp var - assigning directly to m_mutex wouldn't
206 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
209 #else // no recursive mutexes
211 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
215 wxFAIL_MSG( _T("unknown mutex type") );
218 case wxMUTEX_DEFAULT
:
219 err
= pthread_mutex_init(&m_mutex
, NULL
);
226 wxLogApiError( wxT("pthread_mutex_init()"), err
);
230 wxMutexInternal::~wxMutexInternal()
234 int err
= pthread_mutex_destroy(&m_mutex
);
237 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
242 wxMutexError
wxMutexInternal::Lock()
244 int err
= pthread_mutex_lock(&m_mutex
);
248 // only error checking mutexes return this value and so it's an
249 // unexpected situation -- hence use assert, not wxLogDebug
250 wxFAIL_MSG( _T("mutex deadlock prevented") );
251 return wxMUTEX_DEAD_LOCK
;
254 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
258 return wxMUTEX_NO_ERROR
;
261 wxLogApiError(_T("pthread_mutex_lock()"), err
);
264 return wxMUTEX_MISC_ERROR
;
267 wxMutexError
wxMutexInternal::TryLock()
269 int err
= pthread_mutex_trylock(&m_mutex
);
273 // not an error: mutex is already locked, but we're prepared for
278 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
282 return wxMUTEX_NO_ERROR
;
285 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
288 return wxMUTEX_MISC_ERROR
;
291 wxMutexError
wxMutexInternal::Unlock()
293 int err
= pthread_mutex_unlock(&m_mutex
);
297 // we don't own the mutex
298 return wxMUTEX_UNLOCKED
;
301 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
305 return wxMUTEX_NO_ERROR
;
308 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
311 return wxMUTEX_MISC_ERROR
;
314 // ===========================================================================
315 // wxCondition implementation
316 // ===========================================================================
318 // ---------------------------------------------------------------------------
319 // wxConditionInternal
320 // ---------------------------------------------------------------------------
322 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
323 // with a pthread_mutex_t)
324 class wxConditionInternal
327 wxConditionInternal(wxMutex
& mutex
);
328 ~wxConditionInternal();
330 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
333 wxCondError
WaitTimeout(unsigned long milliseconds
);
335 wxCondError
Signal();
336 wxCondError
Broadcast();
339 // get the POSIX mutex associated with us
340 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
343 pthread_cond_t m_cond
;
348 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
351 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
357 wxLogApiError(_T("pthread_cond_init()"), err
);
361 wxConditionInternal::~wxConditionInternal()
365 int err
= pthread_cond_destroy(&m_cond
);
368 wxLogApiError(_T("pthread_cond_destroy()"), err
);
373 wxCondError
wxConditionInternal::Wait()
375 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
378 wxLogApiError(_T("pthread_cond_wait()"), err
);
380 return wxCOND_MISC_ERROR
;
383 return wxCOND_NO_ERROR
;
386 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
388 wxLongLong curtime
= wxGetLocalTimeMillis();
389 curtime
+= milliseconds
;
390 wxLongLong temp
= curtime
/ 1000;
391 int sec
= temp
.GetLo();
393 temp
= curtime
- temp
;
394 int millis
= temp
.GetLo();
399 tspec
.tv_nsec
= millis
* 1000L * 1000L;
401 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
405 return wxCOND_TIMEOUT
;
408 return wxCOND_NO_ERROR
;
411 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
414 return wxCOND_MISC_ERROR
;
417 wxCondError
wxConditionInternal::Signal()
419 int err
= pthread_cond_signal(&m_cond
);
422 wxLogApiError(_T("pthread_cond_signal()"), err
);
424 return wxCOND_MISC_ERROR
;
427 return wxCOND_NO_ERROR
;
430 wxCondError
wxConditionInternal::Broadcast()
432 int err
= pthread_cond_broadcast(&m_cond
);
435 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
437 return wxCOND_MISC_ERROR
;
440 return wxCOND_NO_ERROR
;
443 // ===========================================================================
444 // wxSemaphore implementation
445 // ===========================================================================
447 // ---------------------------------------------------------------------------
448 // wxSemaphoreInternal
449 // ---------------------------------------------------------------------------
451 // we implement the semaphores using mutexes and conditions instead of using
452 // the sem_xxx() POSIX functions because they're not widely available and also
453 // because it's impossible to implement WaitTimeout() using them
454 class wxSemaphoreInternal
457 wxSemaphoreInternal(int initialcount
, int maxcount
);
459 bool IsOk() const { return m_isOk
; }
462 wxSemaError
TryWait();
463 wxSemaError
WaitTimeout(unsigned long milliseconds
);
477 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
481 if ( (initialcount
< 0 || maxcount
< 0) ||
482 ((maxcount
> 0) && (initialcount
> maxcount
)) )
484 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
490 m_maxcount
= (size_t)maxcount
;
491 m_count
= (size_t)initialcount
;
494 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
497 wxSemaError
wxSemaphoreInternal::Wait()
499 wxMutexLocker
locker(m_mutex
);
501 while ( m_count
== 0 )
503 wxLogTrace(TRACE_SEMA
,
504 _T("Thread %ld waiting for semaphore to become signalled"),
505 wxThread::GetCurrentId());
507 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
508 return wxSEMA_MISC_ERROR
;
510 wxLogTrace(TRACE_SEMA
,
511 _T("Thread %ld finished waiting for semaphore, count = %lu"),
512 wxThread::GetCurrentId(), (unsigned long)m_count
);
517 return wxSEMA_NO_ERROR
;
520 wxSemaError
wxSemaphoreInternal::TryWait()
522 wxMutexLocker
locker(m_mutex
);
529 return wxSEMA_NO_ERROR
;
532 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
534 wxMutexLocker
locker(m_mutex
);
536 wxLongLong startTime
= wxGetLocalTimeMillis();
538 while ( m_count
== 0 )
540 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
541 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
542 if ( remainingTime
<= 0 )
545 return wxSEMA_TIMEOUT
;
548 switch ( m_cond
.WaitTimeout(remainingTime
) )
551 return wxSEMA_TIMEOUT
;
554 return wxSEMA_MISC_ERROR
;
556 case wxCOND_NO_ERROR
:
563 return wxSEMA_NO_ERROR
;
566 wxSemaError
wxSemaphoreInternal::Post()
568 wxMutexLocker
locker(m_mutex
);
570 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
572 return wxSEMA_OVERFLOW
;
577 wxLogTrace(TRACE_SEMA
,
578 _T("Thread %ld about to signal semaphore, count = %lu"),
579 wxThread::GetCurrentId(), (unsigned long)m_count
);
581 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
585 // ===========================================================================
586 // wxThread implementation
587 // ===========================================================================
589 // the thread callback functions must have the C linkage
593 #if HAVE_THREAD_CLEANUP_FUNCTIONS
594 // thread exit function
595 void wxPthreadCleanup(void *ptr
);
596 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
598 void *wxPthreadStart(void *ptr
);
602 // ----------------------------------------------------------------------------
604 // ----------------------------------------------------------------------------
606 class wxThreadInternal
612 // thread entry function
613 static void *PthreadStart(wxThread
*thread
);
618 // unblock the thread allowing it to run
619 void SignalRun() { m_semRun
.Post(); }
620 // ask the thread to terminate
622 // go to sleep until Resume() is called
629 int GetPriority() const { return m_prio
; }
630 void SetPriority(int prio
) { m_prio
= prio
; }
632 wxThreadState
GetState() const { return m_state
; }
633 void SetState(wxThreadState state
)
636 static const wxChar
*stateNames
[] =
644 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
645 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
646 #endif // __WXDEBUG__
651 pthread_t
GetId() const { return m_threadId
; }
652 pthread_t
*GetIdPtr() { return &m_threadId
; }
654 void SetCancelFlag() { m_cancelled
= TRUE
; }
655 bool WasCancelled() const { return m_cancelled
; }
657 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
658 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
661 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
662 bool IsReallyPaused() const { return m_isPaused
; }
664 // tell the thread that it is a detached one
667 wxCriticalSectionLocker
lock(m_csJoinFlag
);
669 m_shouldBeJoined
= FALSE
;
673 #if HAVE_THREAD_CLEANUP_FUNCTIONS
674 // this is used by wxPthreadCleanup() only
675 static void Cleanup(wxThread
*thread
);
676 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
679 pthread_t m_threadId
; // id of the thread
680 wxThreadState m_state
; // see wxThreadState enum
681 int m_prio
; // in wxWindows units: from 0 to 100
683 // this flag is set when the thread should terminate
686 // this flag is set when the thread is blocking on m_semSuspend
689 // the thread exit code - only used for joinable (!detached) threads and
690 // is only valid after the thread termination
691 wxThread::ExitCode m_exitcode
;
693 // many threads may call Wait(), but only one of them should call
694 // pthread_join(), so we have to keep track of this
695 wxCriticalSection m_csJoinFlag
;
696 bool m_shouldBeJoined
;
699 // this semaphore is posted by Run() and the threads Entry() is not
700 // called before it is done
701 wxSemaphore m_semRun
;
703 // this one is signaled when the thread should resume after having been
705 wxSemaphore m_semSuspend
;
708 // ----------------------------------------------------------------------------
709 // thread startup and exit functions
710 // ----------------------------------------------------------------------------
712 void *wxPthreadStart(void *ptr
)
714 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
717 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
719 wxThreadInternal
*pthread
= thread
->m_internal
;
721 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
723 // associate the thread pointer with the newly created thread so that
724 // wxThread::This() will work
725 int rc
= pthread_setspecific(gs_keySelf
, thread
);
728 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
733 // have to declare this before pthread_cleanup_push() which defines a
737 #if HAVE_THREAD_CLEANUP_FUNCTIONS
738 // install the cleanup handler which will be called if the thread is
740 pthread_cleanup_push(wxPthreadCleanup
, thread
);
741 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
743 // wait for the semaphore to be posted from Run()
744 pthread
->m_semRun
.Wait();
746 // test whether we should run the run at all - may be it was deleted
747 // before it started to Run()?
749 wxCriticalSectionLocker
lock(thread
->m_critsect
);
751 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
752 pthread
->WasCancelled();
757 // call the main entry
758 wxLogTrace(TRACE_THREADS
,
759 _T("Thread %ld about to enter its Entry()."),
762 pthread
->m_exitcode
= thread
->Entry();
764 wxLogTrace(TRACE_THREADS
,
765 _T("Thread %ld Entry() returned %lu."),
766 THR_ID(pthread
), (unsigned long)pthread
->m_exitcode
);
769 wxCriticalSectionLocker
lock(thread
->m_critsect
);
771 // change the state of the thread to "exited" so that
772 // wxPthreadCleanup handler won't do anything from now (if it's
773 // called before we do pthread_cleanup_pop below)
774 pthread
->SetState(STATE_EXITED
);
778 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
779 // contains the matching '}' for the '{' in push, so they must be used
780 // in the same block!
781 #if HAVE_THREAD_CLEANUP_FUNCTIONS
782 // remove the cleanup handler without executing it
783 pthread_cleanup_pop(FALSE
);
784 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
788 // FIXME: deleting a possibly joinable thread here???
791 return EXITCODE_CANCELLED
;
795 // terminate the thread
796 thread
->Exit(pthread
->m_exitcode
);
798 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
804 #if HAVE_THREAD_CLEANUP_FUNCTIONS
806 // this handler is called when the thread is cancelled
807 extern "C" void wxPthreadCleanup(void *ptr
)
809 wxThreadInternal::Cleanup((wxThread
*)ptr
);
812 void wxThreadInternal::Cleanup(wxThread
*thread
)
815 wxCriticalSectionLocker
lock(thread
->m_critsect
);
816 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
818 // thread is already considered as finished.
823 // exit the thread gracefully
824 thread
->Exit(EXITCODE_CANCELLED
);
827 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
829 // ----------------------------------------------------------------------------
831 // ----------------------------------------------------------------------------
833 wxThreadInternal::wxThreadInternal()
837 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
841 // set to TRUE only when the thread starts waiting on m_semSuspend
844 // defaults for joinable threads
845 m_shouldBeJoined
= TRUE
;
846 m_isDetached
= FALSE
;
849 wxThreadInternal::~wxThreadInternal()
853 wxThreadError
wxThreadInternal::Run()
855 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
856 wxT("thread may only be started once after Create()") );
858 SetState(STATE_RUNNING
);
860 // wake up threads waiting for our start
863 return wxTHREAD_NO_ERROR
;
866 void wxThreadInternal::Wait()
868 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
870 // if the thread we're waiting for is waiting for the GUI mutex, we will
871 // deadlock so make sure we release it temporarily
872 if ( wxThread::IsMain() )
875 wxLogTrace(TRACE_THREADS
,
876 _T("Starting to wait for thread %ld to exit."),
879 // to avoid memory leaks we should call pthread_join(), but it must only be
880 // done once so use a critical section to serialize the code below
882 wxCriticalSectionLocker
lock(m_csJoinFlag
);
884 if ( m_shouldBeJoined
)
886 // FIXME shouldn't we set cancellation type to DISABLED here? If
887 // we're cancelled inside pthread_join(), things will almost
888 // certainly break - but if we disable the cancellation, we
890 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
892 // this is a serious problem, so use wxLogError and not
893 // wxLogDebug: it is possible to bring the system to its knees
894 // by creating too many threads and not joining them quite
896 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
899 m_shouldBeJoined
= FALSE
;
903 // reacquire GUI mutex
904 if ( wxThread::IsMain() )
908 void wxThreadInternal::Pause()
910 // the state is set from the thread which pauses us first, this function
911 // is called later so the state should have been already set
912 wxCHECK_RET( m_state
== STATE_PAUSED
,
913 wxT("thread must first be paused with wxThread::Pause().") );
915 wxLogTrace(TRACE_THREADS
,
916 _T("Thread %ld goes to sleep."), THR_ID(this));
918 // wait until the semaphore is Post()ed from Resume()
922 void wxThreadInternal::Resume()
924 wxCHECK_RET( m_state
== STATE_PAUSED
,
925 wxT("can't resume thread which is not suspended.") );
927 // the thread might be not actually paused yet - if there were no call to
928 // TestDestroy() since the last call to Pause() for example
929 if ( IsReallyPaused() )
931 wxLogTrace(TRACE_THREADS
,
932 _T("Waking up thread %ld"), THR_ID(this));
938 SetReallyPaused(FALSE
);
942 wxLogTrace(TRACE_THREADS
,
943 _T("Thread %ld is not yet really paused"), THR_ID(this));
946 SetState(STATE_RUNNING
);
949 // -----------------------------------------------------------------------------
950 // wxThread static functions
951 // -----------------------------------------------------------------------------
953 wxThread
*wxThread::This()
955 return (wxThread
*)pthread_getspecific(gs_keySelf
);
958 bool wxThread::IsMain()
960 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
963 void wxThread::Yield()
965 #ifdef HAVE_SCHED_YIELD
970 void wxThread::Sleep(unsigned long milliseconds
)
972 wxUsleep(milliseconds
);
975 int wxThread::GetCPUCount()
977 #if defined(__LINUX__) && wxUSE_FFILE
978 // read from proc (can't use wxTextFile here because it's a special file:
979 // it has 0 size but still can be read from)
982 wxFFile
file(_T("/proc/cpuinfo"));
983 if ( file
.IsOpened() )
985 // slurp the whole file
987 if ( file
.ReadAll(&s
) )
989 // (ab)use Replace() to find the number of "processor: num" strings
990 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
996 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1000 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1003 #elif defined(_SC_NPROCESSORS_ONLN)
1004 // this works for Solaris
1005 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1010 #endif // different ways to get number of CPUs
1016 // VMS is a 64 bit system and threads have 64 bit pointers.
1017 // FIXME: also needed for other systems????
1019 unsigned long long wxThread::GetCurrentId()
1021 return (unsigned long long)pthread_self();
1026 unsigned long wxThread::GetCurrentId()
1028 return (unsigned long)pthread_self();
1031 #endif // __VMS/!__VMS
1034 bool wxThread::SetConcurrency(size_t level
)
1036 #ifdef HAVE_THR_SETCONCURRENCY
1037 int rc
= thr_setconcurrency(level
);
1040 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1044 #else // !HAVE_THR_SETCONCURRENCY
1045 // ok only for the default value
1047 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1050 // -----------------------------------------------------------------------------
1052 // -----------------------------------------------------------------------------
1054 wxThread::wxThread(wxThreadKind kind
)
1056 // add this thread to the global list of all threads
1057 gs_allThreads
.Add(this);
1059 m_internal
= new wxThreadInternal();
1061 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1064 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1066 if ( m_internal
->GetState() != STATE_NEW
)
1068 // don't recreate thread
1069 return wxTHREAD_RUNNING
;
1072 // set up the thread attribute: right now, we only set thread priority
1073 pthread_attr_t attr
;
1074 pthread_attr_init(&attr
);
1076 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1078 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1080 wxLogError(_("Cannot retrieve thread scheduling policy."));
1084 /* the pthread.h contains too many spaces. This is a work-around */
1085 # undef sched_get_priority_max
1086 #undef sched_get_priority_min
1087 #define sched_get_priority_max(_pol_) \
1088 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1089 #define sched_get_priority_min(_pol_) \
1090 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1093 int max_prio
= sched_get_priority_max(policy
),
1094 min_prio
= sched_get_priority_min(policy
),
1095 prio
= m_internal
->GetPriority();
1097 if ( min_prio
== -1 || max_prio
== -1 )
1099 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1102 else if ( max_prio
== min_prio
)
1104 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1106 // notify the programmer that this doesn't work here
1107 wxLogWarning(_("Thread priority setting is ignored."));
1109 //else: we have default priority, so don't complain
1111 // anyhow, don't do anything because priority is just ignored
1115 struct sched_param sp
;
1116 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1118 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1121 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1123 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1125 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1128 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1130 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1131 // this will make the threads created by this process really concurrent
1132 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1134 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1136 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1138 // VZ: assume that this one is always available (it's rather fundamental),
1139 // if this function is ever missing we should try to use
1140 // pthread_detach() instead (after thread creation)
1143 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1145 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1148 // never try to join detached threads
1149 m_internal
->Detach();
1151 //else: threads are created joinable by default, it's ok
1153 // create the new OS thread object
1154 int rc
= pthread_create
1156 m_internal
->GetIdPtr(),
1162 if ( pthread_attr_destroy(&attr
) != 0 )
1164 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1169 m_internal
->SetState(STATE_EXITED
);
1171 return wxTHREAD_NO_RESOURCE
;
1174 return wxTHREAD_NO_ERROR
;
1177 wxThreadError
wxThread::Run()
1179 wxCriticalSectionLocker
lock(m_critsect
);
1181 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1182 wxT("must call wxThread::Create() first") );
1184 return m_internal
->Run();
1187 // -----------------------------------------------------------------------------
1189 // -----------------------------------------------------------------------------
1191 void wxThread::SetPriority(unsigned int prio
)
1193 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1194 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1195 wxT("invalid thread priority") );
1197 wxCriticalSectionLocker
lock(m_critsect
);
1199 switch ( m_internal
->GetState() )
1202 // thread not yet started, priority will be set when it is
1203 m_internal
->SetPriority(prio
);
1208 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1209 #if defined(__LINUX__)
1210 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1211 // a priority other than 0. Instead, we use the BSD setpriority
1212 // which alllows us to set a 'nice' value between 20 to -20. Only
1213 // super user can set a value less than zero (more negative yields
1214 // higher priority). setpriority set the static priority of a process,
1215 // but this is OK since Linux is configured as a thread per process.
1221 // Map Wx priorites (WXTHREAD_MIN_PRIORITY -
1222 // WXTHREAD_MAX_PRIORITY) into BSD priorities (20 - -20).
1223 // Do calculation of values instead of hard coding them
1224 // to make maintenance easier.
1226 pSpan
= ((float)(WXTHREAD_MAX_PRIORITY
- WXTHREAD_MIN_PRIORITY
)) / 2.0;
1228 // prio starts as ................... // value => (0) >= p <= (n)
1230 fPrio
= ((float)prio
) - pSpan
; // value => (-n) >= p <= (+n)
1232 fPrio
= 0.0 - fPrio
; // value => (+n) <= p >= (-n)
1234 fPrio
= fPrio
* (20. / pSpan
) + .5; // value => (20) <= p >= (-20)
1238 // Clamp prio from 20 - -20;
1239 iPrio
= (iPrio
> 20) ? 20 : iPrio
;
1240 iPrio
= (iPrio
< -20) ? -20 : iPrio
;
1242 if (setpriority(PRIO_PROCESS
, 0, iPrio
) == -1)
1244 wxLogError(_("Failed to set thread priority %d."), prio
);
1249 struct sched_param sparam
;
1250 sparam
.sched_priority
= prio
;
1252 if ( pthread_setschedparam(m_internal
->GetId(),
1253 SCHED_OTHER
, &sparam
) != 0 )
1255 wxLogError(_("Failed to set thread priority %d."), prio
);
1259 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1264 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1268 unsigned int wxThread::GetPriority() const
1270 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1272 return m_internal
->GetPriority();
1275 wxThreadIdType
wxThread::GetId() const
1277 return (wxThreadIdType
) m_internal
->GetId();
1280 // -----------------------------------------------------------------------------
1282 // -----------------------------------------------------------------------------
1284 wxThreadError
wxThread::Pause()
1286 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1287 _T("a thread can't pause itself") );
1289 wxCriticalSectionLocker
lock(m_critsect
);
1291 if ( m_internal
->GetState() != STATE_RUNNING
)
1293 wxLogDebug(wxT("Can't pause thread which is not running."));
1295 return wxTHREAD_NOT_RUNNING
;
1298 // just set a flag, the thread will be really paused only during the next
1299 // call to TestDestroy()
1300 m_internal
->SetState(STATE_PAUSED
);
1302 return wxTHREAD_NO_ERROR
;
1305 wxThreadError
wxThread::Resume()
1307 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1308 _T("a thread can't resume itself") );
1310 wxCriticalSectionLocker
lock(m_critsect
);
1312 wxThreadState state
= m_internal
->GetState();
1317 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1320 m_internal
->Resume();
1322 return wxTHREAD_NO_ERROR
;
1325 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1327 return wxTHREAD_NO_ERROR
;
1330 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1332 return wxTHREAD_MISC_ERROR
;
1336 // -----------------------------------------------------------------------------
1338 // -----------------------------------------------------------------------------
1340 wxThread::ExitCode
wxThread::Wait()
1342 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1343 _T("a thread can't wait for itself") );
1345 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1346 _T("can't wait for detached thread") );
1350 return m_internal
->GetExitCode();
1353 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1355 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1356 _T("a thread can't delete itself") );
1358 bool isDetached
= m_isDetached
;
1361 wxThreadState state
= m_internal
->GetState();
1363 // ask the thread to stop
1364 m_internal
->SetCancelFlag();
1371 // we need to wake up the thread so that PthreadStart() will
1372 // terminate - right now it's blocking on run semaphore in
1374 m_internal
->SignalRun();
1383 // resume the thread first
1384 m_internal
->Resume();
1391 // wait until the thread stops
1396 // return the exit code of the thread
1397 *rc
= m_internal
->GetExitCode();
1400 //else: can't wait for detached threads
1403 return wxTHREAD_NO_ERROR
;
1406 wxThreadError
wxThread::Kill()
1408 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1409 _T("a thread can't kill itself") );
1411 switch ( m_internal
->GetState() )
1415 return wxTHREAD_NOT_RUNNING
;
1418 // resume the thread first
1424 #ifdef HAVE_PTHREAD_CANCEL
1425 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1428 wxLogError(_("Failed to terminate a thread."));
1430 return wxTHREAD_MISC_ERROR
;
1435 // if we use cleanup function, this will be done from
1436 // wxPthreadCleanup()
1437 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1438 ScheduleThreadForDeletion();
1440 // don't call OnExit() here, it can only be called in the
1441 // threads context and we're in the context of another thread
1444 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1448 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1451 return wxTHREAD_NO_ERROR
;
1455 void wxThread::Exit(ExitCode status
)
1457 wxASSERT_MSG( This() == this,
1458 _T("wxThread::Exit() can only be called in the context of the same thread") );
1462 // from the moment we call OnExit(), the main program may terminate at
1463 // any moment, so mark this thread as being already in process of being
1464 // deleted or wxThreadModule::OnExit() will try to delete it again
1465 ScheduleThreadForDeletion();
1468 // don't enter m_critsect before calling OnExit() because the user code
1469 // might deadlock if, for example, it signals a condition in OnExit() (a
1470 // common case) while the main thread calls any of functions entering
1471 // m_critsect on us (almost all of them do)
1474 // delete C++ thread object if this is a detached thread - user is
1475 // responsible for doing this for joinable ones
1478 // FIXME I'm feeling bad about it - what if another thread function is
1479 // called (in another thread context) now? It will try to access
1480 // half destroyed object which will probably result in something
1481 // very bad - but we can't protect this by a crit section unless
1482 // we make it a global object, but this would mean that we can
1483 // only call one thread function at a time :-(
1487 // terminate the thread (pthread_exit() never returns)
1488 pthread_exit(status
);
1490 wxFAIL_MSG(_T("pthread_exit() failed"));
1493 // also test whether we were paused
1494 bool wxThread::TestDestroy()
1496 wxASSERT_MSG( This() == this,
1497 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1501 if ( m_internal
->GetState() == STATE_PAUSED
)
1503 m_internal
->SetReallyPaused(TRUE
);
1505 // leave the crit section or the other threads will stop too if they
1506 // try to call any of (seemingly harmless) IsXXX() functions while we
1510 m_internal
->Pause();
1514 // thread wasn't requested to pause, nothing to do
1518 return m_internal
->WasCancelled();
1521 wxThread::~wxThread()
1526 // check that the thread either exited or couldn't be created
1527 if ( m_internal
->GetState() != STATE_EXITED
&&
1528 m_internal
->GetState() != STATE_NEW
)
1530 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."), GetId());
1534 #endif // __WXDEBUG__
1538 // remove this thread from the global array
1539 gs_allThreads
.Remove(this);
1542 // -----------------------------------------------------------------------------
1544 // -----------------------------------------------------------------------------
1546 bool wxThread::IsRunning() const
1548 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1550 return m_internal
->GetState() == STATE_RUNNING
;
1553 bool wxThread::IsAlive() const
1555 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1557 switch ( m_internal
->GetState() )
1568 bool wxThread::IsPaused() const
1570 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1572 return (m_internal
->GetState() == STATE_PAUSED
);
1575 //--------------------------------------------------------------------
1577 //--------------------------------------------------------------------
1579 class wxThreadModule
: public wxModule
1582 virtual bool OnInit();
1583 virtual void OnExit();
1586 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1589 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1591 bool wxThreadModule::OnInit()
1593 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1596 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1601 gs_tidMain
= pthread_self();
1603 gs_mutexGui
= new wxMutex();
1604 gs_mutexGui
->Lock();
1606 gs_mutexDeleteThread
= new wxMutex();
1607 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1612 void wxThreadModule::OnExit()
1614 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1616 // are there any threads left which are being deleted right now?
1617 size_t nThreadsBeingDeleted
;
1620 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1621 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1623 if ( nThreadsBeingDeleted
> 0 )
1625 wxLogTrace(TRACE_THREADS
,
1626 _T("Waiting for %lu threads to disappear"),
1627 (unsigned long)nThreadsBeingDeleted
);
1629 // have to wait until all of them disappear
1630 gs_condAllDeleted
->Wait();
1634 // terminate any threads left
1635 size_t count
= gs_allThreads
.GetCount();
1638 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1639 (unsigned long)count
);
1642 for ( size_t n
= 0u; n
< count
; n
++ )
1644 // Delete calls the destructor which removes the current entry. We
1645 // should only delete the first one each time.
1646 gs_allThreads
[0]->Delete();
1649 // destroy GUI mutex
1650 gs_mutexGui
->Unlock();
1653 // and free TLD slot
1654 (void)pthread_key_delete(gs_keySelf
);
1656 delete gs_condAllDeleted
;
1657 delete gs_mutexDeleteThread
;
1660 // ----------------------------------------------------------------------------
1662 // ----------------------------------------------------------------------------
1664 static void ScheduleThreadForDeletion()
1666 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1668 gs_nThreadsBeingDeleted
++;
1670 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1671 (unsigned long)gs_nThreadsBeingDeleted
,
1672 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1675 static void DeleteThread(wxThread
*This
)
1677 // gs_mutexDeleteThread should be unlocked before signalling the condition
1678 // or wxThreadModule::OnExit() would deadlock
1679 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1681 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1685 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1686 _T("no threads scheduled for deletion, yet we delete one?") );
1688 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1689 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1691 if ( !--gs_nThreadsBeingDeleted
)
1693 // no more threads left, signal it
1694 gs_condAllDeleted
->Signal();
1698 void wxMutexGuiEnter()
1700 gs_mutexGui
->Lock();
1703 void wxMutexGuiLeave()
1705 gs_mutexGui
->Unlock();
1708 // ----------------------------------------------------------------------------
1709 // include common implementation code
1710 // ----------------------------------------------------------------------------
1712 #include "wx/thrimpl.cpp"
1714 #endif // wxUSE_THREADS