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 // ----------------------------------------------------------------------------
25 #pragma implementation "thread.h"
32 #include "wx/thread.h"
33 #include "wx/module.h"
37 #include "wx/dynarray.h"
49 #ifdef HAVE_THR_SETCONCURRENCY
53 // we use wxFFile under Linux in GetCPUCount()
58 // ----------------------------------------------------------------------------
60 // ----------------------------------------------------------------------------
62 // the possible states of the thread and transitions from them
65 STATE_NEW
, // didn't start execution yet (=> RUNNING)
66 STATE_RUNNING
, // running (=> PAUSED or EXITED)
67 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
68 STATE_EXITED
// thread doesn't exist any more
71 // the exit value of a thread which has been cancelled
72 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
74 // trace mask for wxThread operations
75 #define TRACE_THREADS _T("thread")
77 // you can get additional debugging messages for the semaphore operations
78 #define TRACE_SEMA _T("semaphore")
80 // ----------------------------------------------------------------------------
82 // ----------------------------------------------------------------------------
84 static void ScheduleThreadForDeletion();
85 static void DeleteThread(wxThread
*This
);
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 // an (non owning) array of pointers to threads
92 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
94 // an entry for a thread we can wait for
96 // -----------------------------------------------------------------------------
98 // -----------------------------------------------------------------------------
100 // we keep the list of all threads created by the application to be able to
101 // terminate them on exit if there are some left - otherwise the process would
103 static wxArrayThread gs_allThreads
;
105 // the id of the main thread
106 static pthread_t gs_tidMain
;
108 // the key for the pointer to the associated wxThread object
109 static pthread_key_t gs_keySelf
;
111 // the number of threads which are being deleted - the program won't exit
112 // until there are any left
113 static size_t gs_nThreadsBeingDeleted
= 0;
115 // a mutex to protect gs_nThreadsBeingDeleted
116 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
118 // and a condition variable which will be signaled when all
119 // gs_nThreadsBeingDeleted will have been deleted
120 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
123 // this mutex must be acquired before any call to a GUI function
124 static wxMutex
*gs_mutexGui
;
127 // when we wait for a thread to exit, we're blocking on a condition which the
128 // thread signals in its SignalExit() method -- but this condition can't be a
129 // member of the thread itself as a detached thread may delete itself at any
130 // moment and accessing the condition member of the thread after this would
131 // result in a disaster
133 // so instead we maintain a global list of the structs below for the threads
134 // we're interested in waiting on
136 // ============================================================================
137 // wxMutex implementation
138 // ============================================================================
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 // this is a simple wrapper around pthread_mutex_t which provides error
146 class wxMutexInternal
149 wxMutexInternal(wxMutexType mutexType
);
153 wxMutexError
TryLock();
154 wxMutexError
Unlock();
156 bool IsOk() const { return m_isOk
; }
159 pthread_mutex_t m_mutex
;
162 // wxConditionInternal uses our m_mutex
163 friend class wxConditionInternal
;
166 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
171 case wxMUTEX_RECURSIVE
:
172 // support recursive locks like Win32, i.e. a thread can lock a
173 // mutex which it had itself already locked
175 // unfortunately initialization of recursive mutexes is non
176 // portable, so try several methods
177 #ifdef HAVE_PTHREAD_MUTEXATTR_T
179 pthread_mutexattr_t attr
;
180 pthread_mutexattr_init(&attr
);
181 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
183 err
= pthread_mutex_init(&m_mutex
, &attr
);
185 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
186 // we can use this only as initializer so we have to assign it
187 // first to a temp var - assigning directly to m_mutex wouldn't
190 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
193 #else // no recursive mutexes
195 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
199 wxFAIL_MSG( _T("unknown mutex type") );
202 case wxMUTEX_DEFAULT
:
203 err
= pthread_mutex_init(&m_mutex
, NULL
);
210 wxLogApiError("pthread_mutex_init()", err
);
214 wxMutexInternal::~wxMutexInternal()
218 int err
= pthread_mutex_destroy(&m_mutex
);
221 wxLogApiError("pthread_mutex_destroy()", err
);
226 wxMutexError
wxMutexInternal::Lock()
228 int err
= pthread_mutex_lock(&m_mutex
);
232 // only error checking mutexes return this value and so it's an
233 // unexpected situation -- hence use assert, not wxLogDebug
234 wxFAIL_MSG( _T("mutex deadlock prevented") );
235 return wxMUTEX_DEAD_LOCK
;
238 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
242 return wxMUTEX_NO_ERROR
;
245 wxLogApiError(_T("pthread_mutex_lock()"), err
);
248 return wxMUTEX_MISC_ERROR
;
251 wxMutexError
wxMutexInternal::TryLock()
253 int err
= pthread_mutex_trylock(&m_mutex
);
257 // not an error: mutex is already locked, but we're prepared for
262 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
266 return wxMUTEX_NO_ERROR
;
269 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
272 return wxMUTEX_MISC_ERROR
;
275 wxMutexError
wxMutexInternal::Unlock()
277 int err
= pthread_mutex_unlock(&m_mutex
);
281 // we don't own the mutex
282 return wxMUTEX_UNLOCKED
;
285 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
289 return wxMUTEX_NO_ERROR
;
292 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
295 return wxMUTEX_MISC_ERROR
;
298 // ===========================================================================
299 // wxCondition implementation
300 // ===========================================================================
302 // ---------------------------------------------------------------------------
303 // wxConditionInternal
304 // ---------------------------------------------------------------------------
306 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
307 // with a pthread_mutex_t)
308 class wxConditionInternal
311 wxConditionInternal(wxMutex
& mutex
);
312 ~wxConditionInternal();
314 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
317 wxCondError
WaitTimeout(unsigned long milliseconds
);
319 wxCondError
Signal();
320 wxCondError
Broadcast();
323 // get the POSIX mutex associated with us
324 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
327 pthread_cond_t m_cond
;
332 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
335 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
341 wxLogApiError(_T("pthread_cond_init()"), err
);
345 wxConditionInternal::~wxConditionInternal()
349 int err
= pthread_cond_destroy(&m_cond
);
352 wxLogApiError(_T("pthread_cond_destroy()"), err
);
357 wxCondError
wxConditionInternal::Wait()
359 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
362 wxLogApiError(_T("pthread_cond_wait()"), err
);
364 return wxCOND_MISC_ERROR
;
367 return wxCOND_NO_ERROR
;
370 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
372 wxLongLong curtime
= wxGetLocalTimeMillis();
373 curtime
+= milliseconds
;
374 wxLongLong temp
= curtime
/ 1000;
375 int sec
= temp
.GetLo();
377 temp
= curtime
- temp
;
378 int millis
= temp
.GetLo();
383 tspec
.tv_nsec
= millis
* 1000L * 1000L;
385 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
389 return wxCOND_TIMEOUT
;
392 return wxCOND_NO_ERROR
;
395 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
398 return wxCOND_MISC_ERROR
;
401 wxCondError
wxConditionInternal::Signal()
403 int err
= pthread_cond_signal(&m_cond
);
406 wxLogApiError(_T("pthread_cond_signal()"), err
);
408 return wxCOND_MISC_ERROR
;
411 return wxCOND_NO_ERROR
;
414 wxCondError
wxConditionInternal::Broadcast()
416 int err
= pthread_cond_broadcast(&m_cond
);
419 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
421 return wxCOND_MISC_ERROR
;
424 return wxCOND_NO_ERROR
;
427 // ===========================================================================
428 // wxSemaphore implementation
429 // ===========================================================================
431 // ---------------------------------------------------------------------------
432 // wxSemaphoreInternal
433 // ---------------------------------------------------------------------------
435 // we implement the semaphores using mutexes and conditions instead of using
436 // the sem_xxx() POSIX functions because they're not widely available and also
437 // because it's impossible to implement WaitTimeout() using them
438 class wxSemaphoreInternal
441 wxSemaphoreInternal(int initialcount
, int maxcount
);
443 bool IsOk() const { return m_isOk
; }
446 wxSemaError
TryWait();
447 wxSemaError
WaitTimeout(unsigned long milliseconds
);
461 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
465 if ( (initialcount
< 0 || maxcount
< 0) ||
466 ((maxcount
> 0) && (initialcount
> maxcount
)) )
468 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
474 m_maxcount
= (size_t)maxcount
;
475 m_count
= (size_t)initialcount
;
478 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
481 wxSemaError
wxSemaphoreInternal::Wait()
483 wxMutexLocker
locker(m_mutex
);
485 while ( m_count
== 0 )
487 wxLogTrace(TRACE_SEMA
,
488 "Thread %ld waiting for semaphore to become signalled",
489 wxThread::GetCurrentId());
491 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
492 return wxSEMA_MISC_ERROR
;
494 wxLogTrace(TRACE_SEMA
,
495 "Thread %ld finished waiting for semaphore, count = %u",
496 wxThread::GetCurrentId(), m_count
);
501 return wxSEMA_NO_ERROR
;
504 wxSemaError
wxSemaphoreInternal::TryWait()
506 wxMutexLocker
locker(m_mutex
);
513 return wxSEMA_NO_ERROR
;
516 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
518 wxMutexLocker
locker(m_mutex
);
520 wxLongLong startTime
= wxGetLocalTimeMillis();
522 while ( m_count
== 0 )
524 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
525 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
526 if ( remainingTime
<= 0 )
529 return wxSEMA_TIMEOUT
;
532 if ( m_cond
.Wait(remainingTime
) != wxCOND_NO_ERROR
)
533 return wxSEMA_MISC_ERROR
;
538 return wxSEMA_NO_ERROR
;
541 wxSemaError
wxSemaphoreInternal::Post()
543 wxMutexLocker
locker(m_mutex
);
545 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
547 return wxSEMA_OVERFLOW
;
552 wxLogTrace(TRACE_SEMA
,
553 "Thread %ld about to signal semaphore, count = %u",
554 wxThread::GetCurrentId(), m_count
);
556 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
560 // ===========================================================================
561 // wxThread implementation
562 // ===========================================================================
564 // the thread callback functions must have the C linkage
568 #if HAVE_THREAD_CLEANUP_FUNCTIONS
569 // thread exit function
570 void wxPthreadCleanup(void *ptr
);
571 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
573 void *wxPthreadStart(void *ptr
);
577 // ----------------------------------------------------------------------------
579 // ----------------------------------------------------------------------------
581 class wxThreadInternal
587 // thread entry function
588 static void *PthreadStart(wxThread
*thread
);
593 // unblock the thread allowing it to run
594 void SignalRun() { m_semRun
.Post(); }
595 // ask the thread to terminate
597 // go to sleep until Resume() is called
604 int GetPriority() const { return m_prio
; }
605 void SetPriority(int prio
) { m_prio
= prio
; }
607 wxThreadState
GetState() const { return m_state
; }
608 void SetState(wxThreadState state
)
611 static const wxChar
*stateNames
[] =
619 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
620 GetId(), stateNames
[m_state
], stateNames
[state
]);
621 #endif // __WXDEBUG__
626 pthread_t
GetId() const { return m_threadId
; }
627 pthread_t
*GetIdPtr() { return &m_threadId
; }
629 void SetCancelFlag() { m_cancelled
= TRUE
; }
630 bool WasCancelled() const { return m_cancelled
; }
632 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
633 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
636 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
637 bool IsReallyPaused() const { return m_isPaused
; }
639 // tell the thread that it is a detached one
642 wxCriticalSectionLocker
lock(m_csJoinFlag
);
644 m_shouldBeJoined
= FALSE
;
648 #if HAVE_THREAD_CLEANUP_FUNCTIONS
649 // this is used by wxPthreadCleanup() only
650 static void Cleanup(wxThread
*thread
);
651 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
654 pthread_t m_threadId
; // id of the thread
655 wxThreadState m_state
; // see wxThreadState enum
656 int m_prio
; // in wxWindows units: from 0 to 100
658 // this flag is set when the thread should terminate
661 // this flag is set when the thread is blocking on m_semSuspend
664 // the thread exit code - only used for joinable (!detached) threads and
665 // is only valid after the thread termination
666 wxThread::ExitCode m_exitcode
;
668 // many threads may call Wait(), but only one of them should call
669 // pthread_join(), so we have to keep track of this
670 wxCriticalSection m_csJoinFlag
;
671 bool m_shouldBeJoined
;
674 // this semaphore is posted by Run() and the threads Entry() is not
675 // called before it is done
676 wxSemaphore m_semRun
;
678 // this one is signaled when the thread should resume after having been
680 wxSemaphore m_semSuspend
;
683 // ----------------------------------------------------------------------------
684 // thread startup and exit functions
685 // ----------------------------------------------------------------------------
687 void *wxPthreadStart(void *ptr
)
689 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
692 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
694 wxThreadInternal
*pthread
= thread
->m_internal
;
696 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), pthread
->GetId());
698 // associate the thread pointer with the newly created thread so that
699 // wxThread::This() will work
700 int rc
= pthread_setspecific(gs_keySelf
, thread
);
703 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
708 // have to declare this before pthread_cleanup_push() which defines a
712 #if HAVE_THREAD_CLEANUP_FUNCTIONS
713 // install the cleanup handler which will be called if the thread is
715 pthread_cleanup_push(wxPthreadCleanup
, thread
);
716 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
718 // wait for the semaphore to be posted from Run()
719 pthread
->m_semRun
.Wait();
721 // test whether we should run the run at all - may be it was deleted
722 // before it started to Run()?
724 wxCriticalSectionLocker
lock(thread
->m_critsect
);
726 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
727 pthread
->WasCancelled();
732 // call the main entry
733 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to enter its Entry()."),
736 pthread
->m_exitcode
= thread
->Entry();
738 wxLogTrace(TRACE_THREADS
, _T("Thread %ld Entry() returned %lu."),
739 pthread
->GetId(), (unsigned long)pthread
->m_exitcode
);
742 wxCriticalSectionLocker
lock(thread
->m_critsect
);
744 // change the state of the thread to "exited" so that
745 // wxPthreadCleanup handler won't do anything from now (if it's
746 // called before we do pthread_cleanup_pop below)
747 pthread
->SetState(STATE_EXITED
);
751 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
752 // contains the matching '}' for the '{' in push, so they must be used
753 // in the same block!
754 #if HAVE_THREAD_CLEANUP_FUNCTIONS
755 // remove the cleanup handler without executing it
756 pthread_cleanup_pop(FALSE
);
757 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
761 // FIXME: deleting a possibly joinable thread here???
764 return EXITCODE_CANCELLED
;
768 // terminate the thread
769 thread
->Exit(pthread
->m_exitcode
);
771 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
777 #if HAVE_THREAD_CLEANUP_FUNCTIONS
779 // this handler is called when the thread is cancelled
780 extern "C" void wxPthreadCleanup(void *ptr
)
782 wxThreadInternal::Cleanup((wxThread
*)ptr
);
785 void wxThreadInternal::Cleanup(wxThread
*thread
)
788 wxCriticalSectionLocker
lock(thread
->m_critsect
);
789 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
791 // thread is already considered as finished.
796 // exit the thread gracefully
797 thread
->Exit(EXITCODE_CANCELLED
);
800 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
802 // ----------------------------------------------------------------------------
804 // ----------------------------------------------------------------------------
806 wxThreadInternal::wxThreadInternal()
810 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
814 // set to TRUE only when the thread starts waiting on m_semSuspend
817 // defaults for joinable threads
818 m_shouldBeJoined
= TRUE
;
819 m_isDetached
= FALSE
;
822 wxThreadInternal::~wxThreadInternal()
826 wxThreadError
wxThreadInternal::Run()
828 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
829 wxT("thread may only be started once after Create()") );
831 SetState(STATE_RUNNING
);
833 // wake up threads waiting for our start
836 return wxTHREAD_NO_ERROR
;
839 void wxThreadInternal::Wait()
841 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
843 // if the thread we're waiting for is waiting for the GUI mutex, we will
844 // deadlock so make sure we release it temporarily
845 if ( wxThread::IsMain() )
848 wxLogTrace(TRACE_THREADS
,
849 _T("Starting to wait for thread %ld to exit."), GetId());
851 // to avoid memory leaks we should call pthread_join(), but it must only be
852 // done once so use a critical section to serialize the code below
854 wxCriticalSectionLocker
lock(m_csJoinFlag
);
856 if ( m_shouldBeJoined
)
858 // FIXME shouldn't we set cancellation type to DISABLED here? If
859 // we're cancelled inside pthread_join(), things will almost
860 // certainly break - but if we disable the cancellation, we
862 if ( pthread_join((pthread_t
)GetId(), &m_exitcode
) != 0 )
864 // this is a serious problem, so use wxLogError and not
865 // wxLogDebug: it is possible to bring the system to its knees
866 // by creating too many threads and not joining them quite
868 wxLogError(_("Failed to join a thread, potential memory leak "
869 "detected - please restart the program"));
872 m_shouldBeJoined
= FALSE
;
876 // reacquire GUI mutex
877 if ( wxThread::IsMain() )
881 void wxThreadInternal::Pause()
883 // the state is set from the thread which pauses us first, this function
884 // is called later so the state should have been already set
885 wxCHECK_RET( m_state
== STATE_PAUSED
,
886 wxT("thread must first be paused with wxThread::Pause().") );
888 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
890 // wait until the semaphore is Post()ed from Resume()
894 void wxThreadInternal::Resume()
896 wxCHECK_RET( m_state
== STATE_PAUSED
,
897 wxT("can't resume thread which is not suspended.") );
899 // the thread might be not actually paused yet - if there were no call to
900 // TestDestroy() since the last call to Pause() for example
901 if ( IsReallyPaused() )
903 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
909 SetReallyPaused(FALSE
);
913 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
917 SetState(STATE_RUNNING
);
920 // -----------------------------------------------------------------------------
921 // wxThread static functions
922 // -----------------------------------------------------------------------------
924 wxThread
*wxThread::This()
926 return (wxThread
*)pthread_getspecific(gs_keySelf
);
929 bool wxThread::IsMain()
931 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
934 void wxThread::Yield()
936 #ifdef HAVE_SCHED_YIELD
941 void wxThread::Sleep(unsigned long milliseconds
)
943 wxUsleep(milliseconds
);
946 int wxThread::GetCPUCount()
948 #if defined(__LINUX__) && wxUSE_FFILE
949 // read from proc (can't use wxTextFile here because it's a special file:
950 // it has 0 size but still can be read from)
953 wxFFile
file(_T("/proc/cpuinfo"));
954 if ( file
.IsOpened() )
956 // slurp the whole file
958 if ( file
.ReadAll(&s
) )
960 // (ab)use Replace() to find the number of "processor" strings
961 size_t count
= s
.Replace(_T("processor"), _T(""));
967 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
971 wxLogDebug(_T("failed to read /proc/cpuinfo"));
974 #elif defined(_SC_NPROCESSORS_ONLN)
975 // this works for Solaris
976 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
981 #endif // different ways to get number of CPUs
988 // VMS is a 64 bit system and threads have 64 bit pointers.
989 // ??? also needed for other systems????
990 unsigned long long wxThread::GetCurrentId()
992 return (unsigned long long)pthread_self();
994 unsigned long wxThread::GetCurrentId()
996 return (unsigned long)pthread_self();
1000 bool wxThread::SetConcurrency(size_t level
)
1002 #ifdef HAVE_THR_SETCONCURRENCY
1003 int rc
= thr_setconcurrency(level
);
1006 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1010 #else // !HAVE_THR_SETCONCURRENCY
1011 // ok only for the default value
1013 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1016 // -----------------------------------------------------------------------------
1018 // -----------------------------------------------------------------------------
1020 wxThread::wxThread(wxThreadKind kind
)
1022 // add this thread to the global list of all threads
1023 gs_allThreads
.Add(this);
1025 m_internal
= new wxThreadInternal();
1027 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1030 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1032 if ( m_internal
->GetState() != STATE_NEW
)
1034 // don't recreate thread
1035 return wxTHREAD_RUNNING
;
1038 // set up the thread attribute: right now, we only set thread priority
1039 pthread_attr_t attr
;
1040 pthread_attr_init(&attr
);
1042 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1044 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1046 wxLogError(_("Cannot retrieve thread scheduling policy."));
1050 /* the pthread.h contains too many spaces. This is a work-around */
1051 # undef sched_get_priority_max
1052 #undef sched_get_priority_min
1053 #define sched_get_priority_max(_pol_) \
1054 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1055 #define sched_get_priority_min(_pol_) \
1056 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1059 int max_prio
= sched_get_priority_max(policy
),
1060 min_prio
= sched_get_priority_min(policy
),
1061 prio
= m_internal
->GetPriority();
1063 if ( min_prio
== -1 || max_prio
== -1 )
1065 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1068 else if ( max_prio
== min_prio
)
1070 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1072 // notify the programmer that this doesn't work here
1073 wxLogWarning(_("Thread priority setting is ignored."));
1075 //else: we have default priority, so don't complain
1077 // anyhow, don't do anything because priority is just ignored
1081 struct sched_param sp
;
1082 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1084 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1087 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1089 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1091 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1094 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1096 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1097 // this will make the threads created by this process really concurrent
1098 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1100 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1102 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1104 // VZ: assume that this one is always available (it's rather fundamental),
1105 // if this function is ever missing we should try to use
1106 // pthread_detach() instead (after thread creation)
1109 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1111 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1114 // never try to join detached threads
1115 m_internal
->Detach();
1117 //else: threads are created joinable by default, it's ok
1119 // create the new OS thread object
1120 int rc
= pthread_create
1122 m_internal
->GetIdPtr(),
1128 if ( pthread_attr_destroy(&attr
) != 0 )
1130 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1135 m_internal
->SetState(STATE_EXITED
);
1137 return wxTHREAD_NO_RESOURCE
;
1140 return wxTHREAD_NO_ERROR
;
1143 wxThreadError
wxThread::Run()
1145 wxCriticalSectionLocker
lock(m_critsect
);
1147 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1148 wxT("must call wxThread::Create() first") );
1150 return m_internal
->Run();
1153 // -----------------------------------------------------------------------------
1155 // -----------------------------------------------------------------------------
1157 void wxThread::SetPriority(unsigned int prio
)
1159 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1160 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1161 wxT("invalid thread priority") );
1163 wxCriticalSectionLocker
lock(m_critsect
);
1165 switch ( m_internal
->GetState() )
1168 // thread not yet started, priority will be set when it is
1169 m_internal
->SetPriority(prio
);
1174 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1176 struct sched_param sparam
;
1177 sparam
.sched_priority
= prio
;
1179 if ( pthread_setschedparam(m_internal
->GetId(),
1180 SCHED_OTHER
, &sparam
) != 0 )
1182 wxLogError(_("Failed to set thread priority %d."), prio
);
1185 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1190 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1194 unsigned int wxThread::GetPriority() const
1196 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1198 return m_internal
->GetPriority();
1201 wxThreadIdType
wxThread::GetId() const
1203 return (wxThreadIdType
) m_internal
->GetId();
1206 // -----------------------------------------------------------------------------
1208 // -----------------------------------------------------------------------------
1210 wxThreadError
wxThread::Pause()
1212 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1213 _T("a thread can't pause itself") );
1215 wxCriticalSectionLocker
lock(m_critsect
);
1217 if ( m_internal
->GetState() != STATE_RUNNING
)
1219 wxLogDebug(wxT("Can't pause thread which is not running."));
1221 return wxTHREAD_NOT_RUNNING
;
1224 // just set a flag, the thread will be really paused only during the next
1225 // call to TestDestroy()
1226 m_internal
->SetState(STATE_PAUSED
);
1228 return wxTHREAD_NO_ERROR
;
1231 wxThreadError
wxThread::Resume()
1233 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1234 _T("a thread can't resume itself") );
1236 wxCriticalSectionLocker
lock(m_critsect
);
1238 wxThreadState state
= m_internal
->GetState();
1243 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1246 m_internal
->Resume();
1248 return wxTHREAD_NO_ERROR
;
1251 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1253 return wxTHREAD_NO_ERROR
;
1256 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1258 return wxTHREAD_MISC_ERROR
;
1262 // -----------------------------------------------------------------------------
1264 // -----------------------------------------------------------------------------
1266 wxThread::ExitCode
wxThread::Wait()
1268 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1269 _T("a thread can't wait for itself") );
1271 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1272 _T("can't wait for detached thread") );
1276 return m_internal
->GetExitCode();
1279 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1281 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1282 _T("a thread can't delete itself") );
1284 bool isDetached
= m_isDetached
;
1287 wxThreadState state
= m_internal
->GetState();
1289 // ask the thread to stop
1290 m_internal
->SetCancelFlag();
1297 // we need to wake up the thread so that PthreadStart() will
1298 // terminate - right now it's blocking on run semaphore in
1300 m_internal
->SignalRun();
1309 // resume the thread first
1310 m_internal
->Resume();
1317 // wait until the thread stops
1322 // return the exit code of the thread
1323 *rc
= m_internal
->GetExitCode();
1326 //else: can't wait for detached threads
1329 return wxTHREAD_NO_ERROR
;
1332 wxThreadError
wxThread::Kill()
1334 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1335 _T("a thread can't kill itself") );
1337 switch ( m_internal
->GetState() )
1341 return wxTHREAD_NOT_RUNNING
;
1344 // resume the thread first
1350 #ifdef HAVE_PTHREAD_CANCEL
1351 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1354 wxLogError(_("Failed to terminate a thread."));
1356 return wxTHREAD_MISC_ERROR
;
1361 // if we use cleanup function, this will be done from
1362 // wxPthreadCleanup()
1363 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1364 ScheduleThreadForDeletion();
1366 // don't call OnExit() here, it can only be called in the
1367 // threads context and we're in the context of another thread
1370 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1374 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1377 return wxTHREAD_NO_ERROR
;
1381 void wxThread::Exit(ExitCode status
)
1383 wxASSERT_MSG( This() == this,
1384 _T("wxThread::Exit() can only be called in the "
1385 "context of the same thread") );
1389 // from the moment we call OnExit(), the main program may terminate at
1390 // any moment, so mark this thread as being already in process of being
1391 // deleted or wxThreadModule::OnExit() will try to delete it again
1392 ScheduleThreadForDeletion();
1395 // don't enter m_critsect before calling OnExit() because the user code
1396 // might deadlock if, for example, it signals a condition in OnExit() (a
1397 // common case) while the main thread calls any of functions entering
1398 // m_critsect on us (almost all of them do)
1401 // delete C++ thread object if this is a detached thread - user is
1402 // responsible for doing this for joinable ones
1405 // FIXME I'm feeling bad about it - what if another thread function is
1406 // called (in another thread context) now? It will try to access
1407 // half destroyed object which will probably result in something
1408 // very bad - but we can't protect this by a crit section unless
1409 // we make it a global object, but this would mean that we can
1410 // only call one thread function at a time :-(
1414 // terminate the thread (pthread_exit() never returns)
1415 pthread_exit(status
);
1417 wxFAIL_MSG(_T("pthread_exit() failed"));
1420 // also test whether we were paused
1421 bool wxThread::TestDestroy()
1423 wxASSERT_MSG( This() == this,
1424 _T("wxThread::TestDestroy() can only be called in the "
1425 "context of the same thread") );
1429 if ( m_internal
->GetState() == STATE_PAUSED
)
1431 m_internal
->SetReallyPaused(TRUE
);
1433 // leave the crit section or the other threads will stop too if they
1434 // try to call any of (seemingly harmless) IsXXX() functions while we
1438 m_internal
->Pause();
1442 // thread wasn't requested to pause, nothing to do
1446 return m_internal
->WasCancelled();
1449 wxThread::~wxThread()
1454 // check that the thread either exited or couldn't be created
1455 if ( m_internal
->GetState() != STATE_EXITED
&&
1456 m_internal
->GetState() != STATE_NEW
)
1458 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1459 "running! The application may crash."), GetId());
1463 #endif // __WXDEBUG__
1467 // remove this thread from the global array
1468 gs_allThreads
.Remove(this);
1471 // -----------------------------------------------------------------------------
1473 // -----------------------------------------------------------------------------
1475 bool wxThread::IsRunning() const
1477 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1479 return m_internal
->GetState() == STATE_RUNNING
;
1482 bool wxThread::IsAlive() const
1484 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1486 switch ( m_internal
->GetState() )
1497 bool wxThread::IsPaused() const
1499 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1501 return (m_internal
->GetState() == STATE_PAUSED
);
1504 //--------------------------------------------------------------------
1506 //--------------------------------------------------------------------
1508 class wxThreadModule
: public wxModule
1511 virtual bool OnInit();
1512 virtual void OnExit();
1515 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1518 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1520 bool wxThreadModule::OnInit()
1522 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1525 wxLogSysError(rc
, _("Thread module initialization failed: "
1526 "failed to create thread key"));
1531 gs_tidMain
= pthread_self();
1534 gs_mutexGui
= new wxMutex();
1536 gs_mutexGui
->Lock();
1539 gs_mutexDeleteThread
= new wxMutex();
1540 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1545 void wxThreadModule::OnExit()
1547 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1549 // are there any threads left which are being deleted right now?
1550 size_t nThreadsBeingDeleted
;
1553 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1554 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1556 if ( nThreadsBeingDeleted
> 0 )
1558 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1559 nThreadsBeingDeleted
);
1561 // have to wait until all of them disappear
1562 gs_condAllDeleted
->Wait();
1566 // terminate any threads left
1567 size_t count
= gs_allThreads
.GetCount();
1570 wxLogDebug(wxT("%u threads were not terminated by the application."),
1574 for ( size_t n
= 0u; n
< count
; n
++ )
1576 // Delete calls the destructor which removes the current entry. We
1577 // should only delete the first one each time.
1578 gs_allThreads
[0]->Delete();
1582 // destroy GUI mutex
1583 gs_mutexGui
->Unlock();
1588 // and free TLD slot
1589 (void)pthread_key_delete(gs_keySelf
);
1591 delete gs_condAllDeleted
;
1592 delete gs_mutexDeleteThread
;
1595 // ----------------------------------------------------------------------------
1597 // ----------------------------------------------------------------------------
1599 static void ScheduleThreadForDeletion()
1601 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1603 gs_nThreadsBeingDeleted
++;
1605 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1606 gs_nThreadsBeingDeleted
,
1607 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1610 static void DeleteThread(wxThread
*This
)
1612 // gs_mutexDeleteThread should be unlocked before signalling the condition
1613 // or wxThreadModule::OnExit() would deadlock
1614 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1616 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1620 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1621 _T("no threads scheduled for deletion, yet we delete one?") );
1623 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1624 gs_nThreadsBeingDeleted
- 1);
1626 if ( !--gs_nThreadsBeingDeleted
)
1628 // no more threads left, signal it
1629 gs_condAllDeleted
->Signal();
1633 void wxMutexGuiEnter()
1636 gs_mutexGui
->Lock();
1640 void wxMutexGuiLeave()
1643 gs_mutexGui
->Unlock();
1647 // ----------------------------------------------------------------------------
1648 // include common implementation code
1649 // ----------------------------------------------------------------------------
1651 #include "wx/thrimpl.cpp"
1653 #endif // wxUSE_THREADS