1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/threadpsx.cpp
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
32 #include "wx/dynarray.h"
38 #include "wx/module.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_PTR(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 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
178 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
179 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
180 // in the library, otherwise we wouldn't compile this code at all)
181 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
184 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
189 case wxMUTEX_RECURSIVE
:
190 // support recursive locks like Win32, i.e. a thread can lock a
191 // mutex which it had itself already locked
193 // unfortunately initialization of recursive mutexes is non
194 // portable, so try several methods
195 #ifdef HAVE_PTHREAD_MUTEXATTR_T
197 pthread_mutexattr_t attr
;
198 pthread_mutexattr_init(&attr
);
199 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
201 err
= pthread_mutex_init(&m_mutex
, &attr
);
203 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
204 // we can use this only as initializer so we have to assign it
205 // first to a temp var - assigning directly to m_mutex wouldn't
208 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
211 #else // no recursive mutexes
213 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
217 wxFAIL_MSG( _T("unknown mutex type") );
220 case wxMUTEX_DEFAULT
:
221 err
= pthread_mutex_init(&m_mutex
, NULL
);
228 wxLogApiError( wxT("pthread_mutex_init()"), err
);
232 wxMutexInternal::~wxMutexInternal()
236 int err
= pthread_mutex_destroy(&m_mutex
);
239 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
244 wxMutexError
wxMutexInternal::Lock()
246 int err
= pthread_mutex_lock(&m_mutex
);
250 // only error checking mutexes return this value and so it's an
251 // unexpected situation -- hence use assert, not wxLogDebug
252 wxFAIL_MSG( _T("mutex deadlock prevented") );
253 return wxMUTEX_DEAD_LOCK
;
256 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
260 return wxMUTEX_NO_ERROR
;
263 wxLogApiError(_T("pthread_mutex_lock()"), err
);
266 return wxMUTEX_MISC_ERROR
;
269 wxMutexError
wxMutexInternal::TryLock()
271 int err
= pthread_mutex_trylock(&m_mutex
);
275 // not an error: mutex is already locked, but we're prepared for
280 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
284 return wxMUTEX_NO_ERROR
;
287 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
290 return wxMUTEX_MISC_ERROR
;
293 wxMutexError
wxMutexInternal::Unlock()
295 int err
= pthread_mutex_unlock(&m_mutex
);
299 // we don't own the mutex
300 return wxMUTEX_UNLOCKED
;
303 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
307 return wxMUTEX_NO_ERROR
;
310 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
313 return wxMUTEX_MISC_ERROR
;
316 // ===========================================================================
317 // wxCondition implementation
318 // ===========================================================================
320 // ---------------------------------------------------------------------------
321 // wxConditionInternal
322 // ---------------------------------------------------------------------------
324 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
325 // with a pthread_mutex_t)
326 class wxConditionInternal
329 wxConditionInternal(wxMutex
& mutex
);
330 ~wxConditionInternal();
332 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
335 wxCondError
WaitTimeout(unsigned long milliseconds
);
337 wxCondError
Signal();
338 wxCondError
Broadcast();
341 // get the POSIX mutex associated with us
342 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
345 pthread_cond_t m_cond
;
350 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
353 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
359 wxLogApiError(_T("pthread_cond_init()"), err
);
363 wxConditionInternal::~wxConditionInternal()
367 int err
= pthread_cond_destroy(&m_cond
);
370 wxLogApiError(_T("pthread_cond_destroy()"), err
);
375 wxCondError
wxConditionInternal::Wait()
377 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
380 wxLogApiError(_T("pthread_cond_wait()"), err
);
382 return wxCOND_MISC_ERROR
;
385 return wxCOND_NO_ERROR
;
388 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
390 wxLongLong curtime
= wxGetLocalTimeMillis();
391 curtime
+= milliseconds
;
392 wxLongLong temp
= curtime
/ 1000;
393 int sec
= temp
.GetLo();
395 temp
= curtime
- temp
;
396 int millis
= temp
.GetLo();
401 tspec
.tv_nsec
= millis
* 1000L * 1000L;
403 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
407 return wxCOND_TIMEOUT
;
410 return wxCOND_NO_ERROR
;
413 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
416 return wxCOND_MISC_ERROR
;
419 wxCondError
wxConditionInternal::Signal()
421 int err
= pthread_cond_signal(&m_cond
);
424 wxLogApiError(_T("pthread_cond_signal()"), err
);
426 return wxCOND_MISC_ERROR
;
429 return wxCOND_NO_ERROR
;
432 wxCondError
wxConditionInternal::Broadcast()
434 int err
= pthread_cond_broadcast(&m_cond
);
437 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
439 return wxCOND_MISC_ERROR
;
442 return wxCOND_NO_ERROR
;
445 // ===========================================================================
446 // wxSemaphore implementation
447 // ===========================================================================
449 // ---------------------------------------------------------------------------
450 // wxSemaphoreInternal
451 // ---------------------------------------------------------------------------
453 // we implement the semaphores using mutexes and conditions instead of using
454 // the sem_xxx() POSIX functions because they're not widely available and also
455 // because it's impossible to implement WaitTimeout() using them
456 class wxSemaphoreInternal
459 wxSemaphoreInternal(int initialcount
, int maxcount
);
461 bool IsOk() const { return m_isOk
; }
464 wxSemaError
TryWait();
465 wxSemaError
WaitTimeout(unsigned long milliseconds
);
479 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
483 if ( (initialcount
< 0 || maxcount
< 0) ||
484 ((maxcount
> 0) && (initialcount
> maxcount
)) )
486 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
492 m_maxcount
= (size_t)maxcount
;
493 m_count
= (size_t)initialcount
;
496 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
499 wxSemaError
wxSemaphoreInternal::Wait()
501 wxMutexLocker
locker(m_mutex
);
503 while ( m_count
== 0 )
505 wxLogTrace(TRACE_SEMA
,
506 _T("Thread %ld waiting for semaphore to become signalled"),
507 wxThread::GetCurrentId());
509 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
510 return wxSEMA_MISC_ERROR
;
512 wxLogTrace(TRACE_SEMA
,
513 _T("Thread %ld finished waiting for semaphore, count = %lu"),
514 wxThread::GetCurrentId(), (unsigned long)m_count
);
519 return wxSEMA_NO_ERROR
;
522 wxSemaError
wxSemaphoreInternal::TryWait()
524 wxMutexLocker
locker(m_mutex
);
531 return wxSEMA_NO_ERROR
;
534 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
536 wxMutexLocker
locker(m_mutex
);
538 wxLongLong startTime
= wxGetLocalTimeMillis();
540 while ( m_count
== 0 )
542 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
543 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
544 if ( remainingTime
<= 0 )
547 return wxSEMA_TIMEOUT
;
550 switch ( m_cond
.WaitTimeout(remainingTime
) )
553 return wxSEMA_TIMEOUT
;
556 return wxSEMA_MISC_ERROR
;
558 case wxCOND_NO_ERROR
:
565 return wxSEMA_NO_ERROR
;
568 wxSemaError
wxSemaphoreInternal::Post()
570 wxMutexLocker
locker(m_mutex
);
572 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
574 return wxSEMA_OVERFLOW
;
579 wxLogTrace(TRACE_SEMA
,
580 _T("Thread %ld about to signal semaphore, count = %lu"),
581 wxThread::GetCurrentId(), (unsigned long)m_count
);
583 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
587 // ===========================================================================
588 // wxThread implementation
589 // ===========================================================================
591 // the thread callback functions must have the C linkage
595 #ifdef wxHAVE_PTHREAD_CLEANUP
596 // thread exit function
597 void wxPthreadCleanup(void *ptr
);
598 #endif // wxHAVE_PTHREAD_CLEANUP
600 void *wxPthreadStart(void *ptr
);
604 // ----------------------------------------------------------------------------
606 // ----------------------------------------------------------------------------
608 class wxThreadInternal
614 // thread entry function
615 static void *PthreadStart(wxThread
*thread
);
620 // unblock the thread allowing it to run
621 void SignalRun() { m_semRun
.Post(); }
622 // ask the thread to terminate
624 // go to sleep until Resume() is called
631 int GetPriority() const { return m_prio
; }
632 void SetPriority(int prio
) { m_prio
= prio
; }
634 wxThreadState
GetState() const { return m_state
; }
635 void SetState(wxThreadState state
)
638 static const wxChar
*stateNames
[] =
646 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
647 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
648 #endif // __WXDEBUG__
653 pthread_t
GetId() const { return m_threadId
; }
654 pthread_t
*GetIdPtr() { return &m_threadId
; }
656 void SetCancelFlag() { m_cancelled
= true; }
657 bool WasCancelled() const { return m_cancelled
; }
659 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
660 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
663 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
664 bool IsReallyPaused() const { return m_isPaused
; }
666 // tell the thread that it is a detached one
669 wxCriticalSectionLocker
lock(m_csJoinFlag
);
671 m_shouldBeJoined
= false;
675 #ifdef wxHAVE_PTHREAD_CLEANUP
676 // this is used by wxPthreadCleanup() only
677 static void Cleanup(wxThread
*thread
);
678 #endif // wxHAVE_PTHREAD_CLEANUP
681 pthread_t m_threadId
; // id of the thread
682 wxThreadState m_state
; // see wxThreadState enum
683 int m_prio
; // in wxWidgets units: from 0 to 100
685 // this flag is set when the thread should terminate
688 // this flag is set when the thread is blocking on m_semSuspend
691 // the thread exit code - only used for joinable (!detached) threads and
692 // is only valid after the thread termination
693 wxThread::ExitCode m_exitcode
;
695 // many threads may call Wait(), but only one of them should call
696 // pthread_join(), so we have to keep track of this
697 wxCriticalSection m_csJoinFlag
;
698 bool m_shouldBeJoined
;
701 // this semaphore is posted by Run() and the threads Entry() is not
702 // called before it is done
703 wxSemaphore m_semRun
;
705 // this one is signaled when the thread should resume after having been
707 wxSemaphore m_semSuspend
;
710 // ----------------------------------------------------------------------------
711 // thread startup and exit functions
712 // ----------------------------------------------------------------------------
714 void *wxPthreadStart(void *ptr
)
716 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
719 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
721 wxThreadInternal
*pthread
= thread
->m_internal
;
723 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
725 // associate the thread pointer with the newly created thread so that
726 // wxThread::This() will work
727 int rc
= pthread_setspecific(gs_keySelf
, thread
);
730 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
735 // have to declare this before pthread_cleanup_push() which defines a
739 #ifdef wxHAVE_PTHREAD_CLEANUP
740 // install the cleanup handler which will be called if the thread is
742 pthread_cleanup_push(wxPthreadCleanup
, thread
);
743 #endif // wxHAVE_PTHREAD_CLEANUP
745 // wait for the semaphore to be posted from Run()
746 pthread
->m_semRun
.Wait();
748 // test whether we should run the run at all - may be it was deleted
749 // before it started to Run()?
751 wxCriticalSectionLocker
lock(thread
->m_critsect
);
753 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
754 pthread
->WasCancelled();
759 // call the main entry
760 wxLogTrace(TRACE_THREADS
,
761 _T("Thread %ld about to enter its Entry()."),
764 pthread
->m_exitcode
= thread
->Entry();
766 wxLogTrace(TRACE_THREADS
,
767 _T("Thread %ld Entry() returned %lu."),
768 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
771 wxCriticalSectionLocker
lock(thread
->m_critsect
);
773 // change the state of the thread to "exited" so that
774 // wxPthreadCleanup handler won't do anything from now (if it's
775 // called before we do pthread_cleanup_pop below)
776 pthread
->SetState(STATE_EXITED
);
780 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
781 // '}' for the '{' in push, so they must be used in the same block!
782 #ifdef wxHAVE_PTHREAD_CLEANUP
784 // under Tru64 we get a warning from macro expansion
786 #pragma message disable(declbutnotref)
789 // remove the cleanup handler without executing it
790 pthread_cleanup_pop(FALSE
);
793 #pragma message restore
795 #endif // wxHAVE_PTHREAD_CLEANUP
799 // FIXME: deleting a possibly joinable thread here???
802 return EXITCODE_CANCELLED
;
806 // terminate the thread
807 thread
->Exit(pthread
->m_exitcode
);
809 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
815 #ifdef wxHAVE_PTHREAD_CLEANUP
817 // this handler is called when the thread is cancelled
818 extern "C" void wxPthreadCleanup(void *ptr
)
820 wxThreadInternal::Cleanup((wxThread
*)ptr
);
823 void wxThreadInternal::Cleanup(wxThread
*thread
)
825 if (pthread_getspecific(gs_keySelf
) == 0) return;
827 wxCriticalSectionLocker
lock(thread
->m_critsect
);
828 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
830 // thread is already considered as finished.
835 // exit the thread gracefully
836 thread
->Exit(EXITCODE_CANCELLED
);
839 #endif // wxHAVE_PTHREAD_CLEANUP
841 // ----------------------------------------------------------------------------
843 // ----------------------------------------------------------------------------
845 wxThreadInternal::wxThreadInternal()
849 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
853 // set to true only when the thread starts waiting on m_semSuspend
856 // defaults for joinable threads
857 m_shouldBeJoined
= true;
858 m_isDetached
= false;
861 wxThreadInternal::~wxThreadInternal()
865 wxThreadError
wxThreadInternal::Run()
867 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
868 wxT("thread may only be started once after Create()") );
870 SetState(STATE_RUNNING
);
872 // wake up threads waiting for our start
875 return wxTHREAD_NO_ERROR
;
878 void wxThreadInternal::Wait()
880 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
882 // if the thread we're waiting for is waiting for the GUI mutex, we will
883 // deadlock so make sure we release it temporarily
884 if ( wxThread::IsMain() )
887 wxLogTrace(TRACE_THREADS
,
888 _T("Starting to wait for thread %ld to exit."),
891 // to avoid memory leaks we should call pthread_join(), but it must only be
892 // done once so use a critical section to serialize the code below
894 wxCriticalSectionLocker
lock(m_csJoinFlag
);
896 if ( m_shouldBeJoined
)
898 // FIXME shouldn't we set cancellation type to DISABLED here? If
899 // we're cancelled inside pthread_join(), things will almost
900 // certainly break - but if we disable the cancellation, we
902 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
904 // this is a serious problem, so use wxLogError and not
905 // wxLogDebug: it is possible to bring the system to its knees
906 // by creating too many threads and not joining them quite
908 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
911 m_shouldBeJoined
= false;
915 // reacquire GUI mutex
916 if ( wxThread::IsMain() )
920 void wxThreadInternal::Pause()
922 // the state is set from the thread which pauses us first, this function
923 // is called later so the state should have been already set
924 wxCHECK_RET( m_state
== STATE_PAUSED
,
925 wxT("thread must first be paused with wxThread::Pause().") );
927 wxLogTrace(TRACE_THREADS
,
928 _T("Thread %ld goes to sleep."), THR_ID(this));
930 // wait until the semaphore is Post()ed from Resume()
934 void wxThreadInternal::Resume()
936 wxCHECK_RET( m_state
== STATE_PAUSED
,
937 wxT("can't resume thread which is not suspended.") );
939 // the thread might be not actually paused yet - if there were no call to
940 // TestDestroy() since the last call to Pause() for example
941 if ( IsReallyPaused() )
943 wxLogTrace(TRACE_THREADS
,
944 _T("Waking up thread %ld"), THR_ID(this));
950 SetReallyPaused(false);
954 wxLogTrace(TRACE_THREADS
,
955 _T("Thread %ld is not yet really paused"), THR_ID(this));
958 SetState(STATE_RUNNING
);
961 // -----------------------------------------------------------------------------
962 // wxThread static functions
963 // -----------------------------------------------------------------------------
965 wxThread
*wxThread::This()
967 return (wxThread
*)pthread_getspecific(gs_keySelf
);
970 bool wxThread::IsMain()
972 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
975 void wxThread::Yield()
977 #ifdef HAVE_SCHED_YIELD
982 void wxThread::Sleep(unsigned long milliseconds
)
984 wxMilliSleep(milliseconds
);
987 int wxThread::GetCPUCount()
989 #if defined(__LINUX__) && wxUSE_FFILE
990 // read from proc (can't use wxTextFile here because it's a special file:
991 // it has 0 size but still can be read from)
994 wxFFile
file(_T("/proc/cpuinfo"));
995 if ( file
.IsOpened() )
997 // slurp the whole file
999 if ( file
.ReadAll(&s
) )
1001 // (ab)use Replace() to find the number of "processor: num" strings
1002 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1008 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1012 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1015 #elif defined(_SC_NPROCESSORS_ONLN)
1016 // this works for Solaris
1017 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1022 #endif // different ways to get number of CPUs
1028 // VMS is a 64 bit system and threads have 64 bit pointers.
1029 // FIXME: also needed for other systems????
1031 unsigned long long wxThread::GetCurrentId()
1033 return (unsigned long long)pthread_self();
1038 unsigned long wxThread::GetCurrentId()
1040 return (unsigned long)pthread_self();
1043 #endif // __VMS/!__VMS
1046 bool wxThread::SetConcurrency(size_t level
)
1048 #ifdef HAVE_THR_SETCONCURRENCY
1049 int rc
= thr_setconcurrency(level
);
1052 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1056 #else // !HAVE_THR_SETCONCURRENCY
1057 // ok only for the default value
1059 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1062 // -----------------------------------------------------------------------------
1064 // -----------------------------------------------------------------------------
1066 wxThread::wxThread(wxThreadKind kind
)
1068 // add this thread to the global list of all threads
1069 gs_allThreads
.Add(this);
1071 m_internal
= new wxThreadInternal();
1073 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1076 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1077 #define WXUNUSED_STACKSIZE(identifier) identifier
1079 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1082 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1084 if ( m_internal
->GetState() != STATE_NEW
)
1086 // don't recreate thread
1087 return wxTHREAD_RUNNING
;
1090 // set up the thread attribute: right now, we only set thread priority
1091 pthread_attr_t attr
;
1092 pthread_attr_init(&attr
);
1094 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1096 pthread_attr_setstacksize(&attr
, stackSize
);
1099 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1101 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1103 wxLogError(_("Cannot retrieve thread scheduling policy."));
1107 /* the pthread.h contains too many spaces. This is a work-around */
1108 # undef sched_get_priority_max
1109 #undef sched_get_priority_min
1110 #define sched_get_priority_max(_pol_) \
1111 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1112 #define sched_get_priority_min(_pol_) \
1113 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1116 int max_prio
= sched_get_priority_max(policy
),
1117 min_prio
= sched_get_priority_min(policy
),
1118 prio
= m_internal
->GetPriority();
1120 if ( min_prio
== -1 || max_prio
== -1 )
1122 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1125 else if ( max_prio
== min_prio
)
1127 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1129 // notify the programmer that this doesn't work here
1130 wxLogWarning(_("Thread priority setting is ignored."));
1132 //else: we have default priority, so don't complain
1134 // anyhow, don't do anything because priority is just ignored
1138 struct sched_param sp
;
1139 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1141 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1144 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1146 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1148 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1151 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1153 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1154 // this will make the threads created by this process really concurrent
1155 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1157 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1159 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1161 // VZ: assume that this one is always available (it's rather fundamental),
1162 // if this function is ever missing we should try to use
1163 // pthread_detach() instead (after thread creation)
1166 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1168 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1171 // never try to join detached threads
1172 m_internal
->Detach();
1174 //else: threads are created joinable by default, it's ok
1176 // create the new OS thread object
1177 int rc
= pthread_create
1179 m_internal
->GetIdPtr(),
1185 if ( pthread_attr_destroy(&attr
) != 0 )
1187 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1192 m_internal
->SetState(STATE_EXITED
);
1194 return wxTHREAD_NO_RESOURCE
;
1197 return wxTHREAD_NO_ERROR
;
1200 wxThreadError
wxThread::Run()
1202 wxCriticalSectionLocker
lock(m_critsect
);
1204 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1205 wxT("must call wxThread::Create() first") );
1207 return m_internal
->Run();
1210 // -----------------------------------------------------------------------------
1212 // -----------------------------------------------------------------------------
1214 void wxThread::SetPriority(unsigned int prio
)
1216 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1217 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1218 wxT("invalid thread priority") );
1220 wxCriticalSectionLocker
lock(m_critsect
);
1222 switch ( m_internal
->GetState() )
1225 // thread not yet started, priority will be set when it is
1226 m_internal
->SetPriority(prio
);
1231 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1232 #if defined(__LINUX__)
1233 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1234 // a priority other than 0. Instead, we use the BSD setpriority
1235 // which alllows us to set a 'nice' value between 20 to -20. Only
1236 // super user can set a value less than zero (more negative yields
1237 // higher priority). setpriority set the static priority of a
1238 // process, but this is OK since Linux is configured as a thread
1241 // FIXME this is not true for 2.6!!
1243 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1244 // to Unix priorities 20..-20
1245 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1247 wxLogError(_("Failed to set thread priority %d."), prio
);
1251 struct sched_param sparam
;
1252 sparam
.sched_priority
= prio
;
1254 if ( pthread_setschedparam(m_internal
->GetId(),
1255 SCHED_OTHER
, &sparam
) != 0 )
1257 wxLogError(_("Failed to set thread priority %d."), prio
);
1261 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1266 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1270 unsigned int wxThread::GetPriority() const
1272 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1274 return m_internal
->GetPriority();
1277 wxThreadIdType
wxThread::GetId() const
1279 return (wxThreadIdType
) m_internal
->GetId();
1282 // -----------------------------------------------------------------------------
1284 // -----------------------------------------------------------------------------
1286 wxThreadError
wxThread::Pause()
1288 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1289 _T("a thread can't pause itself") );
1291 wxCriticalSectionLocker
lock(m_critsect
);
1293 if ( m_internal
->GetState() != STATE_RUNNING
)
1295 wxLogDebug(wxT("Can't pause thread which is not running."));
1297 return wxTHREAD_NOT_RUNNING
;
1300 // just set a flag, the thread will be really paused only during the next
1301 // call to TestDestroy()
1302 m_internal
->SetState(STATE_PAUSED
);
1304 return wxTHREAD_NO_ERROR
;
1307 wxThreadError
wxThread::Resume()
1309 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1310 _T("a thread can't resume itself") );
1312 wxCriticalSectionLocker
lock(m_critsect
);
1314 wxThreadState state
= m_internal
->GetState();
1319 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1322 m_internal
->Resume();
1324 return wxTHREAD_NO_ERROR
;
1327 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1329 return wxTHREAD_NO_ERROR
;
1332 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1334 return wxTHREAD_MISC_ERROR
;
1338 // -----------------------------------------------------------------------------
1340 // -----------------------------------------------------------------------------
1342 wxThread::ExitCode
wxThread::Wait()
1344 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1345 _T("a thread can't wait for itself") );
1347 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1348 _T("can't wait for detached thread") );
1352 return m_internal
->GetExitCode();
1355 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1357 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1358 _T("a thread can't delete itself") );
1360 bool isDetached
= m_isDetached
;
1363 wxThreadState state
= m_internal
->GetState();
1365 // ask the thread to stop
1366 m_internal
->SetCancelFlag();
1373 // we need to wake up the thread so that PthreadStart() will
1374 // terminate - right now it's blocking on run semaphore in
1376 m_internal
->SignalRun();
1385 // resume the thread first
1386 m_internal
->Resume();
1393 // wait until the thread stops
1398 // return the exit code of the thread
1399 *rc
= m_internal
->GetExitCode();
1402 //else: can't wait for detached threads
1405 return wxTHREAD_NO_ERROR
;
1408 wxThreadError
wxThread::Kill()
1410 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1411 _T("a thread can't kill itself") );
1413 switch ( m_internal
->GetState() )
1417 return wxTHREAD_NOT_RUNNING
;
1420 // resume the thread first
1426 #ifdef HAVE_PTHREAD_CANCEL
1427 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1428 #endif // HAVE_PTHREAD_CANCEL
1430 wxLogError(_("Failed to terminate a thread."));
1432 return wxTHREAD_MISC_ERROR
;
1435 #ifdef HAVE_PTHREAD_CANCEL
1438 // if we use cleanup function, this will be done from
1439 // wxPthreadCleanup()
1440 #ifndef wxHAVE_PTHREAD_CLEANUP
1441 ScheduleThreadForDeletion();
1443 // don't call OnExit() here, it can only be called in the
1444 // threads context and we're in the context of another thread
1447 #endif // wxHAVE_PTHREAD_CLEANUP
1451 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1454 return wxTHREAD_NO_ERROR
;
1455 #endif // HAVE_PTHREAD_CANCEL
1459 void wxThread::Exit(ExitCode status
)
1461 wxASSERT_MSG( This() == this,
1462 _T("wxThread::Exit() can only be called in the context of the same thread") );
1466 // from the moment we call OnExit(), the main program may terminate at
1467 // any moment, so mark this thread as being already in process of being
1468 // deleted or wxThreadModule::OnExit() will try to delete it again
1469 ScheduleThreadForDeletion();
1472 // don't enter m_critsect before calling OnExit() because the user code
1473 // might deadlock if, for example, it signals a condition in OnExit() (a
1474 // common case) while the main thread calls any of functions entering
1475 // m_critsect on us (almost all of them do)
1478 // delete C++ thread object if this is a detached thread - user is
1479 // responsible for doing this for joinable ones
1482 // FIXME I'm feeling bad about it - what if another thread function is
1483 // called (in another thread context) now? It will try to access
1484 // half destroyed object which will probably result in something
1485 // very bad - but we can't protect this by a crit section unless
1486 // we make it a global object, but this would mean that we can
1487 // only call one thread function at a time :-(
1489 pthread_setspecific(gs_keySelf
, 0);
1494 m_internal
->SetState(STATE_EXITED
);
1498 // terminate the thread (pthread_exit() never returns)
1499 pthread_exit(status
);
1501 wxFAIL_MSG(_T("pthread_exit() failed"));
1504 // also test whether we were paused
1505 bool wxThread::TestDestroy()
1507 wxASSERT_MSG( This() == this,
1508 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1512 if ( m_internal
->GetState() == STATE_PAUSED
)
1514 m_internal
->SetReallyPaused(true);
1516 // leave the crit section or the other threads will stop too if they
1517 // try to call any of (seemingly harmless) IsXXX() functions while we
1521 m_internal
->Pause();
1525 // thread wasn't requested to pause, nothing to do
1529 return m_internal
->WasCancelled();
1532 wxThread::~wxThread()
1537 // check that the thread either exited or couldn't be created
1538 if ( m_internal
->GetState() != STATE_EXITED
&&
1539 m_internal
->GetState() != STATE_NEW
)
1541 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1546 #endif // __WXDEBUG__
1550 // remove this thread from the global array
1551 gs_allThreads
.Remove(this);
1554 // -----------------------------------------------------------------------------
1556 // -----------------------------------------------------------------------------
1558 bool wxThread::IsRunning() const
1560 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1562 return m_internal
->GetState() == STATE_RUNNING
;
1565 bool wxThread::IsAlive() const
1567 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1569 switch ( m_internal
->GetState() )
1580 bool wxThread::IsPaused() const
1582 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1584 return (m_internal
->GetState() == STATE_PAUSED
);
1587 //--------------------------------------------------------------------
1589 //--------------------------------------------------------------------
1591 class wxThreadModule
: public wxModule
1594 virtual bool OnInit();
1595 virtual void OnExit();
1598 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1601 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1603 bool wxThreadModule::OnInit()
1605 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1608 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1613 gs_tidMain
= pthread_self();
1615 gs_mutexGui
= new wxMutex();
1616 gs_mutexGui
->Lock();
1618 gs_mutexDeleteThread
= new wxMutex();
1619 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1624 void wxThreadModule::OnExit()
1626 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1628 // are there any threads left which are being deleted right now?
1629 size_t nThreadsBeingDeleted
;
1632 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1633 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1635 if ( nThreadsBeingDeleted
> 0 )
1637 wxLogTrace(TRACE_THREADS
,
1638 _T("Waiting for %lu threads to disappear"),
1639 (unsigned long)nThreadsBeingDeleted
);
1641 // have to wait until all of them disappear
1642 gs_condAllDeleted
->Wait();
1646 // terminate any threads left
1647 size_t count
= gs_allThreads
.GetCount();
1650 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1651 (unsigned long)count
);
1654 for ( size_t n
= 0u; n
< count
; n
++ )
1656 // Delete calls the destructor which removes the current entry. We
1657 // should only delete the first one each time.
1658 gs_allThreads
[0]->Delete();
1661 // destroy GUI mutex
1662 gs_mutexGui
->Unlock();
1665 // and free TLD slot
1666 (void)pthread_key_delete(gs_keySelf
);
1668 delete gs_condAllDeleted
;
1669 delete gs_mutexDeleteThread
;
1672 // ----------------------------------------------------------------------------
1674 // ----------------------------------------------------------------------------
1676 static void ScheduleThreadForDeletion()
1678 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1680 gs_nThreadsBeingDeleted
++;
1682 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1683 (unsigned long)gs_nThreadsBeingDeleted
,
1684 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1687 static void DeleteThread(wxThread
*This
)
1689 // gs_mutexDeleteThread should be unlocked before signalling the condition
1690 // or wxThreadModule::OnExit() would deadlock
1691 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1693 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1697 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1698 _T("no threads scheduled for deletion, yet we delete one?") );
1700 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1701 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1703 if ( !--gs_nThreadsBeingDeleted
)
1705 // no more threads left, signal it
1706 gs_condAllDeleted
->Signal();
1710 void wxMutexGuiEnter()
1712 gs_mutexGui
->Lock();
1715 void wxMutexGuiLeave()
1717 gs_mutexGui
->Unlock();
1720 // ----------------------------------------------------------------------------
1721 // include common implementation code
1722 // ----------------------------------------------------------------------------
1724 #include "wx/thrimpl.cpp"
1726 #endif // wxUSE_THREADS