1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
30 #include "wx/module.h"
34 #include "wx/dynarray.h"
36 #include "wx/stopwatch.h"
47 #ifdef HAVE_THR_SETCONCURRENCY
51 // we use wxFFile under Linux in GetCPUCount()
56 #include <sys/resource.h>
60 #define THR_ID(thr) ((long long)(thr)->GetId())
62 #define THR_ID(thr) ((long)(thr)->GetId())
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // the possible states of the thread and transitions from them
72 STATE_NEW
, // didn't start execution yet (=> RUNNING)
73 STATE_RUNNING
, // running (=> PAUSED or EXITED)
74 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
75 STATE_EXITED
// thread doesn't exist any more
78 // the exit value of a thread which has been cancelled
79 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
81 // trace mask for wxThread operations
82 #define TRACE_THREADS _T("thread")
84 // you can get additional debugging messages for the semaphore operations
85 #define TRACE_SEMA _T("semaphore")
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 static void ScheduleThreadForDeletion();
92 static void DeleteThread(wxThread
*This
);
94 // ----------------------------------------------------------------------------
96 // ----------------------------------------------------------------------------
98 // an (non owning) array of pointers to threads
99 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
101 // an entry for a thread we can wait for
103 // -----------------------------------------------------------------------------
105 // -----------------------------------------------------------------------------
107 // we keep the list of all threads created by the application to be able to
108 // terminate them on exit if there are some left - otherwise the process would
110 static wxArrayThread gs_allThreads
;
112 // the id of the main thread
113 static pthread_t gs_tidMain
= (pthread_t
)-1;
115 // the key for the pointer to the associated wxThread object
116 static pthread_key_t gs_keySelf
;
118 // the number of threads which are being deleted - the program won't exit
119 // until there are any left
120 static size_t gs_nThreadsBeingDeleted
= 0;
122 // a mutex to protect gs_nThreadsBeingDeleted
123 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
125 // and a condition variable which will be signaled when all
126 // gs_nThreadsBeingDeleted will have been deleted
127 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
129 // this mutex must be acquired before any call to a GUI function
130 // (it's not inside #if wxUSE_GUI because this file is compiled as part
132 static wxMutex
*gs_mutexGui
= NULL
;
134 // when we wait for a thread to exit, we're blocking on a condition which the
135 // thread signals in its SignalExit() method -- but this condition can't be a
136 // member of the thread itself as a detached thread may delete itself at any
137 // moment and accessing the condition member of the thread after this would
138 // result in a disaster
140 // so instead we maintain a global list of the structs below for the threads
141 // we're interested in waiting on
143 // ============================================================================
144 // wxMutex implementation
145 // ============================================================================
147 // ----------------------------------------------------------------------------
149 // ----------------------------------------------------------------------------
151 // this is a simple wrapper around pthread_mutex_t which provides error
153 class wxMutexInternal
156 wxMutexInternal(wxMutexType mutexType
);
160 wxMutexError
TryLock();
161 wxMutexError
Unlock();
163 bool IsOk() const { return m_isOk
; }
166 pthread_mutex_t m_mutex
;
169 // wxConditionInternal uses our m_mutex
170 friend class wxConditionInternal
;
173 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
174 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
175 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
176 // in the library, otherwise we wouldn't compile this code at all)
177 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
180 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
185 case wxMUTEX_RECURSIVE
:
186 // support recursive locks like Win32, i.e. a thread can lock a
187 // mutex which it had itself already locked
189 // unfortunately initialization of recursive mutexes is non
190 // portable, so try several methods
191 #ifdef HAVE_PTHREAD_MUTEXATTR_T
193 pthread_mutexattr_t attr
;
194 pthread_mutexattr_init(&attr
);
195 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
197 err
= pthread_mutex_init(&m_mutex
, &attr
);
199 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
200 // we can use this only as initializer so we have to assign it
201 // first to a temp var - assigning directly to m_mutex wouldn't
204 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
207 #else // no recursive mutexes
209 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
213 wxFAIL_MSG( _T("unknown mutex type") );
216 case wxMUTEX_DEFAULT
:
217 err
= pthread_mutex_init(&m_mutex
, NULL
);
224 wxLogApiError( wxT("pthread_mutex_init()"), err
);
228 wxMutexInternal::~wxMutexInternal()
232 int err
= pthread_mutex_destroy(&m_mutex
);
235 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
240 wxMutexError
wxMutexInternal::Lock()
242 int err
= pthread_mutex_lock(&m_mutex
);
246 // only error checking mutexes return this value and so it's an
247 // unexpected situation -- hence use assert, not wxLogDebug
248 wxFAIL_MSG( _T("mutex deadlock prevented") );
249 return wxMUTEX_DEAD_LOCK
;
252 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
256 return wxMUTEX_NO_ERROR
;
259 wxLogApiError(_T("pthread_mutex_lock()"), err
);
262 return wxMUTEX_MISC_ERROR
;
265 wxMutexError
wxMutexInternal::TryLock()
267 int err
= pthread_mutex_trylock(&m_mutex
);
271 // not an error: mutex is already locked, but we're prepared for
276 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
280 return wxMUTEX_NO_ERROR
;
283 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
286 return wxMUTEX_MISC_ERROR
;
289 wxMutexError
wxMutexInternal::Unlock()
291 int err
= pthread_mutex_unlock(&m_mutex
);
295 // we don't own the mutex
296 return wxMUTEX_UNLOCKED
;
299 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
303 return wxMUTEX_NO_ERROR
;
306 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
309 return wxMUTEX_MISC_ERROR
;
312 // ===========================================================================
313 // wxCondition implementation
314 // ===========================================================================
316 // ---------------------------------------------------------------------------
317 // wxConditionInternal
318 // ---------------------------------------------------------------------------
320 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
321 // with a pthread_mutex_t)
322 class wxConditionInternal
325 wxConditionInternal(wxMutex
& mutex
);
326 ~wxConditionInternal();
328 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
331 wxCondError
WaitTimeout(unsigned long milliseconds
);
333 wxCondError
Signal();
334 wxCondError
Broadcast();
337 // get the POSIX mutex associated with us
338 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
341 pthread_cond_t m_cond
;
346 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
349 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
355 wxLogApiError(_T("pthread_cond_init()"), err
);
359 wxConditionInternal::~wxConditionInternal()
363 int err
= pthread_cond_destroy(&m_cond
);
366 wxLogApiError(_T("pthread_cond_destroy()"), err
);
371 wxCondError
wxConditionInternal::Wait()
373 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
376 wxLogApiError(_T("pthread_cond_wait()"), err
);
378 return wxCOND_MISC_ERROR
;
381 return wxCOND_NO_ERROR
;
384 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
386 wxLongLong curtime
= wxGetLocalTimeMillis();
387 curtime
+= milliseconds
;
388 wxLongLong temp
= curtime
/ 1000;
389 int sec
= temp
.GetLo();
391 temp
= curtime
- temp
;
392 int millis
= temp
.GetLo();
397 tspec
.tv_nsec
= millis
* 1000L * 1000L;
399 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
403 return wxCOND_TIMEOUT
;
406 return wxCOND_NO_ERROR
;
409 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
412 return wxCOND_MISC_ERROR
;
415 wxCondError
wxConditionInternal::Signal()
417 int err
= pthread_cond_signal(&m_cond
);
420 wxLogApiError(_T("pthread_cond_signal()"), err
);
422 return wxCOND_MISC_ERROR
;
425 return wxCOND_NO_ERROR
;
428 wxCondError
wxConditionInternal::Broadcast()
430 int err
= pthread_cond_broadcast(&m_cond
);
433 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
435 return wxCOND_MISC_ERROR
;
438 return wxCOND_NO_ERROR
;
441 // ===========================================================================
442 // wxSemaphore implementation
443 // ===========================================================================
445 // ---------------------------------------------------------------------------
446 // wxSemaphoreInternal
447 // ---------------------------------------------------------------------------
449 // we implement the semaphores using mutexes and conditions instead of using
450 // the sem_xxx() POSIX functions because they're not widely available and also
451 // because it's impossible to implement WaitTimeout() using them
452 class wxSemaphoreInternal
455 wxSemaphoreInternal(int initialcount
, int maxcount
);
457 bool IsOk() const { return m_isOk
; }
460 wxSemaError
TryWait();
461 wxSemaError
WaitTimeout(unsigned long milliseconds
);
475 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
479 if ( (initialcount
< 0 || maxcount
< 0) ||
480 ((maxcount
> 0) && (initialcount
> maxcount
)) )
482 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
488 m_maxcount
= (size_t)maxcount
;
489 m_count
= (size_t)initialcount
;
492 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
495 wxSemaError
wxSemaphoreInternal::Wait()
497 wxMutexLocker
locker(m_mutex
);
499 while ( m_count
== 0 )
501 wxLogTrace(TRACE_SEMA
,
502 _T("Thread %ld waiting for semaphore to become signalled"),
503 wxThread::GetCurrentId());
505 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
506 return wxSEMA_MISC_ERROR
;
508 wxLogTrace(TRACE_SEMA
,
509 _T("Thread %ld finished waiting for semaphore, count = %lu"),
510 wxThread::GetCurrentId(), (unsigned long)m_count
);
515 return wxSEMA_NO_ERROR
;
518 wxSemaError
wxSemaphoreInternal::TryWait()
520 wxMutexLocker
locker(m_mutex
);
527 return wxSEMA_NO_ERROR
;
530 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
532 wxMutexLocker
locker(m_mutex
);
534 wxLongLong startTime
= wxGetLocalTimeMillis();
536 while ( m_count
== 0 )
538 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
539 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
540 if ( remainingTime
<= 0 )
543 return wxSEMA_TIMEOUT
;
546 switch ( m_cond
.WaitTimeout(remainingTime
) )
549 return wxSEMA_TIMEOUT
;
552 return wxSEMA_MISC_ERROR
;
554 case wxCOND_NO_ERROR
:
561 return wxSEMA_NO_ERROR
;
564 wxSemaError
wxSemaphoreInternal::Post()
566 wxMutexLocker
locker(m_mutex
);
568 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
570 return wxSEMA_OVERFLOW
;
575 wxLogTrace(TRACE_SEMA
,
576 _T("Thread %ld about to signal semaphore, count = %lu"),
577 wxThread::GetCurrentId(), (unsigned long)m_count
);
579 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
583 // ===========================================================================
584 // wxThread implementation
585 // ===========================================================================
587 // the thread callback functions must have the C linkage
591 #ifdef wxHAVE_PTHREAD_CLEANUP
592 // thread exit function
593 void wxPthreadCleanup(void *ptr
);
594 #endif // wxHAVE_PTHREAD_CLEANUP
596 void *wxPthreadStart(void *ptr
);
600 // ----------------------------------------------------------------------------
602 // ----------------------------------------------------------------------------
604 class wxThreadInternal
610 // thread entry function
611 static void *PthreadStart(wxThread
*thread
);
616 // unblock the thread allowing it to run
617 void SignalRun() { m_semRun
.Post(); }
618 // ask the thread to terminate
620 // go to sleep until Resume() is called
627 int GetPriority() const { return m_prio
; }
628 void SetPriority(int prio
) { m_prio
= prio
; }
630 wxThreadState
GetState() const { return m_state
; }
631 void SetState(wxThreadState state
)
634 static const wxChar
*stateNames
[] =
642 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
643 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
644 #endif // __WXDEBUG__
649 pthread_t
GetId() const { return m_threadId
; }
650 pthread_t
*GetIdPtr() { return &m_threadId
; }
652 void SetCancelFlag() { m_cancelled
= TRUE
; }
653 bool WasCancelled() const { return m_cancelled
; }
655 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
656 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
659 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
660 bool IsReallyPaused() const { return m_isPaused
; }
662 // tell the thread that it is a detached one
665 wxCriticalSectionLocker
lock(m_csJoinFlag
);
667 m_shouldBeJoined
= FALSE
;
671 #ifdef wxHAVE_PTHREAD_CLEANUP
672 // this is used by wxPthreadCleanup() only
673 static void Cleanup(wxThread
*thread
);
674 #endif // wxHAVE_PTHREAD_CLEANUP
677 pthread_t m_threadId
; // id of the thread
678 wxThreadState m_state
; // see wxThreadState enum
679 int m_prio
; // in wxWidgets units: from 0 to 100
681 // this flag is set when the thread should terminate
684 // this flag is set when the thread is blocking on m_semSuspend
687 // the thread exit code - only used for joinable (!detached) threads and
688 // is only valid after the thread termination
689 wxThread::ExitCode m_exitcode
;
691 // many threads may call Wait(), but only one of them should call
692 // pthread_join(), so we have to keep track of this
693 wxCriticalSection m_csJoinFlag
;
694 bool m_shouldBeJoined
;
697 // this semaphore is posted by Run() and the threads Entry() is not
698 // called before it is done
699 wxSemaphore m_semRun
;
701 // this one is signaled when the thread should resume after having been
703 wxSemaphore m_semSuspend
;
706 // ----------------------------------------------------------------------------
707 // thread startup and exit functions
708 // ----------------------------------------------------------------------------
710 void *wxPthreadStart(void *ptr
)
712 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
715 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
717 wxThreadInternal
*pthread
= thread
->m_internal
;
719 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
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 #ifdef wxHAVE_PTHREAD_CLEANUP
736 // install the cleanup handler which will be called if the thread is
738 pthread_cleanup_push(wxPthreadCleanup
, thread
);
739 #endif // wxHAVE_PTHREAD_CLEANUP
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
,
757 _T("Thread %ld about to enter its Entry()."),
760 pthread
->m_exitcode
= thread
->Entry();
762 wxLogTrace(TRACE_THREADS
,
763 _T("Thread %ld Entry() returned %lu."),
764 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
767 wxCriticalSectionLocker
lock(thread
->m_critsect
);
769 // change the state of the thread to "exited" so that
770 // wxPthreadCleanup handler won't do anything from now (if it's
771 // called before we do pthread_cleanup_pop below)
772 pthread
->SetState(STATE_EXITED
);
776 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
777 // '}' for the '{' in push, so they must be used in the same block!
778 #ifdef wxHAVE_PTHREAD_CLEANUP
780 // under Tru64 we get a warning from macro expansion
782 #pragma message disable(declbutnotref)
785 // remove the cleanup handler without executing it
786 pthread_cleanup_pop(FALSE
);
789 #pragma message restore
791 #endif // wxHAVE_PTHREAD_CLEANUP
795 // FIXME: deleting a possibly joinable thread here???
798 return EXITCODE_CANCELLED
;
802 // terminate the thread
803 thread
->Exit(pthread
->m_exitcode
);
805 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
811 #ifdef wxHAVE_PTHREAD_CLEANUP
813 // this handler is called when the thread is cancelled
814 extern "C" void wxPthreadCleanup(void *ptr
)
816 wxThreadInternal::Cleanup((wxThread
*)ptr
);
819 void wxThreadInternal::Cleanup(wxThread
*thread
)
821 if (pthread_getspecific(gs_keySelf
) == 0) return;
823 wxCriticalSectionLocker
lock(thread
->m_critsect
);
824 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
826 // thread is already considered as finished.
831 // exit the thread gracefully
832 thread
->Exit(EXITCODE_CANCELLED
);
835 #endif // wxHAVE_PTHREAD_CLEANUP
837 // ----------------------------------------------------------------------------
839 // ----------------------------------------------------------------------------
841 wxThreadInternal::wxThreadInternal()
845 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
849 // set to TRUE only when the thread starts waiting on m_semSuspend
852 // defaults for joinable threads
853 m_shouldBeJoined
= TRUE
;
854 m_isDetached
= FALSE
;
857 wxThreadInternal::~wxThreadInternal()
861 wxThreadError
wxThreadInternal::Run()
863 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
864 wxT("thread may only be started once after Create()") );
866 SetState(STATE_RUNNING
);
868 // wake up threads waiting for our start
871 return wxTHREAD_NO_ERROR
;
874 void wxThreadInternal::Wait()
876 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
878 // if the thread we're waiting for is waiting for the GUI mutex, we will
879 // deadlock so make sure we release it temporarily
880 if ( wxThread::IsMain() )
883 wxLogTrace(TRACE_THREADS
,
884 _T("Starting to wait for thread %ld to exit."),
887 // to avoid memory leaks we should call pthread_join(), but it must only be
888 // done once so use a critical section to serialize the code below
890 wxCriticalSectionLocker
lock(m_csJoinFlag
);
892 if ( m_shouldBeJoined
)
894 // FIXME shouldn't we set cancellation type to DISABLED here? If
895 // we're cancelled inside pthread_join(), things will almost
896 // certainly break - but if we disable the cancellation, we
898 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
900 // this is a serious problem, so use wxLogError and not
901 // wxLogDebug: it is possible to bring the system to its knees
902 // by creating too many threads and not joining them quite
904 wxLogError(_("Failed to join a thread, potential memory leak 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().") );
923 wxLogTrace(TRACE_THREADS
,
924 _T("Thread %ld goes to sleep."), THR_ID(this));
926 // wait until the semaphore is Post()ed from Resume()
930 void wxThreadInternal::Resume()
932 wxCHECK_RET( m_state
== STATE_PAUSED
,
933 wxT("can't resume thread which is not suspended.") );
935 // the thread might be not actually paused yet - if there were no call to
936 // TestDestroy() since the last call to Pause() for example
937 if ( IsReallyPaused() )
939 wxLogTrace(TRACE_THREADS
,
940 _T("Waking up thread %ld"), THR_ID(this));
946 SetReallyPaused(FALSE
);
950 wxLogTrace(TRACE_THREADS
,
951 _T("Thread %ld is not yet really paused"), THR_ID(this));
954 SetState(STATE_RUNNING
);
957 // -----------------------------------------------------------------------------
958 // wxThread static functions
959 // -----------------------------------------------------------------------------
961 wxThread
*wxThread::This()
963 return (wxThread
*)pthread_getspecific(gs_keySelf
);
966 bool wxThread::IsMain()
968 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
971 void wxThread::Yield()
973 #ifdef HAVE_SCHED_YIELD
978 void wxThread::Sleep(unsigned long milliseconds
)
980 wxMilliSleep(milliseconds
);
983 int wxThread::GetCPUCount()
985 #if defined(__LINUX__) && wxUSE_FFILE
986 // read from proc (can't use wxTextFile here because it's a special file:
987 // it has 0 size but still can be read from)
990 wxFFile
file(_T("/proc/cpuinfo"));
991 if ( file
.IsOpened() )
993 // slurp the whole file
995 if ( file
.ReadAll(&s
) )
997 // (ab)use Replace() to find the number of "processor: num" strings
998 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1004 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1008 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1011 #elif defined(_SC_NPROCESSORS_ONLN)
1012 // this works for Solaris
1013 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1018 #endif // different ways to get number of CPUs
1024 // VMS is a 64 bit system and threads have 64 bit pointers.
1025 // FIXME: also needed for other systems????
1027 unsigned long long wxThread::GetCurrentId()
1029 return (unsigned long long)pthread_self();
1034 unsigned long wxThread::GetCurrentId()
1036 return (unsigned long)pthread_self();
1039 #endif // __VMS/!__VMS
1042 bool wxThread::SetConcurrency(size_t level
)
1044 #ifdef HAVE_THR_SETCONCURRENCY
1045 int rc
= thr_setconcurrency(level
);
1048 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1052 #else // !HAVE_THR_SETCONCURRENCY
1053 // ok only for the default value
1055 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1058 // -----------------------------------------------------------------------------
1060 // -----------------------------------------------------------------------------
1062 wxThread::wxThread(wxThreadKind kind
)
1064 // add this thread to the global list of all threads
1065 gs_allThreads
.Add(this);
1067 m_internal
= new wxThreadInternal();
1069 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1072 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1073 #define WXUNUSED_STACKSIZE(identifier) identifier
1075 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1078 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1080 if ( m_internal
->GetState() != STATE_NEW
)
1082 // don't recreate thread
1083 return wxTHREAD_RUNNING
;
1086 // set up the thread attribute: right now, we only set thread priority
1087 pthread_attr_t attr
;
1088 pthread_attr_init(&attr
);
1090 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1092 pthread_attr_setstacksize(&attr
, stackSize
);
1095 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1097 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1099 wxLogError(_("Cannot retrieve thread scheduling policy."));
1103 /* the pthread.h contains too many spaces. This is a work-around */
1104 # undef sched_get_priority_max
1105 #undef sched_get_priority_min
1106 #define sched_get_priority_max(_pol_) \
1107 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1108 #define sched_get_priority_min(_pol_) \
1109 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1112 int max_prio
= sched_get_priority_max(policy
),
1113 min_prio
= sched_get_priority_min(policy
),
1114 prio
= m_internal
->GetPriority();
1116 if ( min_prio
== -1 || max_prio
== -1 )
1118 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1121 else if ( max_prio
== min_prio
)
1123 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1125 // notify the programmer that this doesn't work here
1126 wxLogWarning(_("Thread priority setting is ignored."));
1128 //else: we have default priority, so don't complain
1130 // anyhow, don't do anything because priority is just ignored
1134 struct sched_param sp
;
1135 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1137 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1140 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1142 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1144 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1147 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1149 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1150 // this will make the threads created by this process really concurrent
1151 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1153 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1155 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1157 // VZ: assume that this one is always available (it's rather fundamental),
1158 // if this function is ever missing we should try to use
1159 // pthread_detach() instead (after thread creation)
1162 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1164 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1167 // never try to join detached threads
1168 m_internal
->Detach();
1170 //else: threads are created joinable by default, it's ok
1172 // create the new OS thread object
1173 int rc
= pthread_create
1175 m_internal
->GetIdPtr(),
1181 if ( pthread_attr_destroy(&attr
) != 0 )
1183 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1188 m_internal
->SetState(STATE_EXITED
);
1190 return wxTHREAD_NO_RESOURCE
;
1193 return wxTHREAD_NO_ERROR
;
1196 wxThreadError
wxThread::Run()
1198 wxCriticalSectionLocker
lock(m_critsect
);
1200 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1201 wxT("must call wxThread::Create() first") );
1203 return m_internal
->Run();
1206 // -----------------------------------------------------------------------------
1208 // -----------------------------------------------------------------------------
1210 void wxThread::SetPriority(unsigned int prio
)
1212 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1213 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1214 wxT("invalid thread priority") );
1216 wxCriticalSectionLocker
lock(m_critsect
);
1218 switch ( m_internal
->GetState() )
1221 // thread not yet started, priority will be set when it is
1222 m_internal
->SetPriority(prio
);
1227 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1228 #if defined(__LINUX__)
1229 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1230 // a priority other than 0. Instead, we use the BSD setpriority
1231 // which alllows us to set a 'nice' value between 20 to -20. Only
1232 // super user can set a value less than zero (more negative yields
1233 // higher priority). setpriority set the static priority of a
1234 // process, but this is OK since Linux is configured as a thread
1237 // FIXME this is not true for 2.6!!
1239 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1240 // to Unix priorities 20..-20
1241 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1243 wxLogError(_("Failed to set thread priority %d."), prio
);
1247 struct sched_param sparam
;
1248 sparam
.sched_priority
= prio
;
1250 if ( pthread_setschedparam(m_internal
->GetId(),
1251 SCHED_OTHER
, &sparam
) != 0 )
1253 wxLogError(_("Failed to set thread priority %d."), prio
);
1257 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1262 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1266 unsigned int wxThread::GetPriority() const
1268 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1270 return m_internal
->GetPriority();
1273 wxThreadIdType
wxThread::GetId() const
1275 return (wxThreadIdType
) m_internal
->GetId();
1278 // -----------------------------------------------------------------------------
1280 // -----------------------------------------------------------------------------
1282 wxThreadError
wxThread::Pause()
1284 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1285 _T("a thread can't pause itself") );
1287 wxCriticalSectionLocker
lock(m_critsect
);
1289 if ( m_internal
->GetState() != STATE_RUNNING
)
1291 wxLogDebug(wxT("Can't pause thread which is not running."));
1293 return wxTHREAD_NOT_RUNNING
;
1296 // just set a flag, the thread will be really paused only during the next
1297 // call to TestDestroy()
1298 m_internal
->SetState(STATE_PAUSED
);
1300 return wxTHREAD_NO_ERROR
;
1303 wxThreadError
wxThread::Resume()
1305 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1306 _T("a thread can't resume itself") );
1308 wxCriticalSectionLocker
lock(m_critsect
);
1310 wxThreadState state
= m_internal
->GetState();
1315 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1318 m_internal
->Resume();
1320 return wxTHREAD_NO_ERROR
;
1323 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1325 return wxTHREAD_NO_ERROR
;
1328 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1330 return wxTHREAD_MISC_ERROR
;
1334 // -----------------------------------------------------------------------------
1336 // -----------------------------------------------------------------------------
1338 wxThread::ExitCode
wxThread::Wait()
1340 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1341 _T("a thread can't wait for itself") );
1343 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1344 _T("can't wait for detached thread") );
1348 return m_internal
->GetExitCode();
1351 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1353 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1354 _T("a thread can't delete itself") );
1356 bool isDetached
= m_isDetached
;
1359 wxThreadState state
= m_internal
->GetState();
1361 // ask the thread to stop
1362 m_internal
->SetCancelFlag();
1369 // we need to wake up the thread so that PthreadStart() will
1370 // terminate - right now it's blocking on run semaphore in
1372 m_internal
->SignalRun();
1381 // resume the thread first
1382 m_internal
->Resume();
1389 // wait until the thread stops
1394 // return the exit code of the thread
1395 *rc
= m_internal
->GetExitCode();
1398 //else: can't wait for detached threads
1401 return wxTHREAD_NO_ERROR
;
1404 wxThreadError
wxThread::Kill()
1406 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1407 _T("a thread can't kill itself") );
1409 switch ( m_internal
->GetState() )
1413 return wxTHREAD_NOT_RUNNING
;
1416 // resume the thread first
1422 #ifdef HAVE_PTHREAD_CANCEL
1423 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1424 #endif // HAVE_PTHREAD_CANCEL
1426 wxLogError(_("Failed to terminate a thread."));
1428 return wxTHREAD_MISC_ERROR
;
1431 #ifdef HAVE_PTHREAD_CANCEL
1434 // if we use cleanup function, this will be done from
1435 // wxPthreadCleanup()
1436 #ifndef wxHAVE_PTHREAD_CLEANUP
1437 ScheduleThreadForDeletion();
1439 // don't call OnExit() here, it can only be called in the
1440 // threads context and we're in the context of another thread
1443 #endif // wxHAVE_PTHREAD_CLEANUP
1447 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1450 return wxTHREAD_NO_ERROR
;
1451 #endif // HAVE_PTHREAD_CANCEL
1455 void wxThread::Exit(ExitCode status
)
1457 wxASSERT_MSG( This() == this,
1458 _T("wxThread::Exit() can only be called in the context of the same thread") );
1462 // from the moment we call OnExit(), the main program may terminate at
1463 // any moment, so mark this thread as being already in process of being
1464 // deleted or wxThreadModule::OnExit() will try to delete it again
1465 ScheduleThreadForDeletion();
1468 // don't enter m_critsect before calling OnExit() because the user code
1469 // might deadlock if, for example, it signals a condition in OnExit() (a
1470 // common case) while the main thread calls any of functions entering
1471 // m_critsect on us (almost all of them do)
1474 // delete C++ thread object if this is a detached thread - user is
1475 // responsible for doing this for joinable ones
1478 // FIXME I'm feeling bad about it - what if another thread function is
1479 // called (in another thread context) now? It will try to access
1480 // half destroyed object which will probably result in something
1481 // very bad - but we can't protect this by a crit section unless
1482 // we make it a global object, but this would mean that we can
1483 // only call one thread function at a time :-(
1485 pthread_setspecific(gs_keySelf
, 0);
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."),
1542 #endif // __WXDEBUG__
1546 // remove this thread from the global array
1547 gs_allThreads
.Remove(this);
1550 // -----------------------------------------------------------------------------
1552 // -----------------------------------------------------------------------------
1554 bool wxThread::IsRunning() const
1556 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1558 return m_internal
->GetState() == STATE_RUNNING
;
1561 bool wxThread::IsAlive() const
1563 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1565 switch ( m_internal
->GetState() )
1576 bool wxThread::IsPaused() const
1578 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1580 return (m_internal
->GetState() == STATE_PAUSED
);
1583 //--------------------------------------------------------------------
1585 //--------------------------------------------------------------------
1587 class wxThreadModule
: public wxModule
1590 virtual bool OnInit();
1591 virtual void OnExit();
1594 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1597 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1599 bool wxThreadModule::OnInit()
1601 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1604 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1609 gs_tidMain
= pthread_self();
1611 gs_mutexGui
= new wxMutex();
1612 gs_mutexGui
->Lock();
1614 gs_mutexDeleteThread
= new wxMutex();
1615 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1620 void wxThreadModule::OnExit()
1622 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1624 // are there any threads left which are being deleted right now?
1625 size_t nThreadsBeingDeleted
;
1628 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1629 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1631 if ( nThreadsBeingDeleted
> 0 )
1633 wxLogTrace(TRACE_THREADS
,
1634 _T("Waiting for %lu threads to disappear"),
1635 (unsigned long)nThreadsBeingDeleted
);
1637 // have to wait until all of them disappear
1638 gs_condAllDeleted
->Wait();
1642 // terminate any threads left
1643 size_t count
= gs_allThreads
.GetCount();
1646 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1647 (unsigned long)count
);
1650 for ( size_t n
= 0u; n
< count
; n
++ )
1652 // Delete calls the destructor which removes the current entry. We
1653 // should only delete the first one each time.
1654 gs_allThreads
[0]->Delete();
1657 // destroy GUI mutex
1658 gs_mutexGui
->Unlock();
1661 // and free TLD slot
1662 (void)pthread_key_delete(gs_keySelf
);
1664 delete gs_condAllDeleted
;
1665 delete gs_mutexDeleteThread
;
1668 // ----------------------------------------------------------------------------
1670 // ----------------------------------------------------------------------------
1672 static void ScheduleThreadForDeletion()
1674 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1676 gs_nThreadsBeingDeleted
++;
1678 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1679 (unsigned long)gs_nThreadsBeingDeleted
,
1680 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1683 static void DeleteThread(wxThread
*This
)
1685 // gs_mutexDeleteThread should be unlocked before signalling the condition
1686 // or wxThreadModule::OnExit() would deadlock
1687 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1689 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1693 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1694 _T("no threads scheduled for deletion, yet we delete one?") );
1696 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1697 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1699 if ( !--gs_nThreadsBeingDeleted
)
1701 // no more threads left, signal it
1702 gs_condAllDeleted
->Signal();
1706 void wxMutexGuiEnter()
1708 gs_mutexGui
->Lock();
1711 void wxMutexGuiLeave()
1713 gs_mutexGui
->Unlock();
1716 // ----------------------------------------------------------------------------
1717 // include common implementation code
1718 // ----------------------------------------------------------------------------
1720 #include "wx/thrimpl.cpp"
1722 #endif // wxUSE_THREADS