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"
40 #include "wx/module.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 // a mutex to protect gs_allThreads
117 static wxMutex
*gs_mutexAllThreads
= NULL
;
119 // the id of the main thread
120 static pthread_t gs_tidMain
= (pthread_t
)-1;
122 // the key for the pointer to the associated wxThread object
123 static pthread_key_t gs_keySelf
;
125 // the number of threads which are being deleted - the program won't exit
126 // until there are any left
127 static size_t gs_nThreadsBeingDeleted
= 0;
129 // a mutex to protect gs_nThreadsBeingDeleted
130 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
132 // and a condition variable which will be signaled when all
133 // gs_nThreadsBeingDeleted will have been deleted
134 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
;
141 // when we wait for a thread to exit, we're blocking on a condition which the
142 // thread signals in its SignalExit() method -- but this condition can't be a
143 // member of the thread itself as a detached thread may delete itself at any
144 // moment and accessing the condition member of the thread after this would
145 // result in a disaster
147 // so instead we maintain a global list of the structs below for the threads
148 // we're interested in waiting on
150 // ============================================================================
151 // wxMutex implementation
152 // ============================================================================
154 // ----------------------------------------------------------------------------
156 // ----------------------------------------------------------------------------
158 // this is a simple wrapper around pthread_mutex_t which provides error
160 class wxMutexInternal
163 wxMutexInternal(wxMutexType mutexType
);
167 wxMutexError
TryLock();
168 wxMutexError
Unlock();
170 bool IsOk() const { return m_isOk
; }
173 pthread_mutex_t m_mutex
;
176 // wxConditionInternal uses our m_mutex
177 friend class wxConditionInternal
;
180 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
181 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
182 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
183 // in the library, otherwise we wouldn't compile this code at all)
184 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
187 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
192 case wxMUTEX_RECURSIVE
:
193 // support recursive locks like Win32, i.e. a thread can lock a
194 // mutex which it had itself already locked
196 // unfortunately initialization of recursive mutexes is non
197 // portable, so try several methods
198 #ifdef HAVE_PTHREAD_MUTEXATTR_T
200 pthread_mutexattr_t attr
;
201 pthread_mutexattr_init(&attr
);
202 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
204 err
= pthread_mutex_init(&m_mutex
, &attr
);
206 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
207 // we can use this only as initializer so we have to assign it
208 // first to a temp var - assigning directly to m_mutex wouldn't
211 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
214 #else // no recursive mutexes
216 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
220 wxFAIL_MSG( _T("unknown mutex type") );
223 case wxMUTEX_DEFAULT
:
224 err
= pthread_mutex_init(&m_mutex
, NULL
);
231 wxLogApiError( wxT("pthread_mutex_init()"), err
);
235 wxMutexInternal::~wxMutexInternal()
239 int err
= pthread_mutex_destroy(&m_mutex
);
242 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
247 wxMutexError
wxMutexInternal::Lock()
249 int err
= pthread_mutex_lock(&m_mutex
);
253 // only error checking mutexes return this value and so it's an
254 // unexpected situation -- hence use assert, not wxLogDebug
255 wxFAIL_MSG( _T("mutex deadlock prevented") );
256 return wxMUTEX_DEAD_LOCK
;
259 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
263 return wxMUTEX_NO_ERROR
;
266 wxLogApiError(_T("pthread_mutex_lock()"), err
);
269 return wxMUTEX_MISC_ERROR
;
272 wxMutexError
wxMutexInternal::TryLock()
274 int err
= pthread_mutex_trylock(&m_mutex
);
278 // not an error: mutex is already locked, but we're prepared for
283 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
287 return wxMUTEX_NO_ERROR
;
290 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
293 return wxMUTEX_MISC_ERROR
;
296 wxMutexError
wxMutexInternal::Unlock()
298 int err
= pthread_mutex_unlock(&m_mutex
);
302 // we don't own the mutex
303 return wxMUTEX_UNLOCKED
;
306 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
310 return wxMUTEX_NO_ERROR
;
313 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
316 return wxMUTEX_MISC_ERROR
;
319 // ===========================================================================
320 // wxCondition implementation
321 // ===========================================================================
323 // ---------------------------------------------------------------------------
324 // wxConditionInternal
325 // ---------------------------------------------------------------------------
327 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
328 // with a pthread_mutex_t)
329 class wxConditionInternal
332 wxConditionInternal(wxMutex
& mutex
);
333 ~wxConditionInternal();
335 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
338 wxCondError
WaitTimeout(unsigned long milliseconds
);
340 wxCondError
Signal();
341 wxCondError
Broadcast();
344 // get the POSIX mutex associated with us
345 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
348 pthread_cond_t m_cond
;
353 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
356 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
362 wxLogApiError(_T("pthread_cond_init()"), err
);
366 wxConditionInternal::~wxConditionInternal()
370 int err
= pthread_cond_destroy(&m_cond
);
373 wxLogApiError(_T("pthread_cond_destroy()"), err
);
378 wxCondError
wxConditionInternal::Wait()
380 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
383 wxLogApiError(_T("pthread_cond_wait()"), err
);
385 return wxCOND_MISC_ERROR
;
388 return wxCOND_NO_ERROR
;
391 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
393 wxLongLong curtime
= wxGetLocalTimeMillis();
394 curtime
+= milliseconds
;
395 wxLongLong temp
= curtime
/ 1000;
396 int sec
= temp
.GetLo();
398 temp
= curtime
- temp
;
399 int millis
= temp
.GetLo();
404 tspec
.tv_nsec
= millis
* 1000L * 1000L;
406 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
410 return wxCOND_TIMEOUT
;
413 return wxCOND_NO_ERROR
;
416 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
419 return wxCOND_MISC_ERROR
;
422 wxCondError
wxConditionInternal::Signal()
424 int err
= pthread_cond_signal(&m_cond
);
427 wxLogApiError(_T("pthread_cond_signal()"), err
);
429 return wxCOND_MISC_ERROR
;
432 return wxCOND_NO_ERROR
;
435 wxCondError
wxConditionInternal::Broadcast()
437 int err
= pthread_cond_broadcast(&m_cond
);
440 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
442 return wxCOND_MISC_ERROR
;
445 return wxCOND_NO_ERROR
;
448 // ===========================================================================
449 // wxSemaphore implementation
450 // ===========================================================================
452 // ---------------------------------------------------------------------------
453 // wxSemaphoreInternal
454 // ---------------------------------------------------------------------------
456 // we implement the semaphores using mutexes and conditions instead of using
457 // the sem_xxx() POSIX functions because they're not widely available and also
458 // because it's impossible to implement WaitTimeout() using them
459 class wxSemaphoreInternal
462 wxSemaphoreInternal(int initialcount
, int maxcount
);
464 bool IsOk() const { return m_isOk
; }
467 wxSemaError
TryWait();
468 wxSemaError
WaitTimeout(unsigned long milliseconds
);
482 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
486 if ( (initialcount
< 0 || maxcount
< 0) ||
487 ((maxcount
> 0) && (initialcount
> maxcount
)) )
489 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
495 m_maxcount
= (size_t)maxcount
;
496 m_count
= (size_t)initialcount
;
499 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
502 wxSemaError
wxSemaphoreInternal::Wait()
504 wxMutexLocker
locker(m_mutex
);
506 while ( m_count
== 0 )
508 wxLogTrace(TRACE_SEMA
,
509 _T("Thread %ld waiting for semaphore to become signalled"),
510 wxThread::GetCurrentId());
512 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
513 return wxSEMA_MISC_ERROR
;
515 wxLogTrace(TRACE_SEMA
,
516 _T("Thread %ld finished waiting for semaphore, count = %lu"),
517 wxThread::GetCurrentId(), (unsigned long)m_count
);
522 return wxSEMA_NO_ERROR
;
525 wxSemaError
wxSemaphoreInternal::TryWait()
527 wxMutexLocker
locker(m_mutex
);
534 return wxSEMA_NO_ERROR
;
537 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
539 wxMutexLocker
locker(m_mutex
);
541 wxLongLong startTime
= wxGetLocalTimeMillis();
543 while ( m_count
== 0 )
545 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
546 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
547 if ( remainingTime
<= 0 )
550 return wxSEMA_TIMEOUT
;
553 switch ( m_cond
.WaitTimeout(remainingTime
) )
556 return wxSEMA_TIMEOUT
;
559 return wxSEMA_MISC_ERROR
;
561 case wxCOND_NO_ERROR
:
568 return wxSEMA_NO_ERROR
;
571 wxSemaError
wxSemaphoreInternal::Post()
573 wxMutexLocker
locker(m_mutex
);
575 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
577 return wxSEMA_OVERFLOW
;
582 wxLogTrace(TRACE_SEMA
,
583 _T("Thread %ld about to signal semaphore, count = %lu"),
584 wxThread::GetCurrentId(), (unsigned long)m_count
);
586 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
590 // ===========================================================================
591 // wxThread implementation
592 // ===========================================================================
594 // the thread callback functions must have the C linkage
598 #ifdef wxHAVE_PTHREAD_CLEANUP
599 // thread exit function
600 void wxPthreadCleanup(void *ptr
);
601 #endif // wxHAVE_PTHREAD_CLEANUP
603 void *wxPthreadStart(void *ptr
);
607 // ----------------------------------------------------------------------------
609 // ----------------------------------------------------------------------------
611 class wxThreadInternal
617 // thread entry function
618 static void *PthreadStart(wxThread
*thread
);
623 // unblock the thread allowing it to run
624 void SignalRun() { m_semRun
.Post(); }
625 // ask the thread to terminate
627 // go to sleep until Resume() is called
634 int GetPriority() const { return m_prio
; }
635 void SetPriority(int prio
) { m_prio
= prio
; }
637 wxThreadState
GetState() const { return m_state
; }
638 void SetState(wxThreadState state
)
641 static const wxChar
*stateNames
[] =
649 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
650 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
651 #endif // __WXDEBUG__
656 pthread_t
GetId() const { return m_threadId
; }
657 pthread_t
*GetIdPtr() { return &m_threadId
; }
659 void SetCancelFlag() { m_cancelled
= true; }
660 bool WasCancelled() const { return m_cancelled
; }
662 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
663 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
666 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
667 bool IsReallyPaused() const { return m_isPaused
; }
669 // tell the thread that it is a detached one
672 wxCriticalSectionLocker
lock(m_csJoinFlag
);
674 m_shouldBeJoined
= false;
678 #ifdef wxHAVE_PTHREAD_CLEANUP
679 // this is used by wxPthreadCleanup() only
680 static void Cleanup(wxThread
*thread
);
681 #endif // wxHAVE_PTHREAD_CLEANUP
684 pthread_t m_threadId
; // id of the thread
685 wxThreadState m_state
; // see wxThreadState enum
686 int m_prio
; // in wxWidgets units: from 0 to 100
688 // this flag is set when the thread should terminate
691 // this flag is set when the thread is blocking on m_semSuspend
694 // the thread exit code - only used for joinable (!detached) threads and
695 // is only valid after the thread termination
696 wxThread::ExitCode m_exitcode
;
698 // many threads may call Wait(), but only one of them should call
699 // pthread_join(), so we have to keep track of this
700 wxCriticalSection m_csJoinFlag
;
701 bool m_shouldBeJoined
;
704 // this semaphore is posted by Run() and the threads Entry() is not
705 // called before it is done
706 wxSemaphore m_semRun
;
708 // this one is signaled when the thread should resume after having been
710 wxSemaphore m_semSuspend
;
713 // ----------------------------------------------------------------------------
714 // thread startup and exit functions
715 // ----------------------------------------------------------------------------
717 void *wxPthreadStart(void *ptr
)
719 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
722 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
724 wxThreadInternal
*pthread
= thread
->m_internal
;
726 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
728 // associate the thread pointer with the newly created thread so that
729 // wxThread::This() will work
730 int rc
= pthread_setspecific(gs_keySelf
, thread
);
733 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
738 // have to declare this before pthread_cleanup_push() which defines a
742 #ifdef wxHAVE_PTHREAD_CLEANUP
743 // install the cleanup handler which will be called if the thread is
745 pthread_cleanup_push(wxPthreadCleanup
, thread
);
746 #endif // wxHAVE_PTHREAD_CLEANUP
748 // wait for the semaphore to be posted from Run()
749 pthread
->m_semRun
.Wait();
751 // test whether we should run the run at all - may be it was deleted
752 // before it started to Run()?
754 wxCriticalSectionLocker
lock(thread
->m_critsect
);
756 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
757 pthread
->WasCancelled();
762 // call the main entry
763 wxLogTrace(TRACE_THREADS
,
764 _T("Thread %ld about to enter its Entry()."),
767 pthread
->m_exitcode
= thread
->Entry();
769 wxLogTrace(TRACE_THREADS
,
770 _T("Thread %ld Entry() returned %lu."),
771 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
774 wxCriticalSectionLocker
lock(thread
->m_critsect
);
776 // change the state of the thread to "exited" so that
777 // wxPthreadCleanup handler won't do anything from now (if it's
778 // called before we do pthread_cleanup_pop below)
779 pthread
->SetState(STATE_EXITED
);
783 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
784 // '}' for the '{' in push, so they must be used in the same block!
785 #ifdef wxHAVE_PTHREAD_CLEANUP
787 // under Tru64 we get a warning from macro expansion
789 #pragma message disable(declbutnotref)
792 // remove the cleanup handler without executing it
793 pthread_cleanup_pop(FALSE
);
796 #pragma message restore
798 #endif // wxHAVE_PTHREAD_CLEANUP
802 // FIXME: deleting a possibly joinable thread here???
805 return EXITCODE_CANCELLED
;
809 // terminate the thread
810 thread
->Exit(pthread
->m_exitcode
);
812 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
818 #ifdef wxHAVE_PTHREAD_CLEANUP
820 // this handler is called when the thread is cancelled
821 extern "C" void wxPthreadCleanup(void *ptr
)
823 wxThreadInternal::Cleanup((wxThread
*)ptr
);
826 void wxThreadInternal::Cleanup(wxThread
*thread
)
828 if (pthread_getspecific(gs_keySelf
) == 0) return;
830 wxCriticalSectionLocker
lock(thread
->m_critsect
);
831 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
833 // thread is already considered as finished.
838 // exit the thread gracefully
839 thread
->Exit(EXITCODE_CANCELLED
);
842 #endif // wxHAVE_PTHREAD_CLEANUP
844 // ----------------------------------------------------------------------------
846 // ----------------------------------------------------------------------------
848 wxThreadInternal::wxThreadInternal()
852 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
856 // set to true only when the thread starts waiting on m_semSuspend
859 // defaults for joinable threads
860 m_shouldBeJoined
= true;
861 m_isDetached
= false;
864 wxThreadInternal::~wxThreadInternal()
868 wxThreadError
wxThreadInternal::Run()
870 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
871 wxT("thread may only be started once after Create()") );
873 SetState(STATE_RUNNING
);
875 // wake up threads waiting for our start
878 return wxTHREAD_NO_ERROR
;
881 void wxThreadInternal::Wait()
883 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
885 // if the thread we're waiting for is waiting for the GUI mutex, we will
886 // deadlock so make sure we release it temporarily
887 if ( wxThread::IsMain() )
890 wxLogTrace(TRACE_THREADS
,
891 _T("Starting to wait for thread %ld to exit."),
894 // to avoid memory leaks we should call pthread_join(), but it must only be
895 // done once so use a critical section to serialize the code below
897 wxCriticalSectionLocker
lock(m_csJoinFlag
);
899 if ( m_shouldBeJoined
)
901 // FIXME shouldn't we set cancellation type to DISABLED here? If
902 // we're cancelled inside pthread_join(), things will almost
903 // certainly break - but if we disable the cancellation, we
905 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
907 // this is a serious problem, so use wxLogError and not
908 // wxLogDebug: it is possible to bring the system to its knees
909 // by creating too many threads and not joining them quite
911 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
914 m_shouldBeJoined
= false;
918 // reacquire GUI mutex
919 if ( wxThread::IsMain() )
923 void wxThreadInternal::Pause()
925 // the state is set from the thread which pauses us first, this function
926 // is called later so the state should have been already set
927 wxCHECK_RET( m_state
== STATE_PAUSED
,
928 wxT("thread must first be paused with wxThread::Pause().") );
930 wxLogTrace(TRACE_THREADS
,
931 _T("Thread %ld goes to sleep."), THR_ID(this));
933 // wait until the semaphore is Post()ed from Resume()
937 void wxThreadInternal::Resume()
939 wxCHECK_RET( m_state
== STATE_PAUSED
,
940 wxT("can't resume thread which is not suspended.") );
942 // the thread might be not actually paused yet - if there were no call to
943 // TestDestroy() since the last call to Pause() for example
944 if ( IsReallyPaused() )
946 wxLogTrace(TRACE_THREADS
,
947 _T("Waking up thread %ld"), THR_ID(this));
953 SetReallyPaused(false);
957 wxLogTrace(TRACE_THREADS
,
958 _T("Thread %ld is not yet really paused"), THR_ID(this));
961 SetState(STATE_RUNNING
);
964 // -----------------------------------------------------------------------------
965 // wxThread static functions
966 // -----------------------------------------------------------------------------
968 wxThread
*wxThread::This()
970 return (wxThread
*)pthread_getspecific(gs_keySelf
);
973 bool wxThread::IsMain()
975 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
978 void wxThread::Yield()
980 #ifdef HAVE_SCHED_YIELD
985 void wxThread::Sleep(unsigned long milliseconds
)
987 wxMilliSleep(milliseconds
);
990 int wxThread::GetCPUCount()
992 #if defined(__LINUX__) && wxUSE_FFILE
993 // read from proc (can't use wxTextFile here because it's a special file:
994 // it has 0 size but still can be read from)
997 wxFFile
file(_T("/proc/cpuinfo"));
998 if ( file
.IsOpened() )
1000 // slurp the whole file
1002 if ( file
.ReadAll(&s
) )
1004 // (ab)use Replace() to find the number of "processor: num" strings
1005 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1011 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1015 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1018 #elif defined(_SC_NPROCESSORS_ONLN)
1019 // this works for Solaris
1020 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1025 #endif // different ways to get number of CPUs
1031 // VMS is a 64 bit system and threads have 64 bit pointers.
1032 // FIXME: also needed for other systems????
1034 unsigned long long wxThread::GetCurrentId()
1036 return (unsigned long long)pthread_self();
1041 unsigned long wxThread::GetCurrentId()
1043 return (unsigned long)pthread_self();
1046 #endif // __VMS/!__VMS
1049 bool wxThread::SetConcurrency(size_t level
)
1051 #ifdef HAVE_THR_SETCONCURRENCY
1052 int rc
= thr_setconcurrency(level
);
1055 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1059 #else // !HAVE_THR_SETCONCURRENCY
1060 // ok only for the default value
1062 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1065 // -----------------------------------------------------------------------------
1067 // -----------------------------------------------------------------------------
1069 wxThread::wxThread(wxThreadKind kind
)
1071 // add this thread to the global list of all threads
1073 wxMutexLocker
lock(*gs_mutexAllThreads
);
1075 gs_allThreads
.Add(this);
1078 m_internal
= new wxThreadInternal();
1080 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1083 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1084 #define WXUNUSED_STACKSIZE(identifier) identifier
1086 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1089 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1091 if ( m_internal
->GetState() != STATE_NEW
)
1093 // don't recreate thread
1094 return wxTHREAD_RUNNING
;
1097 // set up the thread attribute: right now, we only set thread priority
1098 pthread_attr_t attr
;
1099 pthread_attr_init(&attr
);
1101 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1103 pthread_attr_setstacksize(&attr
, stackSize
);
1106 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1108 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1110 wxLogError(_("Cannot retrieve thread scheduling policy."));
1114 /* the pthread.h contains too many spaces. This is a work-around */
1115 # undef sched_get_priority_max
1116 #undef sched_get_priority_min
1117 #define sched_get_priority_max(_pol_) \
1118 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1119 #define sched_get_priority_min(_pol_) \
1120 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1123 int max_prio
= sched_get_priority_max(policy
),
1124 min_prio
= sched_get_priority_min(policy
),
1125 prio
= m_internal
->GetPriority();
1127 if ( min_prio
== -1 || max_prio
== -1 )
1129 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1132 else if ( max_prio
== min_prio
)
1134 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1136 // notify the programmer that this doesn't work here
1137 wxLogWarning(_("Thread priority setting is ignored."));
1139 //else: we have default priority, so don't complain
1141 // anyhow, don't do anything because priority is just ignored
1145 struct sched_param sp
;
1146 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1148 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1151 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1153 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1155 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1158 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1160 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1161 // this will make the threads created by this process really concurrent
1162 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1164 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1166 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1168 // VZ: assume that this one is always available (it's rather fundamental),
1169 // if this function is ever missing we should try to use
1170 // pthread_detach() instead (after thread creation)
1173 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1175 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1178 // never try to join detached threads
1179 m_internal
->Detach();
1181 //else: threads are created joinable by default, it's ok
1183 // create the new OS thread object
1184 int rc
= pthread_create
1186 m_internal
->GetIdPtr(),
1192 if ( pthread_attr_destroy(&attr
) != 0 )
1194 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1199 m_internal
->SetState(STATE_EXITED
);
1201 return wxTHREAD_NO_RESOURCE
;
1204 return wxTHREAD_NO_ERROR
;
1207 wxThreadError
wxThread::Run()
1209 wxCriticalSectionLocker
lock(m_critsect
);
1211 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1212 wxT("must call wxThread::Create() first") );
1214 return m_internal
->Run();
1217 // -----------------------------------------------------------------------------
1219 // -----------------------------------------------------------------------------
1221 void wxThread::SetPriority(unsigned int prio
)
1223 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1224 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1225 wxT("invalid thread priority") );
1227 wxCriticalSectionLocker
lock(m_critsect
);
1229 switch ( m_internal
->GetState() )
1232 // thread not yet started, priority will be set when it is
1233 m_internal
->SetPriority(prio
);
1238 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1239 #if defined(__LINUX__)
1240 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1241 // a priority other than 0. Instead, we use the BSD setpriority
1242 // which alllows us to set a 'nice' value between 20 to -20. Only
1243 // super user can set a value less than zero (more negative yields
1244 // higher priority). setpriority set the static priority of a
1245 // process, but this is OK since Linux is configured as a thread
1248 // FIXME this is not true for 2.6!!
1250 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1251 // to Unix priorities 20..-20
1252 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1254 wxLogError(_("Failed to set thread priority %d."), prio
);
1258 struct sched_param sparam
;
1259 sparam
.sched_priority
= prio
;
1261 if ( pthread_setschedparam(m_internal
->GetId(),
1262 SCHED_OTHER
, &sparam
) != 0 )
1264 wxLogError(_("Failed to set thread priority %d."), prio
);
1268 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1273 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1277 unsigned int wxThread::GetPriority() const
1279 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1281 return m_internal
->GetPriority();
1284 wxThreadIdType
wxThread::GetId() const
1286 return (wxThreadIdType
) m_internal
->GetId();
1289 // -----------------------------------------------------------------------------
1291 // -----------------------------------------------------------------------------
1293 wxThreadError
wxThread::Pause()
1295 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1296 _T("a thread can't pause itself") );
1298 wxCriticalSectionLocker
lock(m_critsect
);
1300 if ( m_internal
->GetState() != STATE_RUNNING
)
1302 wxLogDebug(wxT("Can't pause thread which is not running."));
1304 return wxTHREAD_NOT_RUNNING
;
1307 // just set a flag, the thread will be really paused only during the next
1308 // call to TestDestroy()
1309 m_internal
->SetState(STATE_PAUSED
);
1311 return wxTHREAD_NO_ERROR
;
1314 wxThreadError
wxThread::Resume()
1316 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1317 _T("a thread can't resume itself") );
1319 wxCriticalSectionLocker
lock(m_critsect
);
1321 wxThreadState state
= m_internal
->GetState();
1326 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1329 m_internal
->Resume();
1331 return wxTHREAD_NO_ERROR
;
1334 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1336 return wxTHREAD_NO_ERROR
;
1339 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1341 return wxTHREAD_MISC_ERROR
;
1345 // -----------------------------------------------------------------------------
1347 // -----------------------------------------------------------------------------
1349 wxThread::ExitCode
wxThread::Wait()
1351 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1352 _T("a thread can't wait for itself") );
1354 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1355 _T("can't wait for detached thread") );
1359 return m_internal
->GetExitCode();
1362 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1364 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1365 _T("a thread can't delete itself") );
1367 bool isDetached
= m_isDetached
;
1370 wxThreadState state
= m_internal
->GetState();
1372 // ask the thread to stop
1373 m_internal
->SetCancelFlag();
1380 // we need to wake up the thread so that PthreadStart() will
1381 // terminate - right now it's blocking on run semaphore in
1383 m_internal
->SignalRun();
1392 // resume the thread first
1393 m_internal
->Resume();
1400 // wait until the thread stops
1405 // return the exit code of the thread
1406 *rc
= m_internal
->GetExitCode();
1409 //else: can't wait for detached threads
1412 return wxTHREAD_NO_ERROR
;
1415 wxThreadError
wxThread::Kill()
1417 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1418 _T("a thread can't kill itself") );
1420 switch ( m_internal
->GetState() )
1424 return wxTHREAD_NOT_RUNNING
;
1427 // resume the thread first
1433 #ifdef HAVE_PTHREAD_CANCEL
1434 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1435 #endif // HAVE_PTHREAD_CANCEL
1437 wxLogError(_("Failed to terminate a thread."));
1439 return wxTHREAD_MISC_ERROR
;
1442 #ifdef HAVE_PTHREAD_CANCEL
1445 // if we use cleanup function, this will be done from
1446 // wxPthreadCleanup()
1447 #ifndef wxHAVE_PTHREAD_CLEANUP
1448 ScheduleThreadForDeletion();
1450 // don't call OnExit() here, it can only be called in the
1451 // threads context and we're in the context of another thread
1454 #endif // wxHAVE_PTHREAD_CLEANUP
1458 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1461 return wxTHREAD_NO_ERROR
;
1462 #endif // HAVE_PTHREAD_CANCEL
1466 void wxThread::Exit(ExitCode status
)
1468 wxASSERT_MSG( This() == this,
1469 _T("wxThread::Exit() can only be called in the context of the same thread") );
1473 // from the moment we call OnExit(), the main program may terminate at
1474 // any moment, so mark this thread as being already in process of being
1475 // deleted or wxThreadModule::OnExit() will try to delete it again
1476 ScheduleThreadForDeletion();
1479 // don't enter m_critsect before calling OnExit() because the user code
1480 // might deadlock if, for example, it signals a condition in OnExit() (a
1481 // common case) while the main thread calls any of functions entering
1482 // m_critsect on us (almost all of them do)
1485 // delete C++ thread object if this is a detached thread - user is
1486 // responsible for doing this for joinable ones
1489 // FIXME I'm feeling bad about it - what if another thread function is
1490 // called (in another thread context) now? It will try to access
1491 // half destroyed object which will probably result in something
1492 // very bad - but we can't protect this by a crit section unless
1493 // we make it a global object, but this would mean that we can
1494 // only call one thread function at a time :-(
1496 pthread_setspecific(gs_keySelf
, 0);
1501 m_internal
->SetState(STATE_EXITED
);
1505 // terminate the thread (pthread_exit() never returns)
1506 pthread_exit(status
);
1508 wxFAIL_MSG(_T("pthread_exit() failed"));
1511 // also test whether we were paused
1512 bool wxThread::TestDestroy()
1514 wxASSERT_MSG( This() == this,
1515 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1519 if ( m_internal
->GetState() == STATE_PAUSED
)
1521 m_internal
->SetReallyPaused(true);
1523 // leave the crit section or the other threads will stop too if they
1524 // try to call any of (seemingly harmless) IsXXX() functions while we
1528 m_internal
->Pause();
1532 // thread wasn't requested to pause, nothing to do
1536 return m_internal
->WasCancelled();
1539 wxThread::~wxThread()
1544 // check that the thread either exited or couldn't be created
1545 if ( m_internal
->GetState() != STATE_EXITED
&&
1546 m_internal
->GetState() != STATE_NEW
)
1548 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1553 #endif // __WXDEBUG__
1557 // remove this thread from the global array
1559 wxMutexLocker
lock(*gs_mutexAllThreads
);
1561 gs_allThreads
.Remove(this);
1565 // -----------------------------------------------------------------------------
1567 // -----------------------------------------------------------------------------
1569 bool wxThread::IsRunning() const
1571 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1573 return m_internal
->GetState() == STATE_RUNNING
;
1576 bool wxThread::IsAlive() const
1578 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1580 switch ( m_internal
->GetState() )
1591 bool wxThread::IsPaused() const
1593 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1595 return (m_internal
->GetState() == STATE_PAUSED
);
1598 //--------------------------------------------------------------------
1600 //--------------------------------------------------------------------
1602 class wxThreadModule
: public wxModule
1605 virtual bool OnInit();
1606 virtual void OnExit();
1609 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1612 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1614 bool wxThreadModule::OnInit()
1616 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1619 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1624 gs_tidMain
= pthread_self();
1626 gs_mutexAllThreads
= new wxMutex();
1628 gs_mutexGui
= new wxMutex();
1629 gs_mutexGui
->Lock();
1631 gs_mutexDeleteThread
= new wxMutex();
1632 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1637 void wxThreadModule::OnExit()
1639 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1641 // are there any threads left which are being deleted right now?
1642 size_t nThreadsBeingDeleted
;
1645 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1646 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1648 if ( nThreadsBeingDeleted
> 0 )
1650 wxLogTrace(TRACE_THREADS
,
1651 _T("Waiting for %lu threads to disappear"),
1652 (unsigned long)nThreadsBeingDeleted
);
1654 // have to wait until all of them disappear
1655 gs_condAllDeleted
->Wait();
1662 wxMutexLocker
lock(*gs_mutexAllThreads
);
1664 // terminate any threads left
1665 count
= gs_allThreads
.GetCount();
1668 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1669 (unsigned long)count
);
1671 } // unlock mutex before deleting the threads as they lock it in their dtor
1673 for ( size_t n
= 0u; n
< count
; n
++ )
1675 // Delete calls the destructor which removes the current entry. We
1676 // should only delete the first one each time.
1677 gs_allThreads
[0]->Delete();
1680 delete gs_mutexAllThreads
;
1682 // destroy GUI mutex
1683 gs_mutexGui
->Unlock();
1686 // and free TLD slot
1687 (void)pthread_key_delete(gs_keySelf
);
1689 delete gs_condAllDeleted
;
1690 delete gs_mutexDeleteThread
;
1693 // ----------------------------------------------------------------------------
1695 // ----------------------------------------------------------------------------
1697 static void ScheduleThreadForDeletion()
1699 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1701 gs_nThreadsBeingDeleted
++;
1703 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1704 (unsigned long)gs_nThreadsBeingDeleted
,
1705 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1708 static void DeleteThread(wxThread
*This
)
1710 // gs_mutexDeleteThread should be unlocked before signalling the condition
1711 // or wxThreadModule::OnExit() would deadlock
1712 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1714 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1718 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1719 _T("no threads scheduled for deletion, yet we delete one?") );
1721 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1722 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1724 if ( !--gs_nThreadsBeingDeleted
)
1726 // no more threads left, signal it
1727 gs_condAllDeleted
->Signal();
1731 void wxMutexGuiEnter()
1733 gs_mutexGui
->Lock();
1736 void wxMutexGuiLeave()
1738 gs_mutexGui
->Unlock();
1741 // ----------------------------------------------------------------------------
1742 // include common implementation code
1743 // ----------------------------------------------------------------------------
1745 #include "wx/thrimpl.cpp"
1747 #endif // wxUSE_THREADS