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>
62 // ----------------------------------------------------------------------------
64 // ----------------------------------------------------------------------------
66 // the possible states of the thread and transitions from them
69 STATE_NEW
, // didn't start execution yet (=> RUNNING)
70 STATE_RUNNING
, // running (=> PAUSED or EXITED)
71 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
72 STATE_EXITED
// thread doesn't exist any more
75 // the exit value of a thread which has been cancelled
76 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
78 // trace mask for wxThread operations
79 #define TRACE_THREADS _T("thread")
81 // you can get additional debugging messages for the semaphore operations
82 #define TRACE_SEMA _T("semaphore")
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 static void ScheduleThreadForDeletion();
89 static void DeleteThread(wxThread
*This
);
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 // an (non owning) array of pointers to threads
96 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
98 // an entry for a thread we can wait for
100 // -----------------------------------------------------------------------------
102 // -----------------------------------------------------------------------------
104 // we keep the list of all threads created by the application to be able to
105 // terminate them on exit if there are some left - otherwise the process would
107 static wxArrayThread gs_allThreads
;
109 // the id of the main thread
110 static pthread_t gs_tidMain
;
112 // the key for the pointer to the associated wxThread object
113 static pthread_key_t gs_keySelf
;
115 // the number of threads which are being deleted - the program won't exit
116 // until there are any left
117 static size_t gs_nThreadsBeingDeleted
= 0;
119 // a mutex to protect gs_nThreadsBeingDeleted
120 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
122 // and a condition variable which will be signaled when all
123 // gs_nThreadsBeingDeleted will have been deleted
124 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
126 // this mutex must be acquired before any call to a GUI function
127 // (it's not inside #if wxUSE_GUI because this file is compiled as part
129 static wxMutex
*gs_mutexGui
= NULL
;
131 // when we wait for a thread to exit, we're blocking on a condition which the
132 // thread signals in its SignalExit() method -- but this condition can't be a
133 // member of the thread itself as a detached thread may delete itself at any
134 // moment and accessing the condition member of the thread after this would
135 // result in a disaster
137 // so instead we maintain a global list of the structs below for the threads
138 // we're interested in waiting on
140 // ============================================================================
141 // wxMutex implementation
142 // ============================================================================
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 // this is a simple wrapper around pthread_mutex_t which provides error
150 class wxMutexInternal
153 wxMutexInternal(wxMutexType mutexType
);
157 wxMutexError
TryLock();
158 wxMutexError
Unlock();
160 bool IsOk() const { return m_isOk
; }
163 pthread_mutex_t m_mutex
;
166 // wxConditionInternal uses our m_mutex
167 friend class wxConditionInternal
;
170 #ifdef HAVE_PTHREAD_MUTEXATTR_T
171 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
172 // in the library, otherwise we wouldn't compile this code at all)
173 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
176 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
181 case wxMUTEX_RECURSIVE
:
182 // support recursive locks like Win32, i.e. a thread can lock a
183 // mutex which it had itself already locked
185 // unfortunately initialization of recursive mutexes is non
186 // portable, so try several methods
187 #ifdef HAVE_PTHREAD_MUTEXATTR_T
189 pthread_mutexattr_t attr
;
190 pthread_mutexattr_init(&attr
);
191 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
193 err
= pthread_mutex_init(&m_mutex
, &attr
);
195 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
196 // we can use this only as initializer so we have to assign it
197 // first to a temp var - assigning directly to m_mutex wouldn't
200 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
203 #else // no recursive mutexes
205 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
209 wxFAIL_MSG( _T("unknown mutex type") );
212 case wxMUTEX_DEFAULT
:
213 err
= pthread_mutex_init(&m_mutex
, NULL
);
220 wxLogApiError( wxT("pthread_mutex_init()"), err
);
224 wxMutexInternal::~wxMutexInternal()
228 int err
= pthread_mutex_destroy(&m_mutex
);
231 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
236 wxMutexError
wxMutexInternal::Lock()
238 int err
= pthread_mutex_lock(&m_mutex
);
242 // only error checking mutexes return this value and so it's an
243 // unexpected situation -- hence use assert, not wxLogDebug
244 wxFAIL_MSG( _T("mutex deadlock prevented") );
245 return wxMUTEX_DEAD_LOCK
;
248 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
252 return wxMUTEX_NO_ERROR
;
255 wxLogApiError(_T("pthread_mutex_lock()"), err
);
258 return wxMUTEX_MISC_ERROR
;
261 wxMutexError
wxMutexInternal::TryLock()
263 int err
= pthread_mutex_trylock(&m_mutex
);
267 // not an error: mutex is already locked, but we're prepared for
272 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
276 return wxMUTEX_NO_ERROR
;
279 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
282 return wxMUTEX_MISC_ERROR
;
285 wxMutexError
wxMutexInternal::Unlock()
287 int err
= pthread_mutex_unlock(&m_mutex
);
291 // we don't own the mutex
292 return wxMUTEX_UNLOCKED
;
295 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
299 return wxMUTEX_NO_ERROR
;
302 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
305 return wxMUTEX_MISC_ERROR
;
308 // ===========================================================================
309 // wxCondition implementation
310 // ===========================================================================
312 // ---------------------------------------------------------------------------
313 // wxConditionInternal
314 // ---------------------------------------------------------------------------
316 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
317 // with a pthread_mutex_t)
318 class wxConditionInternal
321 wxConditionInternal(wxMutex
& mutex
);
322 ~wxConditionInternal();
324 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
327 wxCondError
WaitTimeout(unsigned long milliseconds
);
329 wxCondError
Signal();
330 wxCondError
Broadcast();
333 // get the POSIX mutex associated with us
334 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
337 pthread_cond_t m_cond
;
342 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
345 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
351 wxLogApiError(_T("pthread_cond_init()"), err
);
355 wxConditionInternal::~wxConditionInternal()
359 int err
= pthread_cond_destroy(&m_cond
);
362 wxLogApiError(_T("pthread_cond_destroy()"), err
);
367 wxCondError
wxConditionInternal::Wait()
369 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
372 wxLogApiError(_T("pthread_cond_wait()"), err
);
374 return wxCOND_MISC_ERROR
;
377 return wxCOND_NO_ERROR
;
380 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
382 wxLongLong curtime
= wxGetLocalTimeMillis();
383 curtime
+= milliseconds
;
384 wxLongLong temp
= curtime
/ 1000;
385 int sec
= temp
.GetLo();
387 temp
= curtime
- temp
;
388 int millis
= temp
.GetLo();
393 tspec
.tv_nsec
= millis
* 1000L * 1000L;
395 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
399 return wxCOND_TIMEOUT
;
402 return wxCOND_NO_ERROR
;
405 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
408 return wxCOND_MISC_ERROR
;
411 wxCondError
wxConditionInternal::Signal()
413 int err
= pthread_cond_signal(&m_cond
);
416 wxLogApiError(_T("pthread_cond_signal()"), err
);
418 return wxCOND_MISC_ERROR
;
421 return wxCOND_NO_ERROR
;
424 wxCondError
wxConditionInternal::Broadcast()
426 int err
= pthread_cond_broadcast(&m_cond
);
429 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
431 return wxCOND_MISC_ERROR
;
434 return wxCOND_NO_ERROR
;
437 // ===========================================================================
438 // wxSemaphore implementation
439 // ===========================================================================
441 // ---------------------------------------------------------------------------
442 // wxSemaphoreInternal
443 // ---------------------------------------------------------------------------
445 // we implement the semaphores using mutexes and conditions instead of using
446 // the sem_xxx() POSIX functions because they're not widely available and also
447 // because it's impossible to implement WaitTimeout() using them
448 class wxSemaphoreInternal
451 wxSemaphoreInternal(int initialcount
, int maxcount
);
453 bool IsOk() const { return m_isOk
; }
456 wxSemaError
TryWait();
457 wxSemaError
WaitTimeout(unsigned long milliseconds
);
471 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
475 if ( (initialcount
< 0 || maxcount
< 0) ||
476 ((maxcount
> 0) && (initialcount
> maxcount
)) )
478 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
484 m_maxcount
= (size_t)maxcount
;
485 m_count
= (size_t)initialcount
;
488 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
491 wxSemaError
wxSemaphoreInternal::Wait()
493 wxMutexLocker
locker(m_mutex
);
495 while ( m_count
== 0 )
497 wxLogTrace(TRACE_SEMA
,
498 "Thread %ld waiting for semaphore to become signalled",
499 wxThread::GetCurrentId());
501 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
502 return wxSEMA_MISC_ERROR
;
504 wxLogTrace(TRACE_SEMA
,
505 "Thread %ld finished waiting for semaphore, count = %lu",
506 wxThread::GetCurrentId(), (unsigned long)m_count
);
511 return wxSEMA_NO_ERROR
;
514 wxSemaError
wxSemaphoreInternal::TryWait()
516 wxMutexLocker
locker(m_mutex
);
523 return wxSEMA_NO_ERROR
;
526 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
528 wxMutexLocker
locker(m_mutex
);
530 wxLongLong startTime
= wxGetLocalTimeMillis();
532 while ( m_count
== 0 )
534 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
535 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
536 if ( remainingTime
<= 0 )
539 return wxSEMA_TIMEOUT
;
542 switch ( m_cond
.WaitTimeout(remainingTime
) )
545 return wxSEMA_TIMEOUT
;
548 return wxSEMA_MISC_ERROR
;
550 case wxCOND_NO_ERROR
:
557 return wxSEMA_NO_ERROR
;
560 wxSemaError
wxSemaphoreInternal::Post()
562 wxMutexLocker
locker(m_mutex
);
564 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
566 return wxSEMA_OVERFLOW
;
571 wxLogTrace(TRACE_SEMA
,
572 "Thread %ld about to signal semaphore, count = %lu",
573 wxThread::GetCurrentId(), (unsigned long)m_count
);
575 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
579 // ===========================================================================
580 // wxThread implementation
581 // ===========================================================================
583 // the thread callback functions must have the C linkage
587 #if HAVE_THREAD_CLEANUP_FUNCTIONS
588 // thread exit function
589 void wxPthreadCleanup(void *ptr
);
590 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
592 void *wxPthreadStart(void *ptr
);
596 // ----------------------------------------------------------------------------
598 // ----------------------------------------------------------------------------
600 class wxThreadInternal
606 // thread entry function
607 static void *PthreadStart(wxThread
*thread
);
612 // unblock the thread allowing it to run
613 void SignalRun() { m_semRun
.Post(); }
614 // ask the thread to terminate
616 // go to sleep until Resume() is called
623 int GetPriority() const { return m_prio
; }
624 void SetPriority(int prio
) { m_prio
= prio
; }
626 wxThreadState
GetState() const { return m_state
; }
627 void SetState(wxThreadState state
)
630 static const wxChar
*stateNames
[] =
638 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
639 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
640 #endif // __WXDEBUG__
645 pthread_t
GetId() const { return m_threadId
; }
646 pthread_t
*GetIdPtr() { return &m_threadId
; }
648 void SetCancelFlag() { m_cancelled
= TRUE
; }
649 bool WasCancelled() const { return m_cancelled
; }
651 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
652 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
655 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
656 bool IsReallyPaused() const { return m_isPaused
; }
658 // tell the thread that it is a detached one
661 wxCriticalSectionLocker
lock(m_csJoinFlag
);
663 m_shouldBeJoined
= FALSE
;
667 #if HAVE_THREAD_CLEANUP_FUNCTIONS
668 // this is used by wxPthreadCleanup() only
669 static void Cleanup(wxThread
*thread
);
670 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
673 pthread_t m_threadId
; // id of the thread
674 wxThreadState m_state
; // see wxThreadState enum
675 int m_prio
; // in wxWindows units: from 0 to 100
677 // this flag is set when the thread should terminate
680 // this flag is set when the thread is blocking on m_semSuspend
683 // the thread exit code - only used for joinable (!detached) threads and
684 // is only valid after the thread termination
685 wxThread::ExitCode m_exitcode
;
687 // many threads may call Wait(), but only one of them should call
688 // pthread_join(), so we have to keep track of this
689 wxCriticalSection m_csJoinFlag
;
690 bool m_shouldBeJoined
;
693 // this semaphore is posted by Run() and the threads Entry() is not
694 // called before it is done
695 wxSemaphore m_semRun
;
697 // this one is signaled when the thread should resume after having been
699 wxSemaphore m_semSuspend
;
702 // ----------------------------------------------------------------------------
703 // thread startup and exit functions
704 // ----------------------------------------------------------------------------
706 void *wxPthreadStart(void *ptr
)
708 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
711 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
713 wxThreadInternal
*pthread
= thread
->m_internal
;
716 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), (long long)pthread
->GetId());
718 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), (long)pthread
->GetId());
721 // associate the thread pointer with the newly created thread so that
722 // wxThread::This() will work
723 int rc
= pthread_setspecific(gs_keySelf
, thread
);
726 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
731 // have to declare this before pthread_cleanup_push() which defines a
735 #if HAVE_THREAD_CLEANUP_FUNCTIONS
736 // install the cleanup handler which will be called if the thread is
738 pthread_cleanup_push(wxPthreadCleanup
, thread
);
739 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
741 // wait for the semaphore to be posted from Run()
742 pthread
->m_semRun
.Wait();
744 // test whether we should run the run at all - may be it was deleted
745 // before it started to Run()?
747 wxCriticalSectionLocker
lock(thread
->m_critsect
);
749 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
750 pthread
->WasCancelled();
755 // call the main entry
756 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to enter its Entry()."),
758 (long long)pthread
->GetId());
760 (long)pthread
->GetId());
763 pthread
->m_exitcode
= thread
->Entry();
765 wxLogTrace(TRACE_THREADS
, _T("Thread %ld Entry() returned %lu."),
767 (long long)pthread
->GetId(), (unsigned long)pthread
->m_exitcode
);
769 (long)pthread
->GetId(), (unsigned long)pthread
->m_exitcode
);
773 wxCriticalSectionLocker
lock(thread
->m_critsect
);
775 // change the state of the thread to "exited" so that
776 // wxPthreadCleanup handler won't do anything from now (if it's
777 // called before we do pthread_cleanup_pop below)
778 pthread
->SetState(STATE_EXITED
);
782 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
783 // contains the matching '}' for the '{' in push, so they must be used
784 // in the same block!
785 #if HAVE_THREAD_CLEANUP_FUNCTIONS
786 // remove the cleanup handler without executing it
787 pthread_cleanup_pop(FALSE
);
788 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
792 // FIXME: deleting a possibly joinable thread here???
795 return EXITCODE_CANCELLED
;
799 // terminate the thread
800 thread
->Exit(pthread
->m_exitcode
);
802 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
808 #if HAVE_THREAD_CLEANUP_FUNCTIONS
810 // this handler is called when the thread is cancelled
811 extern "C" void wxPthreadCleanup(void *ptr
)
813 wxThreadInternal::Cleanup((wxThread
*)ptr
);
816 void wxThreadInternal::Cleanup(wxThread
*thread
)
819 wxCriticalSectionLocker
lock(thread
->m_critsect
);
820 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
822 // thread is already considered as finished.
827 // exit the thread gracefully
828 thread
->Exit(EXITCODE_CANCELLED
);
831 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
833 // ----------------------------------------------------------------------------
835 // ----------------------------------------------------------------------------
837 wxThreadInternal::wxThreadInternal()
841 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
845 // set to TRUE only when the thread starts waiting on m_semSuspend
848 // defaults for joinable threads
849 m_shouldBeJoined
= TRUE
;
850 m_isDetached
= FALSE
;
853 wxThreadInternal::~wxThreadInternal()
857 wxThreadError
wxThreadInternal::Run()
859 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
860 wxT("thread may only be started once after Create()") );
862 SetState(STATE_RUNNING
);
864 // wake up threads waiting for our start
867 return wxTHREAD_NO_ERROR
;
870 void wxThreadInternal::Wait()
872 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
874 // if the thread we're waiting for is waiting for the GUI mutex, we will
875 // deadlock so make sure we release it temporarily
876 if ( wxThread::IsMain() )
879 wxLogTrace(TRACE_THREADS
,
881 _T("Starting to wait for thread %ld to exit."), (long long)GetId());
883 _T("Starting to wait for thread %ld to exit."), (long)GetId());
886 // to avoid memory leaks we should call pthread_join(), but it must only be
887 // done once so use a critical section to serialize the code below
889 wxCriticalSectionLocker
lock(m_csJoinFlag
);
891 if ( m_shouldBeJoined
)
893 // FIXME shouldn't we set cancellation type to DISABLED here? If
894 // we're cancelled inside pthread_join(), things will almost
895 // certainly break - but if we disable the cancellation, we
897 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
899 // this is a serious problem, so use wxLogError and not
900 // wxLogDebug: it is possible to bring the system to its knees
901 // by creating too many threads and not joining them quite
903 wxLogError(_("Failed to join a thread, potential memory leak "
904 "detected - please restart the program"));
907 m_shouldBeJoined
= FALSE
;
911 // reacquire GUI mutex
912 if ( wxThread::IsMain() )
916 void wxThreadInternal::Pause()
918 // the state is set from the thread which pauses us first, this function
919 // is called later so the state should have been already set
920 wxCHECK_RET( m_state
== STATE_PAUSED
,
921 wxT("thread must first be paused with wxThread::Pause().") );
924 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), (long long)GetId());
926 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), (long)GetId());
929 // wait until the semaphore is Post()ed from Resume()
933 void wxThreadInternal::Resume()
935 wxCHECK_RET( m_state
== STATE_PAUSED
,
936 wxT("can't resume thread which is not suspended.") );
938 // the thread might be not actually paused yet - if there were no call to
939 // TestDestroy() since the last call to Pause() for example
940 if ( IsReallyPaused() )
943 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), (long long)GetId());
945 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), (long)GetId());
952 SetReallyPaused(FALSE
);
956 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
964 SetState(STATE_RUNNING
);
967 // -----------------------------------------------------------------------------
968 // wxThread static functions
969 // -----------------------------------------------------------------------------
971 wxThread
*wxThread::This()
973 return (wxThread
*)pthread_getspecific(gs_keySelf
);
976 bool wxThread::IsMain()
978 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
981 void wxThread::Yield()
983 #ifdef HAVE_SCHED_YIELD
988 void wxThread::Sleep(unsigned long milliseconds
)
990 wxUsleep(milliseconds
);
993 int wxThread::GetCPUCount()
995 #if defined(__LINUX__) && wxUSE_FFILE
996 // read from proc (can't use wxTextFile here because it's a special file:
997 // it has 0 size but still can be read from)
1000 wxFFile
file(_T("/proc/cpuinfo"));
1001 if ( file
.IsOpened() )
1003 // slurp the whole file
1005 if ( file
.ReadAll(&s
) )
1007 // (ab)use Replace() to find the number of "processor: num" strings
1008 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1014 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1018 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1021 #elif defined(_SC_NPROCESSORS_ONLN)
1022 // this works for Solaris
1023 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1028 #endif // different ways to get number of CPUs
1035 // VMS is a 64 bit system and threads have 64 bit pointers.
1036 // ??? also needed for other systems????
1037 unsigned long long wxThread::GetCurrentId()
1039 return (unsigned long long)pthread_self();
1041 unsigned long wxThread::GetCurrentId()
1043 return (unsigned long)pthread_self();
1047 bool wxThread::SetConcurrency(size_t level
)
1049 #ifdef HAVE_THR_SETCONCURRENCY
1050 int rc
= thr_setconcurrency(level
);
1053 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1057 #else // !HAVE_THR_SETCONCURRENCY
1058 // ok only for the default value
1060 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1063 // -----------------------------------------------------------------------------
1065 // -----------------------------------------------------------------------------
1067 wxThread::wxThread(wxThreadKind kind
)
1069 // add this thread to the global list of all threads
1070 gs_allThreads
.Add(this);
1072 m_internal
= new wxThreadInternal();
1074 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1077 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1079 if ( m_internal
->GetState() != STATE_NEW
)
1081 // don't recreate thread
1082 return wxTHREAD_RUNNING
;
1085 // set up the thread attribute: right now, we only set thread priority
1086 pthread_attr_t attr
;
1087 pthread_attr_init(&attr
);
1089 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1091 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1093 wxLogError(_("Cannot retrieve thread scheduling policy."));
1097 /* the pthread.h contains too many spaces. This is a work-around */
1098 # undef sched_get_priority_max
1099 #undef sched_get_priority_min
1100 #define sched_get_priority_max(_pol_) \
1101 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1102 #define sched_get_priority_min(_pol_) \
1103 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1106 int max_prio
= sched_get_priority_max(policy
),
1107 min_prio
= sched_get_priority_min(policy
),
1108 prio
= m_internal
->GetPriority();
1110 if ( min_prio
== -1 || max_prio
== -1 )
1112 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1115 else if ( max_prio
== min_prio
)
1117 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1119 // notify the programmer that this doesn't work here
1120 wxLogWarning(_("Thread priority setting is ignored."));
1122 //else: we have default priority, so don't complain
1124 // anyhow, don't do anything because priority is just ignored
1128 struct sched_param sp
;
1129 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1131 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1134 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1136 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1138 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1141 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1143 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1144 // this will make the threads created by this process really concurrent
1145 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1147 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1149 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1151 // VZ: assume that this one is always available (it's rather fundamental),
1152 // if this function is ever missing we should try to use
1153 // pthread_detach() instead (after thread creation)
1156 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1158 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1161 // never try to join detached threads
1162 m_internal
->Detach();
1164 //else: threads are created joinable by default, it's ok
1166 // create the new OS thread object
1167 int rc
= pthread_create
1169 m_internal
->GetIdPtr(),
1175 if ( pthread_attr_destroy(&attr
) != 0 )
1177 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1182 m_internal
->SetState(STATE_EXITED
);
1184 return wxTHREAD_NO_RESOURCE
;
1187 return wxTHREAD_NO_ERROR
;
1190 wxThreadError
wxThread::Run()
1192 wxCriticalSectionLocker
lock(m_critsect
);
1194 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1195 wxT("must call wxThread::Create() first") );
1197 return m_internal
->Run();
1200 // -----------------------------------------------------------------------------
1202 // -----------------------------------------------------------------------------
1204 void wxThread::SetPriority(unsigned int prio
)
1206 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1207 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1208 wxT("invalid thread priority") );
1210 wxCriticalSectionLocker
lock(m_critsect
);
1212 switch ( m_internal
->GetState() )
1215 // thread not yet started, priority will be set when it is
1216 m_internal
->SetPriority(prio
);
1221 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1222 #if defined(__LINUX__)
1223 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1224 // a priority other than 0. Instead, we use the BSD setpriority
1225 // which alllows us to set a 'nice' value between 20 to -20. Only
1226 // super user can set a value less than zero (more negative yields
1227 // higher priority). setpriority set the static priority of a process,
1228 // but this is OK since Linux is configured as a thread per process.
1234 // Map Wx priorites (WXTHREAD_MIN_PRIORITY -
1235 // WXTHREAD_MAX_PRIORITY) into BSD priorities (20 - -20).
1236 // Do calculation of values instead of hard coding them
1237 // to make maintenance easier.
1239 pSpan
= ((float)(WXTHREAD_MAX_PRIORITY
- WXTHREAD_MIN_PRIORITY
)) / 2.0;
1241 // prio starts as ................... // value => (0) >= p <= (n)
1243 fPrio
= ((float)prio
) - pSpan
; // value => (-n) >= p <= (+n)
1245 fPrio
= 0.0 - fPrio
; // value => (+n) <= p >= (-n)
1247 fPrio
= fPrio
* (20. / pSpan
) + .5; // value => (20) <= p >= (-20)
1251 // Clamp prio from 20 - -20;
1252 iPrio
= (iPrio
> 20) ? 20 : iPrio
;
1253 iPrio
= (iPrio
< -20) ? -20 : iPrio
;
1255 if (setpriority(PRIO_PROCESS
, 0, iPrio
) == -1)
1257 wxLogError(_("Failed to set thread priority %d."), prio
);
1262 struct sched_param sparam
;
1263 sparam
.sched_priority
= prio
;
1265 if ( pthread_setschedparam(m_internal
->GetId(),
1266 SCHED_OTHER
, &sparam
) != 0 )
1268 wxLogError(_("Failed to set thread priority %d."), prio
);
1272 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1277 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1281 unsigned int wxThread::GetPriority() const
1283 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1285 return m_internal
->GetPriority();
1288 wxThreadIdType
wxThread::GetId() const
1290 return (wxThreadIdType
) m_internal
->GetId();
1293 // -----------------------------------------------------------------------------
1295 // -----------------------------------------------------------------------------
1297 wxThreadError
wxThread::Pause()
1299 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1300 _T("a thread can't pause itself") );
1302 wxCriticalSectionLocker
lock(m_critsect
);
1304 if ( m_internal
->GetState() != STATE_RUNNING
)
1306 wxLogDebug(wxT("Can't pause thread which is not running."));
1308 return wxTHREAD_NOT_RUNNING
;
1311 // just set a flag, the thread will be really paused only during the next
1312 // call to TestDestroy()
1313 m_internal
->SetState(STATE_PAUSED
);
1315 return wxTHREAD_NO_ERROR
;
1318 wxThreadError
wxThread::Resume()
1320 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1321 _T("a thread can't resume itself") );
1323 wxCriticalSectionLocker
lock(m_critsect
);
1325 wxThreadState state
= m_internal
->GetState();
1330 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1333 m_internal
->Resume();
1335 return wxTHREAD_NO_ERROR
;
1338 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1340 return wxTHREAD_NO_ERROR
;
1343 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1345 return wxTHREAD_MISC_ERROR
;
1349 // -----------------------------------------------------------------------------
1351 // -----------------------------------------------------------------------------
1353 wxThread::ExitCode
wxThread::Wait()
1355 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1356 _T("a thread can't wait for itself") );
1358 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1359 _T("can't wait for detached thread") );
1363 return m_internal
->GetExitCode();
1366 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1368 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1369 _T("a thread can't delete itself") );
1371 bool isDetached
= m_isDetached
;
1374 wxThreadState state
= m_internal
->GetState();
1376 // ask the thread to stop
1377 m_internal
->SetCancelFlag();
1384 // we need to wake up the thread so that PthreadStart() will
1385 // terminate - right now it's blocking on run semaphore in
1387 m_internal
->SignalRun();
1396 // resume the thread first
1397 m_internal
->Resume();
1404 // wait until the thread stops
1409 // return the exit code of the thread
1410 *rc
= m_internal
->GetExitCode();
1413 //else: can't wait for detached threads
1416 return wxTHREAD_NO_ERROR
;
1419 wxThreadError
wxThread::Kill()
1421 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1422 _T("a thread can't kill itself") );
1424 switch ( m_internal
->GetState() )
1428 return wxTHREAD_NOT_RUNNING
;
1431 // resume the thread first
1437 #ifdef HAVE_PTHREAD_CANCEL
1438 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1441 wxLogError(_("Failed to terminate a thread."));
1443 return wxTHREAD_MISC_ERROR
;
1448 // if we use cleanup function, this will be done from
1449 // wxPthreadCleanup()
1450 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1451 ScheduleThreadForDeletion();
1453 // don't call OnExit() here, it can only be called in the
1454 // threads context and we're in the context of another thread
1457 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1461 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1464 return wxTHREAD_NO_ERROR
;
1468 void wxThread::Exit(ExitCode status
)
1470 wxASSERT_MSG( This() == this,
1471 _T("wxThread::Exit() can only be called in the "
1472 "context of the same thread") );
1476 // from the moment we call OnExit(), the main program may terminate at
1477 // any moment, so mark this thread as being already in process of being
1478 // deleted or wxThreadModule::OnExit() will try to delete it again
1479 ScheduleThreadForDeletion();
1482 // don't enter m_critsect before calling OnExit() because the user code
1483 // might deadlock if, for example, it signals a condition in OnExit() (a
1484 // common case) while the main thread calls any of functions entering
1485 // m_critsect on us (almost all of them do)
1488 // delete C++ thread object if this is a detached thread - user is
1489 // responsible for doing this for joinable ones
1492 // FIXME I'm feeling bad about it - what if another thread function is
1493 // called (in another thread context) now? It will try to access
1494 // half destroyed object which will probably result in something
1495 // very bad - but we can't protect this by a crit section unless
1496 // we make it a global object, but this would mean that we can
1497 // only call one thread function at a time :-(
1501 // terminate the thread (pthread_exit() never returns)
1502 pthread_exit(status
);
1504 wxFAIL_MSG(_T("pthread_exit() failed"));
1507 // also test whether we were paused
1508 bool wxThread::TestDestroy()
1510 wxASSERT_MSG( This() == this,
1511 _T("wxThread::TestDestroy() can only be called in the "
1512 "context of the same thread") );
1516 if ( m_internal
->GetState() == STATE_PAUSED
)
1518 m_internal
->SetReallyPaused(TRUE
);
1520 // leave the crit section or the other threads will stop too if they
1521 // try to call any of (seemingly harmless) IsXXX() functions while we
1525 m_internal
->Pause();
1529 // thread wasn't requested to pause, nothing to do
1533 return m_internal
->WasCancelled();
1536 wxThread::~wxThread()
1541 // check that the thread either exited or couldn't be created
1542 if ( m_internal
->GetState() != STATE_EXITED
&&
1543 m_internal
->GetState() != STATE_NEW
)
1545 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1546 "running! The application may crash."), GetId());
1550 #endif // __WXDEBUG__
1554 // remove this thread from the global array
1555 gs_allThreads
.Remove(this);
1558 // -----------------------------------------------------------------------------
1560 // -----------------------------------------------------------------------------
1562 bool wxThread::IsRunning() const
1564 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1566 return m_internal
->GetState() == STATE_RUNNING
;
1569 bool wxThread::IsAlive() const
1571 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1573 switch ( m_internal
->GetState() )
1584 bool wxThread::IsPaused() const
1586 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1588 return (m_internal
->GetState() == STATE_PAUSED
);
1591 //--------------------------------------------------------------------
1593 //--------------------------------------------------------------------
1595 class wxThreadModule
: public wxModule
1598 virtual bool OnInit();
1599 virtual void OnExit();
1602 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1605 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1607 bool wxThreadModule::OnInit()
1609 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1612 wxLogSysError(rc
, _("Thread module initialization failed: "
1613 "failed to create thread key"));
1618 gs_tidMain
= pthread_self();
1620 gs_mutexGui
= new wxMutex();
1621 gs_mutexGui
->Lock();
1623 gs_mutexDeleteThread
= new wxMutex();
1624 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1629 void wxThreadModule::OnExit()
1631 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1633 // are there any threads left which are being deleted right now?
1634 size_t nThreadsBeingDeleted
;
1637 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1638 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1640 if ( nThreadsBeingDeleted
> 0 )
1642 wxLogTrace(TRACE_THREADS
,
1643 _T("Waiting for %lu threads to disappear"),
1644 (unsigned long)nThreadsBeingDeleted
);
1646 // have to wait until all of them disappear
1647 gs_condAllDeleted
->Wait();
1651 // terminate any threads left
1652 size_t count
= gs_allThreads
.GetCount();
1655 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1656 (unsigned long)count
);
1659 for ( size_t n
= 0u; n
< count
; n
++ )
1661 // Delete calls the destructor which removes the current entry. We
1662 // should only delete the first one each time.
1663 gs_allThreads
[0]->Delete();
1666 // destroy GUI mutex
1667 gs_mutexGui
->Unlock();
1670 // and free TLD slot
1671 (void)pthread_key_delete(gs_keySelf
);
1673 delete gs_condAllDeleted
;
1674 delete gs_mutexDeleteThread
;
1677 // ----------------------------------------------------------------------------
1679 // ----------------------------------------------------------------------------
1681 static void ScheduleThreadForDeletion()
1683 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1685 gs_nThreadsBeingDeleted
++;
1687 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1688 (unsigned long)gs_nThreadsBeingDeleted
,
1689 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1692 static void DeleteThread(wxThread
*This
)
1694 // gs_mutexDeleteThread should be unlocked before signalling the condition
1695 // or wxThreadModule::OnExit() would deadlock
1696 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1698 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1702 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1703 _T("no threads scheduled for deletion, yet we delete one?") );
1705 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1706 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1708 if ( !--gs_nThreadsBeingDeleted
)
1710 // no more threads left, signal it
1711 gs_condAllDeleted
->Signal();
1715 void wxMutexGuiEnter()
1717 gs_mutexGui
->Lock();
1720 void wxMutexGuiLeave()
1722 gs_mutexGui
->Unlock();
1725 // ----------------------------------------------------------------------------
1726 // include common implementation code
1727 // ----------------------------------------------------------------------------
1729 #include "wx/thrimpl.cpp"
1731 #endif // wxUSE_THREADS