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"
37 #include "wx/stopwatch.h"
38 #include "wx/module.h"
50 #ifdef HAVE_THR_SETCONCURRENCY
54 // we use wxFFile under Linux in GetCPUCount()
59 #include <sys/resource.h>
63 #define THR_ID(thr) ((long long)(thr)->GetId())
65 #define THR_ID(thr) ((long)(thr)->GetId())
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // the possible states of the thread and transitions from them
75 STATE_NEW
, // didn't start execution yet (=> RUNNING)
76 STATE_RUNNING
, // running (=> PAUSED or EXITED)
77 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
78 STATE_EXITED
// thread doesn't exist any more
81 // the exit value of a thread which has been cancelled
82 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
84 // trace mask for wxThread operations
85 #define TRACE_THREADS _T("thread")
87 // you can get additional debugging messages for the semaphore operations
88 #define TRACE_SEMA _T("semaphore")
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 static void ScheduleThreadForDeletion();
95 static void DeleteThread(wxThread
*This
);
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 // an (non owning) array of pointers to threads
102 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
104 // an entry for a thread we can wait for
106 // -----------------------------------------------------------------------------
108 // -----------------------------------------------------------------------------
110 // we keep the list of all threads created by the application to be able to
111 // terminate them on exit if there are some left - otherwise the process would
113 static wxArrayThread gs_allThreads
;
115 // a mutex to protect gs_allThreads
116 static wxMutex
*gs_mutexAllThreads
= NULL
;
118 // the id of the main thread
119 static pthread_t gs_tidMain
= (pthread_t
)-1;
121 // the key for the pointer to the associated wxThread object
122 static pthread_key_t gs_keySelf
;
124 // the number of threads which are being deleted - the program won't exit
125 // until there are any left
126 static size_t gs_nThreadsBeingDeleted
= 0;
128 // a mutex to protect gs_nThreadsBeingDeleted
129 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
131 // and a condition variable which will be signaled when all
132 // gs_nThreadsBeingDeleted will have been deleted
133 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
136 // this mutex must be acquired before any call to a GUI function
137 // (it's not inside #if wxUSE_GUI because this file is compiled as part
139 static wxMutex
*gs_mutexGui
= NULL
;
142 // when we wait for a thread to exit, we're blocking on a condition which the
143 // thread signals in its SignalExit() method -- but this condition can't be a
144 // member of the thread itself as a detached thread may delete itself at any
145 // moment and accessing the condition member of the thread after this would
146 // result in a disaster
148 // so instead we maintain a global list of the structs below for the threads
149 // we're interested in waiting on
151 // ============================================================================
152 // wxMutex implementation
153 // ============================================================================
155 // ----------------------------------------------------------------------------
157 // ----------------------------------------------------------------------------
159 // this is a simple wrapper around pthread_mutex_t which provides error
161 class wxMutexInternal
164 wxMutexInternal(wxMutexType mutexType
);
168 wxMutexError
TryLock();
169 wxMutexError
Unlock();
171 bool IsOk() const { return m_isOk
; }
174 pthread_mutex_t m_mutex
;
177 // wxConditionInternal uses our m_mutex
178 friend class wxConditionInternal
;
181 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
182 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
183 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
184 // in the library, otherwise we wouldn't compile this code at all)
185 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
188 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
193 case wxMUTEX_RECURSIVE
:
194 // support recursive locks like Win32, i.e. a thread can lock a
195 // mutex which it had itself already locked
197 // unfortunately initialization of recursive mutexes is non
198 // portable, so try several methods
199 #ifdef HAVE_PTHREAD_MUTEXATTR_T
201 pthread_mutexattr_t attr
;
202 pthread_mutexattr_init(&attr
);
203 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
205 err
= pthread_mutex_init(&m_mutex
, &attr
);
207 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
208 // we can use this only as initializer so we have to assign it
209 // first to a temp var - assigning directly to m_mutex wouldn't
212 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
215 #else // no recursive mutexes
217 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
221 wxFAIL_MSG( _T("unknown mutex type") );
224 case wxMUTEX_DEFAULT
:
225 err
= pthread_mutex_init(&m_mutex
, NULL
);
232 wxLogApiError( wxT("pthread_mutex_init()"), err
);
236 wxMutexInternal::~wxMutexInternal()
240 int err
= pthread_mutex_destroy(&m_mutex
);
243 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
248 wxMutexError
wxMutexInternal::Lock()
250 int err
= pthread_mutex_lock(&m_mutex
);
254 // only error checking mutexes return this value and so it's an
255 // unexpected situation -- hence use assert, not wxLogDebug
256 wxFAIL_MSG( _T("mutex deadlock prevented") );
257 return wxMUTEX_DEAD_LOCK
;
260 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
264 return wxMUTEX_NO_ERROR
;
267 wxLogApiError(_T("pthread_mutex_lock()"), err
);
270 return wxMUTEX_MISC_ERROR
;
273 wxMutexError
wxMutexInternal::TryLock()
275 int err
= pthread_mutex_trylock(&m_mutex
);
279 // not an error: mutex is already locked, but we're prepared for
284 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
288 return wxMUTEX_NO_ERROR
;
291 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
294 return wxMUTEX_MISC_ERROR
;
297 wxMutexError
wxMutexInternal::Unlock()
299 int err
= pthread_mutex_unlock(&m_mutex
);
303 // we don't own the mutex
304 return wxMUTEX_UNLOCKED
;
307 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
311 return wxMUTEX_NO_ERROR
;
314 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
317 return wxMUTEX_MISC_ERROR
;
320 // ===========================================================================
321 // wxCondition implementation
322 // ===========================================================================
324 // ---------------------------------------------------------------------------
325 // wxConditionInternal
326 // ---------------------------------------------------------------------------
328 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
329 // with a pthread_mutex_t)
330 class wxConditionInternal
333 wxConditionInternal(wxMutex
& mutex
);
334 ~wxConditionInternal();
336 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
339 wxCondError
WaitTimeout(unsigned long milliseconds
);
341 wxCondError
Signal();
342 wxCondError
Broadcast();
345 // get the POSIX mutex associated with us
346 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
349 pthread_cond_t m_cond
;
354 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
357 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
363 wxLogApiError(_T("pthread_cond_init()"), err
);
367 wxConditionInternal::~wxConditionInternal()
371 int err
= pthread_cond_destroy(&m_cond
);
374 wxLogApiError(_T("pthread_cond_destroy()"), err
);
379 wxCondError
wxConditionInternal::Wait()
381 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
384 wxLogApiError(_T("pthread_cond_wait()"), err
);
386 return wxCOND_MISC_ERROR
;
389 return wxCOND_NO_ERROR
;
392 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
394 wxLongLong curtime
= wxGetLocalTimeMillis();
395 curtime
+= milliseconds
;
396 wxLongLong temp
= curtime
/ 1000;
397 int sec
= temp
.GetLo();
399 temp
= curtime
- temp
;
400 int millis
= temp
.GetLo();
405 tspec
.tv_nsec
= millis
* 1000L * 1000L;
407 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
411 return wxCOND_TIMEOUT
;
414 return wxCOND_NO_ERROR
;
417 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
420 return wxCOND_MISC_ERROR
;
423 wxCondError
wxConditionInternal::Signal()
425 int err
= pthread_cond_signal(&m_cond
);
428 wxLogApiError(_T("pthread_cond_signal()"), err
);
430 return wxCOND_MISC_ERROR
;
433 return wxCOND_NO_ERROR
;
436 wxCondError
wxConditionInternal::Broadcast()
438 int err
= pthread_cond_broadcast(&m_cond
);
441 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
443 return wxCOND_MISC_ERROR
;
446 return wxCOND_NO_ERROR
;
449 // ===========================================================================
450 // wxSemaphore implementation
451 // ===========================================================================
453 // ---------------------------------------------------------------------------
454 // wxSemaphoreInternal
455 // ---------------------------------------------------------------------------
457 // we implement the semaphores using mutexes and conditions instead of using
458 // the sem_xxx() POSIX functions because they're not widely available and also
459 // because it's impossible to implement WaitTimeout() using them
460 class wxSemaphoreInternal
463 wxSemaphoreInternal(int initialcount
, int maxcount
);
465 bool IsOk() const { return m_isOk
; }
468 wxSemaError
TryWait();
469 wxSemaError
WaitTimeout(unsigned long milliseconds
);
483 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
487 if ( (initialcount
< 0 || maxcount
< 0) ||
488 ((maxcount
> 0) && (initialcount
> maxcount
)) )
490 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
496 m_maxcount
= (size_t)maxcount
;
497 m_count
= (size_t)initialcount
;
500 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
503 wxSemaError
wxSemaphoreInternal::Wait()
505 wxMutexLocker
locker(m_mutex
);
507 while ( m_count
== 0 )
509 wxLogTrace(TRACE_SEMA
,
510 _T("Thread %ld waiting for semaphore to become signalled"),
511 wxThread::GetCurrentId());
513 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
514 return wxSEMA_MISC_ERROR
;
516 wxLogTrace(TRACE_SEMA
,
517 _T("Thread %ld finished waiting for semaphore, count = %lu"),
518 wxThread::GetCurrentId(), (unsigned long)m_count
);
523 return wxSEMA_NO_ERROR
;
526 wxSemaError
wxSemaphoreInternal::TryWait()
528 wxMutexLocker
locker(m_mutex
);
535 return wxSEMA_NO_ERROR
;
538 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
540 wxMutexLocker
locker(m_mutex
);
542 wxLongLong startTime
= wxGetLocalTimeMillis();
544 while ( m_count
== 0 )
546 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
547 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
548 if ( remainingTime
<= 0 )
551 return wxSEMA_TIMEOUT
;
554 switch ( m_cond
.WaitTimeout(remainingTime
) )
557 return wxSEMA_TIMEOUT
;
560 return wxSEMA_MISC_ERROR
;
562 case wxCOND_NO_ERROR
:
569 return wxSEMA_NO_ERROR
;
572 wxSemaError
wxSemaphoreInternal::Post()
574 wxMutexLocker
locker(m_mutex
);
576 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
578 return wxSEMA_OVERFLOW
;
583 wxLogTrace(TRACE_SEMA
,
584 _T("Thread %ld about to signal semaphore, count = %lu"),
585 wxThread::GetCurrentId(), (unsigned long)m_count
);
587 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
591 // ===========================================================================
592 // wxThread implementation
593 // ===========================================================================
595 // the thread callback functions must have the C linkage
599 #ifdef wxHAVE_PTHREAD_CLEANUP
600 // thread exit function
601 void wxPthreadCleanup(void *ptr
);
602 #endif // wxHAVE_PTHREAD_CLEANUP
604 void *wxPthreadStart(void *ptr
);
608 // ----------------------------------------------------------------------------
610 // ----------------------------------------------------------------------------
612 class wxThreadInternal
618 // thread entry function
619 static void *PthreadStart(wxThread
*thread
);
624 // unblock the thread allowing it to run
625 void SignalRun() { m_semRun
.Post(); }
626 // ask the thread to terminate
628 // go to sleep until Resume() is called
635 int GetPriority() const { return m_prio
; }
636 void SetPriority(int prio
) { m_prio
= prio
; }
638 wxThreadState
GetState() const { return m_state
; }
639 void SetState(wxThreadState state
)
642 static const wxChar
*stateNames
[] =
650 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
651 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
652 #endif // __WXDEBUG__
657 pthread_t
GetId() const { return m_threadId
; }
658 pthread_t
*GetIdPtr() { return &m_threadId
; }
660 void SetCancelFlag() { m_cancelled
= true; }
661 bool WasCancelled() const { return m_cancelled
; }
663 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
664 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
667 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
668 bool IsReallyPaused() const { return m_isPaused
; }
670 // tell the thread that it is a detached one
673 wxCriticalSectionLocker
lock(m_csJoinFlag
);
675 m_shouldBeJoined
= false;
679 #ifdef wxHAVE_PTHREAD_CLEANUP
680 // this is used by wxPthreadCleanup() only
681 static void Cleanup(wxThread
*thread
);
682 #endif // wxHAVE_PTHREAD_CLEANUP
685 pthread_t m_threadId
; // id of the thread
686 wxThreadState m_state
; // see wxThreadState enum
687 int m_prio
; // in wxWidgets units: from 0 to 100
689 // this flag is set when the thread should terminate
692 // this flag is set when the thread is blocking on m_semSuspend
695 // the thread exit code - only used for joinable (!detached) threads and
696 // is only valid after the thread termination
697 wxThread::ExitCode m_exitcode
;
699 // many threads may call Wait(), but only one of them should call
700 // pthread_join(), so we have to keep track of this
701 wxCriticalSection m_csJoinFlag
;
702 bool m_shouldBeJoined
;
705 // this semaphore is posted by Run() and the threads Entry() is not
706 // called before it is done
707 wxSemaphore m_semRun
;
709 // this one is signaled when the thread should resume after having been
711 wxSemaphore m_semSuspend
;
714 // ----------------------------------------------------------------------------
715 // thread startup and exit functions
716 // ----------------------------------------------------------------------------
718 void *wxPthreadStart(void *ptr
)
720 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
723 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
725 wxThreadInternal
*pthread
= thread
->m_internal
;
727 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
729 // associate the thread pointer with the newly created thread so that
730 // wxThread::This() will work
731 int rc
= pthread_setspecific(gs_keySelf
, thread
);
734 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
739 // have to declare this before pthread_cleanup_push() which defines a
743 #ifdef wxHAVE_PTHREAD_CLEANUP
744 // install the cleanup handler which will be called if the thread is
746 pthread_cleanup_push(wxPthreadCleanup
, thread
);
747 #endif // wxHAVE_PTHREAD_CLEANUP
749 // wait for the semaphore to be posted from Run()
750 pthread
->m_semRun
.Wait();
752 // test whether we should run the run at all - may be it was deleted
753 // before it started to Run()?
755 wxCriticalSectionLocker
lock(thread
->m_critsect
);
757 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
758 pthread
->WasCancelled();
763 // call the main entry
764 wxLogTrace(TRACE_THREADS
,
765 _T("Thread %ld about to enter its Entry()."),
768 pthread
->m_exitcode
= thread
->Entry();
770 wxLogTrace(TRACE_THREADS
,
771 _T("Thread %ld Entry() returned %lu."),
772 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
775 wxCriticalSectionLocker
lock(thread
->m_critsect
);
777 // change the state of the thread to "exited" so that
778 // wxPthreadCleanup handler won't do anything from now (if it's
779 // called before we do pthread_cleanup_pop below)
780 pthread
->SetState(STATE_EXITED
);
784 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
785 // '}' for the '{' in push, so they must be used in the same block!
786 #ifdef wxHAVE_PTHREAD_CLEANUP
788 // under Tru64 we get a warning from macro expansion
790 #pragma message disable(declbutnotref)
793 // remove the cleanup handler without executing it
794 pthread_cleanup_pop(FALSE
);
797 #pragma message restore
799 #endif // wxHAVE_PTHREAD_CLEANUP
803 // FIXME: deleting a possibly joinable thread here???
806 return EXITCODE_CANCELLED
;
810 // terminate the thread
811 thread
->Exit(pthread
->m_exitcode
);
813 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
819 #ifdef wxHAVE_PTHREAD_CLEANUP
821 // this handler is called when the thread is cancelled
822 extern "C" void wxPthreadCleanup(void *ptr
)
824 wxThreadInternal::Cleanup((wxThread
*)ptr
);
827 void wxThreadInternal::Cleanup(wxThread
*thread
)
829 if (pthread_getspecific(gs_keySelf
) == 0) return;
831 wxCriticalSectionLocker
lock(thread
->m_critsect
);
832 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
834 // thread is already considered as finished.
839 // exit the thread gracefully
840 thread
->Exit(EXITCODE_CANCELLED
);
843 #endif // wxHAVE_PTHREAD_CLEANUP
845 // ----------------------------------------------------------------------------
847 // ----------------------------------------------------------------------------
849 wxThreadInternal::wxThreadInternal()
853 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
857 // set to true only when the thread starts waiting on m_semSuspend
860 // defaults for joinable threads
861 m_shouldBeJoined
= true;
862 m_isDetached
= false;
865 wxThreadInternal::~wxThreadInternal()
869 wxThreadError
wxThreadInternal::Run()
871 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
872 wxT("thread may only be started once after Create()") );
874 SetState(STATE_RUNNING
);
876 // wake up threads waiting for our start
879 return wxTHREAD_NO_ERROR
;
882 void wxThreadInternal::Wait()
884 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
886 // if the thread we're waiting for is waiting for the GUI mutex, we will
887 // deadlock so make sure we release it temporarily
888 if ( wxThread::IsMain() )
891 wxLogTrace(TRACE_THREADS
,
892 _T("Starting to wait for thread %ld to exit."),
895 // to avoid memory leaks we should call pthread_join(), but it must only be
896 // done once so use a critical section to serialize the code below
898 wxCriticalSectionLocker
lock(m_csJoinFlag
);
900 if ( m_shouldBeJoined
)
902 // FIXME shouldn't we set cancellation type to DISABLED here? If
903 // we're cancelled inside pthread_join(), things will almost
904 // certainly break - but if we disable the cancellation, we
906 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
908 // this is a serious problem, so use wxLogError and not
909 // wxLogDebug: it is possible to bring the system to its knees
910 // by creating too many threads and not joining them quite
912 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
915 m_shouldBeJoined
= false;
919 // reacquire GUI mutex
920 if ( wxThread::IsMain() )
924 void wxThreadInternal::Pause()
926 // the state is set from the thread which pauses us first, this function
927 // is called later so the state should have been already set
928 wxCHECK_RET( m_state
== STATE_PAUSED
,
929 wxT("thread must first be paused with wxThread::Pause().") );
931 wxLogTrace(TRACE_THREADS
,
932 _T("Thread %ld goes to sleep."), THR_ID(this));
934 // wait until the semaphore is Post()ed from Resume()
938 void wxThreadInternal::Resume()
940 wxCHECK_RET( m_state
== STATE_PAUSED
,
941 wxT("can't resume thread which is not suspended.") );
943 // the thread might be not actually paused yet - if there were no call to
944 // TestDestroy() since the last call to Pause() for example
945 if ( IsReallyPaused() )
947 wxLogTrace(TRACE_THREADS
,
948 _T("Waking up thread %ld"), THR_ID(this));
954 SetReallyPaused(false);
958 wxLogTrace(TRACE_THREADS
,
959 _T("Thread %ld is not yet really paused"), THR_ID(this));
962 SetState(STATE_RUNNING
);
965 // -----------------------------------------------------------------------------
966 // wxThread static functions
967 // -----------------------------------------------------------------------------
969 wxThread
*wxThread::This()
971 return (wxThread
*)pthread_getspecific(gs_keySelf
);
974 bool wxThread::IsMain()
976 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
979 void wxThread::Yield()
981 #ifdef HAVE_SCHED_YIELD
986 void wxThread::Sleep(unsigned long milliseconds
)
988 wxMilliSleep(milliseconds
);
991 int wxThread::GetCPUCount()
993 #if defined(__LINUX__) && wxUSE_FFILE
994 // read from proc (can't use wxTextFile here because it's a special file:
995 // it has 0 size but still can be read from)
998 wxFFile
file(_T("/proc/cpuinfo"));
999 if ( file
.IsOpened() )
1001 // slurp the whole file
1003 if ( file
.ReadAll(&s
) )
1005 // (ab)use Replace() to find the number of "processor: num" strings
1006 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1012 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1016 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1019 #elif defined(_SC_NPROCESSORS_ONLN)
1020 // this works for Solaris
1021 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1026 #endif // different ways to get number of CPUs
1032 // VMS is a 64 bit system and threads have 64 bit pointers.
1033 // FIXME: also needed for other systems????
1035 unsigned long long wxThread::GetCurrentId()
1037 return (unsigned long long)pthread_self();
1042 unsigned long wxThread::GetCurrentId()
1044 return (unsigned long)pthread_self();
1047 #endif // __VMS/!__VMS
1050 bool wxThread::SetConcurrency(size_t level
)
1052 #ifdef HAVE_THR_SETCONCURRENCY
1053 int rc
= thr_setconcurrency(level
);
1056 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1060 #else // !HAVE_THR_SETCONCURRENCY
1061 // ok only for the default value
1063 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1066 // -----------------------------------------------------------------------------
1068 // -----------------------------------------------------------------------------
1070 wxThread::wxThread(wxThreadKind kind
)
1072 // add this thread to the global list of all threads
1074 wxMutexLocker
lock(*gs_mutexAllThreads
);
1076 gs_allThreads
.Add(this);
1079 m_internal
= new wxThreadInternal();
1081 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1084 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1085 #define WXUNUSED_STACKSIZE(identifier) identifier
1087 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1090 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1092 if ( m_internal
->GetState() != STATE_NEW
)
1094 // don't recreate thread
1095 return wxTHREAD_RUNNING
;
1098 // set up the thread attribute: right now, we only set thread priority
1099 pthread_attr_t attr
;
1100 pthread_attr_init(&attr
);
1102 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1104 pthread_attr_setstacksize(&attr
, stackSize
);
1107 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1109 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1111 wxLogError(_("Cannot retrieve thread scheduling policy."));
1115 /* the pthread.h contains too many spaces. This is a work-around */
1116 # undef sched_get_priority_max
1117 #undef sched_get_priority_min
1118 #define sched_get_priority_max(_pol_) \
1119 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1120 #define sched_get_priority_min(_pol_) \
1121 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1124 int max_prio
= sched_get_priority_max(policy
),
1125 min_prio
= sched_get_priority_min(policy
),
1126 prio
= m_internal
->GetPriority();
1128 if ( min_prio
== -1 || max_prio
== -1 )
1130 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1133 else if ( max_prio
== min_prio
)
1135 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1137 // notify the programmer that this doesn't work here
1138 wxLogWarning(_("Thread priority setting is ignored."));
1140 //else: we have default priority, so don't complain
1142 // anyhow, don't do anything because priority is just ignored
1146 struct sched_param sp
;
1147 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1149 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1152 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1154 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1156 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1159 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1161 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1162 // this will make the threads created by this process really concurrent
1163 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1165 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1167 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1169 // VZ: assume that this one is always available (it's rather fundamental),
1170 // if this function is ever missing we should try to use
1171 // pthread_detach() instead (after thread creation)
1174 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1176 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1179 // never try to join detached threads
1180 m_internal
->Detach();
1182 //else: threads are created joinable by default, it's ok
1184 // create the new OS thread object
1185 int rc
= pthread_create
1187 m_internal
->GetIdPtr(),
1193 if ( pthread_attr_destroy(&attr
) != 0 )
1195 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1200 m_internal
->SetState(STATE_EXITED
);
1202 return wxTHREAD_NO_RESOURCE
;
1205 return wxTHREAD_NO_ERROR
;
1208 wxThreadError
wxThread::Run()
1210 wxCriticalSectionLocker
lock(m_critsect
);
1212 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1213 wxT("must call wxThread::Create() first") );
1215 return m_internal
->Run();
1218 // -----------------------------------------------------------------------------
1220 // -----------------------------------------------------------------------------
1222 void wxThread::SetPriority(unsigned int prio
)
1224 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1225 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1226 wxT("invalid thread priority") );
1228 wxCriticalSectionLocker
lock(m_critsect
);
1230 switch ( m_internal
->GetState() )
1233 // thread not yet started, priority will be set when it is
1234 m_internal
->SetPriority(prio
);
1239 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1240 #if defined(__LINUX__)
1241 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1242 // a priority other than 0. Instead, we use the BSD setpriority
1243 // which alllows us to set a 'nice' value between 20 to -20. Only
1244 // super user can set a value less than zero (more negative yields
1245 // higher priority). setpriority set the static priority of a
1246 // process, but this is OK since Linux is configured as a thread
1249 // FIXME this is not true for 2.6!!
1251 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1252 // to Unix priorities 20..-20
1253 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1255 wxLogError(_("Failed to set thread priority %d."), prio
);
1259 struct sched_param sparam
;
1260 sparam
.sched_priority
= prio
;
1262 if ( pthread_setschedparam(m_internal
->GetId(),
1263 SCHED_OTHER
, &sparam
) != 0 )
1265 wxLogError(_("Failed to set thread priority %d."), prio
);
1269 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1274 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1278 unsigned int wxThread::GetPriority() const
1280 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1282 return m_internal
->GetPriority();
1285 wxThreadIdType
wxThread::GetId() const
1287 return (wxThreadIdType
) m_internal
->GetId();
1290 // -----------------------------------------------------------------------------
1292 // -----------------------------------------------------------------------------
1294 wxThreadError
wxThread::Pause()
1296 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1297 _T("a thread can't pause itself") );
1299 wxCriticalSectionLocker
lock(m_critsect
);
1301 if ( m_internal
->GetState() != STATE_RUNNING
)
1303 wxLogDebug(wxT("Can't pause thread which is not running."));
1305 return wxTHREAD_NOT_RUNNING
;
1308 // just set a flag, the thread will be really paused only during the next
1309 // call to TestDestroy()
1310 m_internal
->SetState(STATE_PAUSED
);
1312 return wxTHREAD_NO_ERROR
;
1315 wxThreadError
wxThread::Resume()
1317 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1318 _T("a thread can't resume itself") );
1320 wxCriticalSectionLocker
lock(m_critsect
);
1322 wxThreadState state
= m_internal
->GetState();
1327 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1330 m_internal
->Resume();
1332 return wxTHREAD_NO_ERROR
;
1335 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1337 return wxTHREAD_NO_ERROR
;
1340 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1342 return wxTHREAD_MISC_ERROR
;
1346 // -----------------------------------------------------------------------------
1348 // -----------------------------------------------------------------------------
1350 wxThread::ExitCode
wxThread::Wait()
1352 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1353 _T("a thread can't wait for itself") );
1355 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1356 _T("can't wait for detached thread") );
1360 return m_internal
->GetExitCode();
1363 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1365 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1366 _T("a thread can't delete itself") );
1368 bool isDetached
= m_isDetached
;
1371 wxThreadState state
= m_internal
->GetState();
1373 // ask the thread to stop
1374 m_internal
->SetCancelFlag();
1381 // we need to wake up the thread so that PthreadStart() will
1382 // terminate - right now it's blocking on run semaphore in
1384 m_internal
->SignalRun();
1393 // resume the thread first
1394 m_internal
->Resume();
1401 // wait until the thread stops
1406 // return the exit code of the thread
1407 *rc
= m_internal
->GetExitCode();
1410 //else: can't wait for detached threads
1413 return wxTHREAD_NO_ERROR
;
1416 wxThreadError
wxThread::Kill()
1418 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1419 _T("a thread can't kill itself") );
1421 switch ( m_internal
->GetState() )
1425 return wxTHREAD_NOT_RUNNING
;
1428 // resume the thread first
1434 #ifdef HAVE_PTHREAD_CANCEL
1435 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1436 #endif // HAVE_PTHREAD_CANCEL
1438 wxLogError(_("Failed to terminate a thread."));
1440 return wxTHREAD_MISC_ERROR
;
1443 #ifdef HAVE_PTHREAD_CANCEL
1446 // if we use cleanup function, this will be done from
1447 // wxPthreadCleanup()
1448 #ifndef wxHAVE_PTHREAD_CLEANUP
1449 ScheduleThreadForDeletion();
1451 // don't call OnExit() here, it can only be called in the
1452 // threads context and we're in the context of another thread
1455 #endif // wxHAVE_PTHREAD_CLEANUP
1459 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1462 return wxTHREAD_NO_ERROR
;
1463 #endif // HAVE_PTHREAD_CANCEL
1467 void wxThread::Exit(ExitCode status
)
1469 wxASSERT_MSG( This() == this,
1470 _T("wxThread::Exit() can only be called in the context of the same thread") );
1474 // from the moment we call OnExit(), the main program may terminate at
1475 // any moment, so mark this thread as being already in process of being
1476 // deleted or wxThreadModule::OnExit() will try to delete it again
1477 ScheduleThreadForDeletion();
1480 // don't enter m_critsect before calling OnExit() because the user code
1481 // might deadlock if, for example, it signals a condition in OnExit() (a
1482 // common case) while the main thread calls any of functions entering
1483 // m_critsect on us (almost all of them do)
1486 // delete C++ thread object if this is a detached thread - user is
1487 // responsible for doing this for joinable ones
1490 // FIXME I'm feeling bad about it - what if another thread function is
1491 // called (in another thread context) now? It will try to access
1492 // half destroyed object which will probably result in something
1493 // very bad - but we can't protect this by a crit section unless
1494 // we make it a global object, but this would mean that we can
1495 // only call one thread function at a time :-(
1497 pthread_setspecific(gs_keySelf
, 0);
1502 m_internal
->SetState(STATE_EXITED
);
1506 // terminate the thread (pthread_exit() never returns)
1507 pthread_exit(status
);
1509 wxFAIL_MSG(_T("pthread_exit() failed"));
1512 // also test whether we were paused
1513 bool wxThread::TestDestroy()
1515 wxASSERT_MSG( This() == this,
1516 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1520 if ( m_internal
->GetState() == STATE_PAUSED
)
1522 m_internal
->SetReallyPaused(true);
1524 // leave the crit section or the other threads will stop too if they
1525 // try to call any of (seemingly harmless) IsXXX() functions while we
1529 m_internal
->Pause();
1533 // thread wasn't requested to pause, nothing to do
1537 return m_internal
->WasCancelled();
1540 wxThread::~wxThread()
1545 // check that the thread either exited or couldn't be created
1546 if ( m_internal
->GetState() != STATE_EXITED
&&
1547 m_internal
->GetState() != STATE_NEW
)
1549 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1554 #endif // __WXDEBUG__
1558 // remove this thread from the global array
1560 wxMutexLocker
lock(*gs_mutexAllThreads
);
1562 gs_allThreads
.Remove(this);
1566 // -----------------------------------------------------------------------------
1568 // -----------------------------------------------------------------------------
1570 bool wxThread::IsRunning() const
1572 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1574 return m_internal
->GetState() == STATE_RUNNING
;
1577 bool wxThread::IsAlive() const
1579 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1581 switch ( m_internal
->GetState() )
1592 bool wxThread::IsPaused() const
1594 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1596 return (m_internal
->GetState() == STATE_PAUSED
);
1599 //--------------------------------------------------------------------
1601 //--------------------------------------------------------------------
1603 class wxThreadModule
: public wxModule
1606 virtual bool OnInit();
1607 virtual void OnExit();
1610 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1613 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1615 bool wxThreadModule::OnInit()
1617 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1620 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1625 gs_tidMain
= pthread_self();
1627 gs_mutexAllThreads
= new wxMutex();
1630 gs_mutexGui
= new wxMutex();
1631 gs_mutexGui
->Lock();
1634 gs_mutexDeleteThread
= new wxMutex();
1635 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1640 void wxThreadModule::OnExit()
1642 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1644 // are there any threads left which are being deleted right now?
1645 size_t nThreadsBeingDeleted
;
1648 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1649 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1651 if ( nThreadsBeingDeleted
> 0 )
1653 wxLogTrace(TRACE_THREADS
,
1654 _T("Waiting for %lu threads to disappear"),
1655 (unsigned long)nThreadsBeingDeleted
);
1657 // have to wait until all of them disappear
1658 gs_condAllDeleted
->Wait();
1665 wxMutexLocker
lock(*gs_mutexAllThreads
);
1667 // terminate any threads left
1668 count
= gs_allThreads
.GetCount();
1671 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1672 (unsigned long)count
);
1674 } // unlock mutex before deleting the threads as they lock it in their dtor
1676 for ( size_t n
= 0u; n
< count
; n
++ )
1678 // Delete calls the destructor which removes the current entry. We
1679 // should only delete the first one each time.
1680 gs_allThreads
[0]->Delete();
1683 delete gs_mutexAllThreads
;
1686 // destroy GUI mutex
1687 gs_mutexGui
->Unlock();
1691 // and free TLD slot
1692 (void)pthread_key_delete(gs_keySelf
);
1694 delete gs_condAllDeleted
;
1695 delete gs_mutexDeleteThread
;
1698 // ----------------------------------------------------------------------------
1700 // ----------------------------------------------------------------------------
1702 static void ScheduleThreadForDeletion()
1704 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1706 gs_nThreadsBeingDeleted
++;
1708 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1709 (unsigned long)gs_nThreadsBeingDeleted
,
1710 gs_nThreadsBeingDeleted
== 1 ? _T("") : _T("s"));
1713 static void DeleteThread(wxThread
*This
)
1715 // gs_mutexDeleteThread should be unlocked before signalling the condition
1716 // or wxThreadModule::OnExit() would deadlock
1717 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1719 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1723 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1724 _T("no threads scheduled for deletion, yet we delete one?") );
1726 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1727 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1729 if ( !--gs_nThreadsBeingDeleted
)
1731 // no more threads left, signal it
1732 gs_condAllDeleted
->Signal();
1737 void wxMutexGuiEnter()
1739 gs_mutexGui
->Lock();
1742 void wxMutexGuiLeave()
1744 gs_mutexGui
->Unlock();
1748 // ----------------------------------------------------------------------------
1749 // include common implementation code
1750 // ----------------------------------------------------------------------------
1752 #include "wx/thrimpl.cpp"
1754 #endif // wxUSE_THREADS