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"
40 #include "wx/stopwatch.h"
51 #ifdef HAVE_THR_SETCONCURRENCY
55 // we use wxFFile under Linux in GetCPUCount()
60 #include <sys/resource.h>
64 #define THR_ID(thr) ((long long)(thr)->GetId())
66 #define THR_ID(thr) ((long)(thr)->GetId())
69 // ----------------------------------------------------------------------------
71 // ----------------------------------------------------------------------------
73 // the possible states of the thread and transitions from them
76 STATE_NEW
, // didn't start execution yet (=> RUNNING)
77 STATE_RUNNING
, // running (=> PAUSED or EXITED)
78 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
79 STATE_EXITED
// thread doesn't exist any more
82 // the exit value of a thread which has been cancelled
83 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
85 // trace mask for wxThread operations
86 #define TRACE_THREADS _T("thread")
88 // you can get additional debugging messages for the semaphore operations
89 #define TRACE_SEMA _T("semaphore")
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 static void ScheduleThreadForDeletion();
96 static void DeleteThread(wxThread
*This
);
98 // ----------------------------------------------------------------------------
100 // ----------------------------------------------------------------------------
102 // an (non owning) array of pointers to threads
103 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
105 // an entry for a thread we can wait for
107 // -----------------------------------------------------------------------------
109 // -----------------------------------------------------------------------------
111 // we keep the list of all threads created by the application to be able to
112 // terminate them on exit if there are some left - otherwise the process would
114 static wxArrayThread gs_allThreads
;
116 // the id of the main thread
117 static pthread_t gs_tidMain
= (pthread_t
)-1;
119 // the key for the pointer to the associated wxThread object
120 static pthread_key_t gs_keySelf
;
122 // the number of threads which are being deleted - the program won't exit
123 // until there are any left
124 static size_t gs_nThreadsBeingDeleted
= 0;
126 // a mutex to protect gs_nThreadsBeingDeleted
127 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
129 // and a condition variable which will be signaled when all
130 // gs_nThreadsBeingDeleted will have been deleted
131 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
133 // this mutex must be acquired before any call to a GUI function
134 // (it's not inside #if wxUSE_GUI because this file is compiled as part
136 static wxMutex
*gs_mutexGui
= NULL
;
138 // when we wait for a thread to exit, we're blocking on a condition which the
139 // thread signals in its SignalExit() method -- but this condition can't be a
140 // member of the thread itself as a detached thread may delete itself at any
141 // moment and accessing the condition member of the thread after this would
142 // result in a disaster
144 // so instead we maintain a global list of the structs below for the threads
145 // we're interested in waiting on
147 // ============================================================================
148 // wxMutex implementation
149 // ============================================================================
151 // ----------------------------------------------------------------------------
153 // ----------------------------------------------------------------------------
155 // this is a simple wrapper around pthread_mutex_t which provides error
157 class wxMutexInternal
160 wxMutexInternal(wxMutexType mutexType
);
164 wxMutexError
TryLock();
165 wxMutexError
Unlock();
167 bool IsOk() const { return m_isOk
; }
170 pthread_mutex_t m_mutex
;
173 // wxConditionInternal uses our m_mutex
174 friend class wxConditionInternal
;
177 #ifdef HAVE_PTHREAD_MUTEXATTR_T
178 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
179 // in the library, otherwise we wouldn't compile this code at all)
180 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
183 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
188 case wxMUTEX_RECURSIVE
:
189 // support recursive locks like Win32, i.e. a thread can lock a
190 // mutex which it had itself already locked
192 // unfortunately initialization of recursive mutexes is non
193 // portable, so try several methods
194 #ifdef HAVE_PTHREAD_MUTEXATTR_T
196 pthread_mutexattr_t attr
;
197 pthread_mutexattr_init(&attr
);
198 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
200 err
= pthread_mutex_init(&m_mutex
, &attr
);
202 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
203 // we can use this only as initializer so we have to assign it
204 // first to a temp var - assigning directly to m_mutex wouldn't
207 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
210 #else // no recursive mutexes
212 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
216 wxFAIL_MSG( _T("unknown mutex type") );
219 case wxMUTEX_DEFAULT
:
220 err
= pthread_mutex_init(&m_mutex
, NULL
);
227 wxLogApiError( wxT("pthread_mutex_init()"), err
);
231 wxMutexInternal::~wxMutexInternal()
235 int err
= pthread_mutex_destroy(&m_mutex
);
238 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
243 wxMutexError
wxMutexInternal::Lock()
245 int err
= pthread_mutex_lock(&m_mutex
);
249 // only error checking mutexes return this value and so it's an
250 // unexpected situation -- hence use assert, not wxLogDebug
251 wxFAIL_MSG( _T("mutex deadlock prevented") );
252 return wxMUTEX_DEAD_LOCK
;
255 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
259 return wxMUTEX_NO_ERROR
;
262 wxLogApiError(_T("pthread_mutex_lock()"), err
);
265 return wxMUTEX_MISC_ERROR
;
268 wxMutexError
wxMutexInternal::TryLock()
270 int err
= pthread_mutex_trylock(&m_mutex
);
274 // not an error: mutex is already locked, but we're prepared for
279 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
283 return wxMUTEX_NO_ERROR
;
286 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
289 return wxMUTEX_MISC_ERROR
;
292 wxMutexError
wxMutexInternal::Unlock()
294 int err
= pthread_mutex_unlock(&m_mutex
);
298 // we don't own the mutex
299 return wxMUTEX_UNLOCKED
;
302 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
306 return wxMUTEX_NO_ERROR
;
309 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
312 return wxMUTEX_MISC_ERROR
;
315 // ===========================================================================
316 // wxCondition implementation
317 // ===========================================================================
319 // ---------------------------------------------------------------------------
320 // wxConditionInternal
321 // ---------------------------------------------------------------------------
323 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
324 // with a pthread_mutex_t)
325 class wxConditionInternal
328 wxConditionInternal(wxMutex
& mutex
);
329 ~wxConditionInternal();
331 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
334 wxCondError
WaitTimeout(unsigned long milliseconds
);
336 wxCondError
Signal();
337 wxCondError
Broadcast();
340 // get the POSIX mutex associated with us
341 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
344 pthread_cond_t m_cond
;
349 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
352 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
358 wxLogApiError(_T("pthread_cond_init()"), err
);
362 wxConditionInternal::~wxConditionInternal()
366 int err
= pthread_cond_destroy(&m_cond
);
369 wxLogApiError(_T("pthread_cond_destroy()"), err
);
374 wxCondError
wxConditionInternal::Wait()
376 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
379 wxLogApiError(_T("pthread_cond_wait()"), err
);
381 return wxCOND_MISC_ERROR
;
384 return wxCOND_NO_ERROR
;
387 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
389 wxLongLong curtime
= wxGetLocalTimeMillis();
390 curtime
+= milliseconds
;
391 wxLongLong temp
= curtime
/ 1000;
392 int sec
= temp
.GetLo();
394 temp
= curtime
- temp
;
395 int millis
= temp
.GetLo();
400 tspec
.tv_nsec
= millis
* 1000L * 1000L;
402 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
406 return wxCOND_TIMEOUT
;
409 return wxCOND_NO_ERROR
;
412 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
415 return wxCOND_MISC_ERROR
;
418 wxCondError
wxConditionInternal::Signal()
420 int err
= pthread_cond_signal(&m_cond
);
423 wxLogApiError(_T("pthread_cond_signal()"), err
);
425 return wxCOND_MISC_ERROR
;
428 return wxCOND_NO_ERROR
;
431 wxCondError
wxConditionInternal::Broadcast()
433 int err
= pthread_cond_broadcast(&m_cond
);
436 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
438 return wxCOND_MISC_ERROR
;
441 return wxCOND_NO_ERROR
;
444 // ===========================================================================
445 // wxSemaphore implementation
446 // ===========================================================================
448 // ---------------------------------------------------------------------------
449 // wxSemaphoreInternal
450 // ---------------------------------------------------------------------------
452 // we implement the semaphores using mutexes and conditions instead of using
453 // the sem_xxx() POSIX functions because they're not widely available and also
454 // because it's impossible to implement WaitTimeout() using them
455 class wxSemaphoreInternal
458 wxSemaphoreInternal(int initialcount
, int maxcount
);
460 bool IsOk() const { return m_isOk
; }
463 wxSemaError
TryWait();
464 wxSemaError
WaitTimeout(unsigned long milliseconds
);
478 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
482 if ( (initialcount
< 0 || maxcount
< 0) ||
483 ((maxcount
> 0) && (initialcount
> maxcount
)) )
485 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
491 m_maxcount
= (size_t)maxcount
;
492 m_count
= (size_t)initialcount
;
495 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
498 wxSemaError
wxSemaphoreInternal::Wait()
500 wxMutexLocker
locker(m_mutex
);
502 while ( m_count
== 0 )
504 wxLogTrace(TRACE_SEMA
,
505 _T("Thread %ld waiting for semaphore to become signalled"),
506 wxThread::GetCurrentId());
508 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
509 return wxSEMA_MISC_ERROR
;
511 wxLogTrace(TRACE_SEMA
,
512 _T("Thread %ld finished waiting for semaphore, count = %lu"),
513 wxThread::GetCurrentId(), (unsigned long)m_count
);
518 return wxSEMA_NO_ERROR
;
521 wxSemaError
wxSemaphoreInternal::TryWait()
523 wxMutexLocker
locker(m_mutex
);
530 return wxSEMA_NO_ERROR
;
533 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
535 wxMutexLocker
locker(m_mutex
);
537 wxLongLong startTime
= wxGetLocalTimeMillis();
539 while ( m_count
== 0 )
541 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
542 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
543 if ( remainingTime
<= 0 )
546 return wxSEMA_TIMEOUT
;
549 switch ( m_cond
.WaitTimeout(remainingTime
) )
552 return wxSEMA_TIMEOUT
;
555 return wxSEMA_MISC_ERROR
;
557 case wxCOND_NO_ERROR
:
564 return wxSEMA_NO_ERROR
;
567 wxSemaError
wxSemaphoreInternal::Post()
569 wxMutexLocker
locker(m_mutex
);
571 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
573 return wxSEMA_OVERFLOW
;
578 wxLogTrace(TRACE_SEMA
,
579 _T("Thread %ld about to signal semaphore, count = %lu"),
580 wxThread::GetCurrentId(), (unsigned long)m_count
);
582 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
586 // ===========================================================================
587 // wxThread implementation
588 // ===========================================================================
590 // the thread callback functions must have the C linkage
594 #if HAVE_THREAD_CLEANUP_FUNCTIONS
595 // thread exit function
596 void wxPthreadCleanup(void *ptr
);
597 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
599 void *wxPthreadStart(void *ptr
);
603 // ----------------------------------------------------------------------------
605 // ----------------------------------------------------------------------------
607 class wxThreadInternal
613 // thread entry function
614 static void *PthreadStart(wxThread
*thread
);
619 // unblock the thread allowing it to run
620 void SignalRun() { m_semRun
.Post(); }
621 // ask the thread to terminate
623 // go to sleep until Resume() is called
630 int GetPriority() const { return m_prio
; }
631 void SetPriority(int prio
) { m_prio
= prio
; }
633 wxThreadState
GetState() const { return m_state
; }
634 void SetState(wxThreadState state
)
637 static const wxChar
*stateNames
[] =
645 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
646 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
647 #endif // __WXDEBUG__
652 pthread_t
GetId() const { return m_threadId
; }
653 pthread_t
*GetIdPtr() { return &m_threadId
; }
655 void SetCancelFlag() { m_cancelled
= TRUE
; }
656 bool WasCancelled() const { return m_cancelled
; }
658 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
659 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
662 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
663 bool IsReallyPaused() const { return m_isPaused
; }
665 // tell the thread that it is a detached one
668 wxCriticalSectionLocker
lock(m_csJoinFlag
);
670 m_shouldBeJoined
= FALSE
;
674 #if HAVE_THREAD_CLEANUP_FUNCTIONS
675 // this is used by wxPthreadCleanup() only
676 static void Cleanup(wxThread
*thread
);
677 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
680 pthread_t m_threadId
; // id of the thread
681 wxThreadState m_state
; // see wxThreadState enum
682 int m_prio
; // in wxWidgets units: from 0 to 100
684 // this flag is set when the thread should terminate
687 // this flag is set when the thread is blocking on m_semSuspend
690 // the thread exit code - only used for joinable (!detached) threads and
691 // is only valid after the thread termination
692 wxThread::ExitCode m_exitcode
;
694 // many threads may call Wait(), but only one of them should call
695 // pthread_join(), so we have to keep track of this
696 wxCriticalSection m_csJoinFlag
;
697 bool m_shouldBeJoined
;
700 // this semaphore is posted by Run() and the threads Entry() is not
701 // called before it is done
702 wxSemaphore m_semRun
;
704 // this one is signaled when the thread should resume after having been
706 wxSemaphore m_semSuspend
;
709 // ----------------------------------------------------------------------------
710 // thread startup and exit functions
711 // ----------------------------------------------------------------------------
713 void *wxPthreadStart(void *ptr
)
715 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
718 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
720 wxThreadInternal
*pthread
= thread
->m_internal
;
722 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
724 // associate the thread pointer with the newly created thread so that
725 // wxThread::This() will work
726 int rc
= pthread_setspecific(gs_keySelf
, thread
);
729 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
734 // have to declare this before pthread_cleanup_push() which defines a
738 #if HAVE_THREAD_CLEANUP_FUNCTIONS
739 // install the cleanup handler which will be called if the thread is
741 pthread_cleanup_push(wxPthreadCleanup
, thread
);
742 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
744 // wait for the semaphore to be posted from Run()
745 pthread
->m_semRun
.Wait();
747 // test whether we should run the run at all - may be it was deleted
748 // before it started to Run()?
750 wxCriticalSectionLocker
lock(thread
->m_critsect
);
752 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
753 pthread
->WasCancelled();
758 // call the main entry
759 wxLogTrace(TRACE_THREADS
,
760 _T("Thread %ld about to enter its Entry()."),
763 pthread
->m_exitcode
= thread
->Entry();
765 wxLogTrace(TRACE_THREADS
,
766 _T("Thread %ld Entry() returned %lu."),
767 THR_ID(pthread
), (unsigned long)pthread
->m_exitcode
);
770 wxCriticalSectionLocker
lock(thread
->m_critsect
);
772 // change the state of the thread to "exited" so that
773 // wxPthreadCleanup handler won't do anything from now (if it's
774 // called before we do pthread_cleanup_pop below)
775 pthread
->SetState(STATE_EXITED
);
779 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
780 // contains the matching '}' for the '{' in push, so they must be used
781 // in the same block!
782 #if HAVE_THREAD_CLEANUP_FUNCTIONS
783 // remove the cleanup handler without executing it
784 pthread_cleanup_pop(FALSE
);
785 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
789 // FIXME: deleting a possibly joinable thread here???
792 return EXITCODE_CANCELLED
;
796 // terminate the thread
797 thread
->Exit(pthread
->m_exitcode
);
799 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
805 #if HAVE_THREAD_CLEANUP_FUNCTIONS
807 // this handler is called when the thread is cancelled
808 extern "C" void wxPthreadCleanup(void *ptr
)
810 wxThreadInternal::Cleanup((wxThread
*)ptr
);
813 void wxThreadInternal::Cleanup(wxThread
*thread
)
816 wxCriticalSectionLocker
lock(thread
->m_critsect
);
817 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
819 // thread is already considered as finished.
824 // exit the thread gracefully
825 thread
->Exit(EXITCODE_CANCELLED
);
828 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
830 // ----------------------------------------------------------------------------
832 // ----------------------------------------------------------------------------
834 wxThreadInternal::wxThreadInternal()
838 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
842 // set to TRUE only when the thread starts waiting on m_semSuspend
845 // defaults for joinable threads
846 m_shouldBeJoined
= TRUE
;
847 m_isDetached
= FALSE
;
850 wxThreadInternal::~wxThreadInternal()
854 wxThreadError
wxThreadInternal::Run()
856 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
857 wxT("thread may only be started once after Create()") );
859 SetState(STATE_RUNNING
);
861 // wake up threads waiting for our start
864 return wxTHREAD_NO_ERROR
;
867 void wxThreadInternal::Wait()
869 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
871 // if the thread we're waiting for is waiting for the GUI mutex, we will
872 // deadlock so make sure we release it temporarily
873 if ( wxThread::IsMain() )
876 wxLogTrace(TRACE_THREADS
,
877 _T("Starting to wait for thread %ld to exit."),
880 // to avoid memory leaks we should call pthread_join(), but it must only be
881 // done once so use a critical section to serialize the code below
883 wxCriticalSectionLocker
lock(m_csJoinFlag
);
885 if ( m_shouldBeJoined
)
887 // FIXME shouldn't we set cancellation type to DISABLED here? If
888 // we're cancelled inside pthread_join(), things will almost
889 // certainly break - but if we disable the cancellation, we
891 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
893 // this is a serious problem, so use wxLogError and not
894 // wxLogDebug: it is possible to bring the system to its knees
895 // by creating too many threads and not joining them quite
897 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
900 m_shouldBeJoined
= FALSE
;
904 // reacquire GUI mutex
905 if ( wxThread::IsMain() )
909 void wxThreadInternal::Pause()
911 // the state is set from the thread which pauses us first, this function
912 // is called later so the state should have been already set
913 wxCHECK_RET( m_state
== STATE_PAUSED
,
914 wxT("thread must first be paused with wxThread::Pause().") );
916 wxLogTrace(TRACE_THREADS
,
917 _T("Thread %ld goes to sleep."), THR_ID(this));
919 // wait until the semaphore is Post()ed from Resume()
923 void wxThreadInternal::Resume()
925 wxCHECK_RET( m_state
== STATE_PAUSED
,
926 wxT("can't resume thread which is not suspended.") );
928 // the thread might be not actually paused yet - if there were no call to
929 // TestDestroy() since the last call to Pause() for example
930 if ( IsReallyPaused() )
932 wxLogTrace(TRACE_THREADS
,
933 _T("Waking up thread %ld"), THR_ID(this));
939 SetReallyPaused(FALSE
);
943 wxLogTrace(TRACE_THREADS
,
944 _T("Thread %ld is not yet really paused"), THR_ID(this));
947 SetState(STATE_RUNNING
);
950 // -----------------------------------------------------------------------------
951 // wxThread static functions
952 // -----------------------------------------------------------------------------
954 wxThread
*wxThread::This()
956 return (wxThread
*)pthread_getspecific(gs_keySelf
);
959 bool wxThread::IsMain()
961 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
964 void wxThread::Yield()
966 #ifdef HAVE_SCHED_YIELD
971 void wxThread::Sleep(unsigned long milliseconds
)
973 wxMilliSleep(milliseconds
);
976 int wxThread::GetCPUCount()
978 #if defined(__LINUX__) && wxUSE_FFILE
979 // read from proc (can't use wxTextFile here because it's a special file:
980 // it has 0 size but still can be read from)
983 wxFFile
file(_T("/proc/cpuinfo"));
984 if ( file
.IsOpened() )
986 // slurp the whole file
988 if ( file
.ReadAll(&s
) )
990 // (ab)use Replace() to find the number of "processor: num" strings
991 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
997 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1001 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1004 #elif defined(_SC_NPROCESSORS_ONLN)
1005 // this works for Solaris
1006 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1011 #endif // different ways to get number of CPUs
1017 // VMS is a 64 bit system and threads have 64 bit pointers.
1018 // FIXME: also needed for other systems????
1020 unsigned long long wxThread::GetCurrentId()
1022 return (unsigned long long)pthread_self();
1027 unsigned long wxThread::GetCurrentId()
1029 return (unsigned long)pthread_self();
1032 #endif // __VMS/!__VMS
1035 bool wxThread::SetConcurrency(size_t level
)
1037 #ifdef HAVE_THR_SETCONCURRENCY
1038 int rc
= thr_setconcurrency(level
);
1041 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1045 #else // !HAVE_THR_SETCONCURRENCY
1046 // ok only for the default value
1048 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1051 // -----------------------------------------------------------------------------
1053 // -----------------------------------------------------------------------------
1055 wxThread::wxThread(wxThreadKind kind
)
1057 // add this thread to the global list of all threads
1058 gs_allThreads
.Add(this);
1060 m_internal
= new wxThreadInternal();
1062 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1065 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1067 if ( m_internal
->GetState() != STATE_NEW
)
1069 // don't recreate thread
1070 return wxTHREAD_RUNNING
;
1073 // set up the thread attribute: right now, we only set thread priority
1074 pthread_attr_t attr
;
1075 pthread_attr_init(&attr
);
1077 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1079 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1081 wxLogError(_("Cannot retrieve thread scheduling policy."));
1085 /* the pthread.h contains too many spaces. This is a work-around */
1086 # undef sched_get_priority_max
1087 #undef sched_get_priority_min
1088 #define sched_get_priority_max(_pol_) \
1089 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1090 #define sched_get_priority_min(_pol_) \
1091 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1094 int max_prio
= sched_get_priority_max(policy
),
1095 min_prio
= sched_get_priority_min(policy
),
1096 prio
= m_internal
->GetPriority();
1098 if ( min_prio
== -1 || max_prio
== -1 )
1100 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1103 else if ( max_prio
== min_prio
)
1105 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1107 // notify the programmer that this doesn't work here
1108 wxLogWarning(_("Thread priority setting is ignored."));
1110 //else: we have default priority, so don't complain
1112 // anyhow, don't do anything because priority is just ignored
1116 struct sched_param sp
;
1117 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1119 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1122 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1124 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1126 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1129 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1131 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1132 // this will make the threads created by this process really concurrent
1133 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1135 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1137 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1139 // VZ: assume that this one is always available (it's rather fundamental),
1140 // if this function is ever missing we should try to use
1141 // pthread_detach() instead (after thread creation)
1144 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1146 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1149 // never try to join detached threads
1150 m_internal
->Detach();
1152 //else: threads are created joinable by default, it's ok
1154 // create the new OS thread object
1155 int rc
= pthread_create
1157 m_internal
->GetIdPtr(),
1163 if ( pthread_attr_destroy(&attr
) != 0 )
1165 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1170 m_internal
->SetState(STATE_EXITED
);
1172 return wxTHREAD_NO_RESOURCE
;
1175 return wxTHREAD_NO_ERROR
;
1178 wxThreadError
wxThread::Run()
1180 wxCriticalSectionLocker
lock(m_critsect
);
1182 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1183 wxT("must call wxThread::Create() first") );
1185 return m_internal
->Run();
1188 // -----------------------------------------------------------------------------
1190 // -----------------------------------------------------------------------------
1192 void wxThread::SetPriority(unsigned int prio
)
1194 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1195 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1196 wxT("invalid thread priority") );
1198 wxCriticalSectionLocker
lock(m_critsect
);
1200 switch ( m_internal
->GetState() )
1203 // thread not yet started, priority will be set when it is
1204 m_internal
->SetPriority(prio
);
1209 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1210 #if defined(__LINUX__)
1211 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1212 // a priority other than 0. Instead, we use the BSD setpriority
1213 // which alllows us to set a 'nice' value between 20 to -20. Only
1214 // super user can set a value less than zero (more negative yields
1215 // higher priority). setpriority set the static priority of a process,
1216 // but this is OK since Linux is configured as a thread per process.
1222 // Map Wx priorites (WXTHREAD_MIN_PRIORITY -
1223 // WXTHREAD_MAX_PRIORITY) into BSD priorities (20 - -20).
1224 // Do calculation of values instead of hard coding them
1225 // to make maintenance easier.
1227 pSpan
= ((float)(WXTHREAD_MAX_PRIORITY
- WXTHREAD_MIN_PRIORITY
)) / 2.0;
1229 // prio starts as ................... // value => (0) >= p <= (n)
1231 fPrio
= ((float)prio
) - pSpan
; // value => (-n) >= p <= (+n)
1233 fPrio
= 0.0 - fPrio
; // value => (+n) <= p >= (-n)
1235 fPrio
= fPrio
* (20. / pSpan
) + .5; // value => (20) <= p >= (-20)
1239 // Clamp prio from 20 - -20;
1240 iPrio
= (iPrio
> 20) ? 20 : iPrio
;
1241 iPrio
= (iPrio
< -20) ? -20 : iPrio
;
1243 if (setpriority(PRIO_PROCESS
, 0, iPrio
) == -1)
1245 wxLogError(_("Failed to set thread priority %d."), prio
);
1250 struct sched_param sparam
;
1251 sparam
.sched_priority
= prio
;
1253 if ( pthread_setschedparam(m_internal
->GetId(),
1254 SCHED_OTHER
, &sparam
) != 0 )
1256 wxLogError(_("Failed to set thread priority %d."), prio
);
1260 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1265 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1269 unsigned int wxThread::GetPriority() const
1271 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1273 return m_internal
->GetPriority();
1276 wxThreadIdType
wxThread::GetId() const
1278 return (wxThreadIdType
) m_internal
->GetId();
1281 // -----------------------------------------------------------------------------
1283 // -----------------------------------------------------------------------------
1285 wxThreadError
wxThread::Pause()
1287 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1288 _T("a thread can't pause itself") );
1290 wxCriticalSectionLocker
lock(m_critsect
);
1292 if ( m_internal
->GetState() != STATE_RUNNING
)
1294 wxLogDebug(wxT("Can't pause thread which is not running."));
1296 return wxTHREAD_NOT_RUNNING
;
1299 // just set a flag, the thread will be really paused only during the next
1300 // call to TestDestroy()
1301 m_internal
->SetState(STATE_PAUSED
);
1303 return wxTHREAD_NO_ERROR
;
1306 wxThreadError
wxThread::Resume()
1308 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1309 _T("a thread can't resume itself") );
1311 wxCriticalSectionLocker
lock(m_critsect
);
1313 wxThreadState state
= m_internal
->GetState();
1318 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1321 m_internal
->Resume();
1323 return wxTHREAD_NO_ERROR
;
1326 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1328 return wxTHREAD_NO_ERROR
;
1331 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1333 return wxTHREAD_MISC_ERROR
;
1337 // -----------------------------------------------------------------------------
1339 // -----------------------------------------------------------------------------
1341 wxThread::ExitCode
wxThread::Wait()
1343 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1344 _T("a thread can't wait for itself") );
1346 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1347 _T("can't wait for detached thread") );
1351 return m_internal
->GetExitCode();
1354 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1356 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1357 _T("a thread can't delete itself") );
1359 bool isDetached
= m_isDetached
;
1362 wxThreadState state
= m_internal
->GetState();
1364 // ask the thread to stop
1365 m_internal
->SetCancelFlag();
1372 // we need to wake up the thread so that PthreadStart() will
1373 // terminate - right now it's blocking on run semaphore in
1375 m_internal
->SignalRun();
1384 // resume the thread first
1385 m_internal
->Resume();
1392 // wait until the thread stops
1397 // return the exit code of the thread
1398 *rc
= m_internal
->GetExitCode();
1401 //else: can't wait for detached threads
1404 return wxTHREAD_NO_ERROR
;
1407 wxThreadError
wxThread::Kill()
1409 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1410 _T("a thread can't kill itself") );
1412 switch ( m_internal
->GetState() )
1416 return wxTHREAD_NOT_RUNNING
;
1419 // resume the thread first
1425 #ifdef HAVE_PTHREAD_CANCEL
1426 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1429 wxLogError(_("Failed to terminate a thread."));
1431 return wxTHREAD_MISC_ERROR
;
1436 // if we use cleanup function, this will be done from
1437 // wxPthreadCleanup()
1438 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1439 ScheduleThreadForDeletion();
1441 // don't call OnExit() here, it can only be called in the
1442 // threads context and we're in the context of another thread
1445 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1449 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1452 return wxTHREAD_NO_ERROR
;
1456 void wxThread::Exit(ExitCode status
)
1458 wxASSERT_MSG( This() == this,
1459 _T("wxThread::Exit() can only be called in the context of the same thread") );
1463 // from the moment we call OnExit(), the main program may terminate at
1464 // any moment, so mark this thread as being already in process of being
1465 // deleted or wxThreadModule::OnExit() will try to delete it again
1466 ScheduleThreadForDeletion();
1469 // don't enter m_critsect before calling OnExit() because the user code
1470 // might deadlock if, for example, it signals a condition in OnExit() (a
1471 // common case) while the main thread calls any of functions entering
1472 // m_critsect on us (almost all of them do)
1475 // delete C++ thread object if this is a detached thread - user is
1476 // responsible for doing this for joinable ones
1479 // FIXME I'm feeling bad about it - what if another thread function is
1480 // called (in another thread context) now? It will try to access
1481 // half destroyed object which will probably result in something
1482 // very bad - but we can't protect this by a crit section unless
1483 // we make it a global object, but this would mean that we can
1484 // only call one thread function at a time :-(
1490 m_internal
->SetState(STATE_EXITED
);
1494 // terminate the thread (pthread_exit() never returns)
1495 pthread_exit(status
);
1497 wxFAIL_MSG(_T("pthread_exit() failed"));
1500 // also test whether we were paused
1501 bool wxThread::TestDestroy()
1503 wxASSERT_MSG( This() == this,
1504 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1508 if ( m_internal
->GetState() == STATE_PAUSED
)
1510 m_internal
->SetReallyPaused(TRUE
);
1512 // leave the crit section or the other threads will stop too if they
1513 // try to call any of (seemingly harmless) IsXXX() functions while we
1517 m_internal
->Pause();
1521 // thread wasn't requested to pause, nothing to do
1525 return m_internal
->WasCancelled();
1528 wxThread::~wxThread()
1533 // check that the thread either exited or couldn't be created
1534 if ( m_internal
->GetState() != STATE_EXITED
&&
1535 m_internal
->GetState() != STATE_NEW
)
1537 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."), GetId());
1541 #endif // __WXDEBUG__
1545 // remove this thread from the global array
1546 gs_allThreads
.Remove(this);
1549 // -----------------------------------------------------------------------------
1551 // -----------------------------------------------------------------------------
1553 bool wxThread::IsRunning() const
1555 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1557 return m_internal
->GetState() == STATE_RUNNING
;
1560 bool wxThread::IsAlive() const
1562 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1564 switch ( m_internal
->GetState() )
1575 bool wxThread::IsPaused() const
1577 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1579 return (m_internal
->GetState() == STATE_PAUSED
);
1582 //--------------------------------------------------------------------
1584 //--------------------------------------------------------------------
1586 class wxThreadModule
: public wxModule
1589 virtual bool OnInit();
1590 virtual void OnExit();
1593 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1596 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1598 bool wxThreadModule::OnInit()
1600 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1603 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1608 gs_tidMain
= pthread_self();
1610 gs_mutexGui
= new wxMutex();
1611 gs_mutexGui
->Lock();
1613 gs_mutexDeleteThread
= new wxMutex();
1614 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1619 void wxThreadModule::OnExit()
1621 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1623 // are there any threads left which are being deleted right now?
1624 size_t nThreadsBeingDeleted
;
1627 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1628 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1630 if ( nThreadsBeingDeleted
> 0 )
1632 wxLogTrace(TRACE_THREADS
,
1633 _T("Waiting for %lu threads to disappear"),
1634 (unsigned long)nThreadsBeingDeleted
);
1636 // have to wait until all of them disappear
1637 gs_condAllDeleted
->Wait();
1641 // terminate any threads left
1642 size_t count
= gs_allThreads
.GetCount();
1645 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1646 (unsigned long)count
);
1649 for ( size_t n
= 0u; n
< count
; n
++ )
1651 // Delete calls the destructor which removes the current entry. We
1652 // should only delete the first one each time.
1653 gs_allThreads
[0]->Delete();
1656 // destroy GUI mutex
1657 gs_mutexGui
->Unlock();
1660 // and free TLD slot
1661 (void)pthread_key_delete(gs_keySelf
);
1663 delete gs_condAllDeleted
;
1664 delete gs_mutexDeleteThread
;
1667 // ----------------------------------------------------------------------------
1669 // ----------------------------------------------------------------------------
1671 static void ScheduleThreadForDeletion()
1673 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1675 gs_nThreadsBeingDeleted
++;
1677 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1678 (unsigned long)gs_nThreadsBeingDeleted
,
1679 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1682 static void DeleteThread(wxThread
*This
)
1684 // gs_mutexDeleteThread should be unlocked before signalling the condition
1685 // or wxThreadModule::OnExit() would deadlock
1686 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1688 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1692 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1693 _T("no threads scheduled for deletion, yet we delete one?") );
1695 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1696 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1698 if ( !--gs_nThreadsBeingDeleted
)
1700 // no more threads left, signal it
1701 gs_condAllDeleted
->Signal();
1705 void wxMutexGuiEnter()
1707 gs_mutexGui
->Lock();
1710 void wxMutexGuiLeave()
1712 gs_mutexGui
->Unlock();
1715 // ----------------------------------------------------------------------------
1716 // include common implementation code
1717 // ----------------------------------------------------------------------------
1719 #include "wx/thrimpl.cpp"
1721 #endif // wxUSE_THREADS