1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // Licence: wxWindows licence
13 /////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
24 #pragma implementation "thread.h"
31 #include "wx/thread.h"
32 #include "wx/module.h"
36 #include "wx/dynarray.h"
47 #ifdef HAVE_THR_SETCONCURRENCY
51 // we use wxFFile under Linux in GetCPUCount()
56 // ----------------------------------------------------------------------------
58 // ----------------------------------------------------------------------------
60 // the possible states of the thread and transitions from them
63 STATE_NEW
, // didn't start execution yet (=> RUNNING)
64 STATE_RUNNING
, // running (=> PAUSED or EXITED)
65 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
66 STATE_EXITED
// thread doesn't exist any more
69 // the exit value of a thread which has been cancelled
70 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
73 #define TRACE_THREADS _T("thread")
75 // ----------------------------------------------------------------------------
76 // pseudo template types
77 // ----------------------------------------------------------------------------
79 WX_DECLARE_LIST(pthread_mutex_t
, wxMutexList
);
81 #include "wx/listimpl.cpp"
82 WX_DEFINE_LIST(wxMutexList
);
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 static void ScheduleThreadForDeletion();
89 static void DeleteThread(wxThread
*This
);
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 // same as wxMutexLocker but for "native" mutex
99 MutexLock(pthread_mutex_t
& mutex
)
102 if ( pthread_mutex_lock(m_mutex
) != 0 )
104 wxLogDebug(_T("pthread_mutex_lock() failed"));
110 if ( pthread_mutex_unlock(m_mutex
) != 0 )
112 wxLogDebug(_T("pthread_mutex_unlock() failed"));
117 pthread_mutex_t
*m_mutex
;
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
126 // -----------------------------------------------------------------------------
128 // -----------------------------------------------------------------------------
130 // we keep the list of all threads created by the application to be able to
131 // terminate them on exit if there are some left - otherwise the process would
133 static wxArrayThread gs_allThreads
;
135 // the id of the main thread
136 static pthread_t gs_tidMain
;
138 // the key for the pointer to the associated wxThread object
139 static pthread_key_t gs_keySelf
;
141 // the number of threads which are being deleted - the program won't exit
142 // until there are any left
143 static size_t gs_nThreadsBeingDeleted
= 0;
145 // a mutex to protect gs_nThreadsBeingDeleted
146 static pthread_mutex_t gs_mutexDeleteThread
;
148 // and a condition variable which will be signaled when all
149 // gs_nThreadsBeingDeleted will have been deleted
150 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
153 // this mutex must be acquired before any call to a GUI function
154 static wxMutex
*gs_mutexGui
;
157 // ============================================================================
158 // wxMutex implementation
159 // ============================================================================
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 class wxMutexInternal
172 wxMutexError
TryLock();
173 wxMutexError
Unlock();
176 pthread_mutex_t m_mutex
;
179 wxMutexInternal::wxMutexInternal()
181 // support recursive locks like Win32, i.e. a thread can lock a mutex which
182 // it had itself already locked
184 // but initialization of recursive mutexes is non portable <sigh>, so try
186 #ifdef HAVE_PTHREAD_MUTEXATTR_T
187 pthread_mutexattr_t attr
;
188 pthread_mutexattr_init(&attr
);
189 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
191 pthread_mutex_init(&m_mutex
, &attr
);
192 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
193 // we can use this only as initializer so we have to assign it first to a
194 // temp var - assigning directly to m_mutex wouldn't even compile
195 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
197 #else // no recursive mutexes
198 pthread_mutex_init(&m_mutex
, NULL
);
200 // used by TryLock() below
201 #define NO_RECURSIVE_MUTEXES
202 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
205 wxMutexInternal::~wxMutexInternal()
207 pthread_mutex_destroy(&m_mutex
);
210 wxMutexError
wxMutexInternal::Lock()
212 int err
= pthread_mutex_lock(&m_mutex
);
216 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
217 return wxMUTEX_DEAD_LOCK
;
220 wxFAIL_MSG( _T("unexpected pthread_mutex_lock() return") );
224 wxLogDebug(_T("Failed to lock the mutex."));
225 return wxMUTEX_MISC_ERROR
;
228 return wxMUTEX_NO_ERROR
;
232 wxMutexError
wxMutexInternal::TryLock()
234 int err
= pthread_mutex_trylock(&m_mutex
);
241 wxFAIL_MSG( _T("unexpected pthread_mutex_trylock() return") );
245 wxLogDebug(_T("Failed to try to lock the mutex."));
246 return wxMUTEX_MISC_ERROR
;
249 return wxMUTEX_NO_ERROR
;
253 wxMutexError
wxMutexInternal::Unlock()
255 int err
= pthread_mutex_unlock(&m_mutex
);
259 // we don't own the mutex
260 return wxMUTEX_UNLOCKED
;
263 wxFAIL_MSG( _T("unexpected pthread_mutex_unlock() return") );
267 wxLogDebug(_T("Failed to unlock the mutex."));
268 return wxMUTEX_MISC_ERROR
;
271 return wxMUTEX_NO_ERROR
;
275 // ----------------------------------------------------------------------------
277 // ----------------------------------------------------------------------------
279 // TODO: this is completely generic, move it to common code?
283 m_internal
= new wxMutexInternal
;
291 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
296 wxMutexError
wxMutex::Lock()
298 wxMutexError err
= m_internal
->Lock();
308 wxMutexError
wxMutex::TryLock()
312 #ifdef NO_RECURSIVE_MUTEXES
313 return wxMUTEX_DEAD_LOCK
;
314 #else // have recursive mutexes on this platform
315 // we will succeed in locking it when we have it already locked
316 return wxMUTEX_NO_ERROR
;
317 #endif // recursive/non-recursive mutexes
320 wxMutexError err
= m_internal
->TryLock();
329 wxMutexError
wxMutex::Unlock()
337 wxLogDebug(wxT("Unlocking not locked mutex."));
339 return wxMUTEX_UNLOCKED
;
342 return m_internal
->Unlock();
345 // ============================================================================
346 // wxCondition implementation
347 // ============================================================================
349 // ----------------------------------------------------------------------------
350 // wxConditionInternal
351 // ----------------------------------------------------------------------------
353 // The native POSIX condition variables are dumb: if the condition is signaled
354 // before another thread starts to wait on it, the signal is lost and so this
355 // other thread will be never woken up. It's much more convenient to us to
356 // remember that the condition was signaled and to return from Wait()
357 // immediately in this case (this is more like Win32 automatic event objects)
358 class wxConditionInternal
361 wxConditionInternal();
362 ~wxConditionInternal();
364 // wait with the given timeout or indefinitely if NULL
365 bool Wait(const timespec
* ts
= NULL
);
367 void Signal(bool all
= FALSE
);
370 // the number of Signal() calls queued
372 // changed by Signal(), accessed by Wait()
374 // protected by m_mutexSignalCount
375 size_t m_nSignalsMissed
;
377 // protects access to m_nSignalsMissed
378 pthread_mutex_t m_mutexSignalCount
;
380 // serializes Broadcast() and/or Signal() calls
382 // TODO: I'm not sure if this is really needed but it shouldn't harm
383 // neither (except for efficiency condierations). However MSW doesn't
384 // do this so maybe we shouldn't do it here neither? (VZ)
385 pthread_mutex_t m_mutexSignal
;
387 // a condition variable must be always used with a mutex and so we maintain
388 // a list of mutexes - one for each thread that calls Wait().
390 // access to this list must be protected by m_mutexListContents
391 wxMutexList m_mutexes
;
393 // the condition itself
394 pthread_cond_t m_condition
;
396 // protects all accesses to m_mutexes list
397 pthread_mutex_t m_mutexListContents
;
400 wxConditionInternal::wxConditionInternal()
402 m_nSignalsMissed
= 0;
404 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
406 // this is supposed to never happen
407 wxFAIL_MSG( _T("pthread_cond_init() failed") );
410 if ( pthread_mutex_init(&m_mutexSignalCount
, NULL
) != 0 ||
411 pthread_mutex_init(&m_mutexListContents
, NULL
) != 0 ||
412 pthread_mutex_init(&m_mutexSignal
, NULL
) != 0 )
415 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
419 wxConditionInternal::~wxConditionInternal()
421 if ( pthread_cond_destroy( &m_condition
) != 0 )
423 wxLogDebug(_T("Failed to destroy condition variable (some "
424 "threads are probably still waiting on it?)"));
427 // the list of waiters mutexes must be empty by now
428 wxASSERT_MSG( !m_mutexes
.GetFirst(),
429 _T("deleting condition someone is still waiting on?") );
431 if ( pthread_mutex_destroy( &m_mutexSignalCount
) != 0 ||
432 pthread_mutex_destroy( &m_mutexListContents
) != 0 ||
433 pthread_mutex_destroy( &m_mutexSignal
) != 0 )
435 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
439 bool wxConditionInternal::Wait(const timespec
* ts
)
442 wxLogTrace(TRACE_THREADS
,
443 _T("wxCondition(%08x)::Wait: about to lock missed signal counter"),
446 MutexLock
lock(m_mutexSignalCount
);
448 if ( m_nSignalsMissed
)
450 // the condition was signaled before we started to wait, just
451 // decrease the number of queued signals and return
454 wxLogTrace(TRACE_THREADS
,
455 _T("wxCondition(%08x)::Wait: not waiting at all, count = %u"),
456 this, m_nSignalsMissed
);
462 // we need to really wait, create a new mutex for this
463 pthread_mutex_t
*mutex
= new pthread_mutex_t
;
464 if ( pthread_mutex_init(mutex
, (pthread_mutexattr_t
*)NULL
) != 0 )
466 // not supposed to happen
467 wxFAIL_MSG( _T("pthread_mutex_init() failed when starting waiting") );
470 // lock the mutex before starting to wait on it
471 pthread_mutex_lock(mutex
);
473 // lock the list before modifying it
474 wxMutexList::Node
*mutexNode
;
476 MutexLock
lockList(m_mutexListContents
);
478 mutexNode
= m_mutexes
.Append(mutex
);
481 // calling wait function below unlocks the mutex and Signal() or
482 // Broadcast() will be able to continue to run now if they were
483 // blocking for it in the loop locking all mutexes)
484 wxLogTrace(TRACE_THREADS
,
485 _T("wxCondition(%08x)::Wait(): starting to wait"), this);
486 int err
= ts
? pthread_cond_timedwait(&m_condition
, mutex
, ts
)
487 : pthread_cond_wait(&m_condition
, mutex
);
491 // condition was signaled
492 wxLogTrace(TRACE_THREADS
,
493 _T("wxCondition(%08x)::Wait(): ok"), this);
497 wxLogDebug(_T("unexpected pthread_cond_[timed]wait() return"));
502 // wait interrupted or timeout elapsed
503 wxLogTrace(TRACE_THREADS
,
504 _T("wxCondition(%08x)::Wait(): timeout/intr"), this);
507 // delete the mutex we had used for waiting
509 MutexLock
lock(m_mutexListContents
);
511 pthread_mutex_t
*m
= mutexNode
->GetData();
512 pthread_mutex_unlock(m
);
513 pthread_mutex_destroy(m
);
516 m_mutexes
.DeleteNode(mutexNode
);
522 void wxConditionInternal::Signal(bool all
)
524 // make sure that only one Signal() or Broadcast() is in progress
525 MutexLock
lock(m_mutexSignal
);
527 // this mutex has to be locked as well, so that during the entire Signal()
528 // call, no new Wait() is going to wreak havoc (it will block in the very
529 // beginning on this mutex instead)
530 MutexLock
lockSignalCount(m_mutexSignalCount
);
532 wxLogTrace(TRACE_THREADS
,
533 _T("wxCondition(%08x)::Signal(): got signal count mutex"),
537 MutexLock
lockList(m_mutexListContents
);
539 if ( !m_mutexes
.GetFirst() )
541 // nobody is waiting for us, just remember that the condition was
542 // signaled and don't do anything else for now
545 wxLogTrace(TRACE_THREADS
,
546 _T("wxCondition(%08x)::Signal(): no waiters, count = %u"),
547 this, m_nSignalsMissed
);
553 wxLogTrace(TRACE_THREADS
,
554 _T("wxCondition(%08x)::Signal(): acquiring all mutexes"), this);
556 // All mutexes on the list have to be locked. This means that execution of
557 // Signal() goes on as soon as all pending Wait() calls have called
558 // pthread_cond_wait() (where the mutex gets unlocked internally)
559 wxMutexList::Node
*node
;
560 for ( node
= m_mutexes
.GetFirst(); node
; node
= node
->GetNext() )
562 pthread_mutex_lock(node
->GetData());
565 // now we can finally signal it
566 wxLogTrace(TRACE_THREADS
, _T("wxCondition(%08x)::Signal(): preparing to %s"),
567 this, all
? _T("broadcast") : _T("signal"));
569 int err
= all
? pthread_cond_broadcast(&m_condition
)
570 : pthread_cond_signal(&m_condition
);
573 // shouldn't ever happen
574 wxFAIL_MSG(_T("pthread_cond_{broadcast|signal}() failed"));
577 // unlock all mutexes so that the threads blocking in their Wait()s could
579 for ( node
= m_mutexes
.GetFirst(); node
; node
= node
->GetNext() )
581 pthread_mutex_unlock(node
->GetData());
584 wxLogTrace(TRACE_THREADS
,
585 _T("wxCondition(%08x)::Signal(): exiting"), this);
588 // ----------------------------------------------------------------------------
590 // ----------------------------------------------------------------------------
592 wxCondition::wxCondition()
594 m_internal
= new wxConditionInternal
;
597 wxCondition::~wxCondition()
602 void wxCondition::Wait()
604 (void)m_internal
->Wait();
607 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
611 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
612 tspec
.tv_nsec
= nsec
;
614 return m_internal
->Wait(&tspec
);
617 void wxCondition::Signal()
619 m_internal
->Signal();
622 void wxCondition::Broadcast()
624 m_internal
->Signal(TRUE
/* all */);
627 // ============================================================================
628 // wxThread implementation
629 // ============================================================================
631 // the thread callback functions must have the C linkage
635 #if HAVE_THREAD_CLEANUP_FUNCTIONS
636 // thread exit function
637 void wxPthreadCleanup(void *ptr
);
638 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
640 void *wxPthreadStart(void *ptr
);
644 // ----------------------------------------------------------------------------
646 // ----------------------------------------------------------------------------
648 class wxThreadInternal
654 // thread entry function
655 static void *PthreadStart(wxThread
*thread
);
660 // ask the thread to terminate
662 // wake up threads waiting for our termination
664 // wake up threads waiting for our start
665 void SignalRun() { m_condRun
.Signal(); }
666 // go to sleep until Resume() is called
673 int GetPriority() const { return m_prio
; }
674 void SetPriority(int prio
) { m_prio
= prio
; }
676 wxThreadState
GetState() const { return m_state
; }
677 void SetState(wxThreadState state
) { m_state
= state
; }
679 pthread_t
GetId() const { return m_threadId
; }
680 pthread_t
*GetIdPtr() { return &m_threadId
; }
682 void SetCancelFlag() { m_cancelled
= TRUE
; }
683 bool WasCancelled() const { return m_cancelled
; }
685 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
686 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
689 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
690 bool IsReallyPaused() const { return m_isPaused
; }
692 // tell the thread that it is a detached one
695 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
698 // but even detached threads need to notifyus about their termination
699 // sometimes - tell the thread that it should do it
700 void Notify() { m_shouldBroadcast
= TRUE
; }
702 #if HAVE_THREAD_CLEANUP_FUNCTIONS
703 // this is used by wxPthreadCleanup() only
704 static void Cleanup(wxThread
*thread
);
705 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
708 pthread_t m_threadId
; // id of the thread
709 wxThreadState m_state
; // see wxThreadState enum
710 int m_prio
; // in wxWindows units: from 0 to 100
712 // this flag is set when the thread should terminate
715 // this flag is set when the thread is blocking on m_condSuspend
718 // the thread exit code - only used for joinable (!detached) threads and
719 // is only valid after the thread termination
720 wxThread::ExitCode m_exitcode
;
722 // many threads may call Wait(), but only one of them should call
723 // pthread_join(), so we have to keep track of this
724 wxCriticalSection m_csJoinFlag
;
725 bool m_shouldBeJoined
;
726 bool m_shouldBroadcast
;
729 // VZ: it's possible that we might do with less than three different
730 // condition objects - for example, m_condRun and m_condEnd a priori
731 // won't be used in the same time. But for now I prefer this may be a
732 // bit less efficient but safer solution of having distinct condition
733 // variables for each purpose.
735 // this condition is signaled by Run() and the threads Entry() is not
736 // called before it is done
737 wxCondition m_condRun
;
739 // this one is signaled when the thread should resume after having been
741 wxCondition m_condSuspend
;
743 // finally this one is signalled when the thread exits
744 wxCondition m_condEnd
;
747 // ----------------------------------------------------------------------------
748 // thread startup and exit functions
749 // ----------------------------------------------------------------------------
751 void *wxPthreadStart(void *ptr
)
753 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
756 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
758 wxThreadInternal
*pthread
= thread
->m_internal
;
760 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), pthread
->GetId());
762 // associate the thread pointer with the newly created thread so that
763 // wxThread::This() will work
764 int rc
= pthread_setspecific(gs_keySelf
, thread
);
767 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
772 // have to declare this before pthread_cleanup_push() which defines a
776 #if HAVE_THREAD_CLEANUP_FUNCTIONS
777 // install the cleanup handler which will be called if the thread is
779 pthread_cleanup_push(wxPthreadCleanup
, thread
);
780 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
782 // wait for the condition to be signaled from Run()
783 pthread
->m_condRun
.Wait();
785 // test whether we should run the run at all - may be it was deleted
786 // before it started to Run()?
788 wxCriticalSectionLocker
lock(thread
->m_critsect
);
790 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
791 pthread
->WasCancelled();
796 // call the main entry
797 pthread
->m_exitcode
= thread
->Entry();
799 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
803 wxCriticalSectionLocker
lock(thread
->m_critsect
);
805 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
808 // change the state of the thread to "exited" so that
809 // wxPthreadCleanup handler won't do anything from now (if it's
810 // called before we do pthread_cleanup_pop below)
811 pthread
->SetState(STATE_EXITED
);
815 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
816 // contains the matching '}' for the '{' in push, so they must be used
817 // in the same block!
818 #if HAVE_THREAD_CLEANUP_FUNCTIONS
819 // remove the cleanup handler without executing it
820 pthread_cleanup_pop(FALSE
);
821 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
827 return EXITCODE_CANCELLED
;
831 // terminate the thread
832 thread
->Exit(pthread
->m_exitcode
);
834 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
840 #if HAVE_THREAD_CLEANUP_FUNCTIONS
842 // this handler is called when the thread is cancelled
843 extern "C" void wxPthreadCleanup(void *ptr
)
845 wxThreadInternal::Cleanup((wxThread
*)ptr
);
848 void wxThreadInternal::Cleanup(wxThread
*thread
)
851 wxCriticalSectionLocker
lock(thread
->m_critsect
);
852 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
854 // thread is already considered as finished.
859 // exit the thread gracefully
860 thread
->Exit(EXITCODE_CANCELLED
);
863 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
865 // ----------------------------------------------------------------------------
867 // ----------------------------------------------------------------------------
869 wxThreadInternal::wxThreadInternal()
873 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
877 // set to TRUE only when the thread starts waiting on m_condSuspend
880 // defaults for joinable threads
881 m_shouldBeJoined
= TRUE
;
882 m_shouldBroadcast
= TRUE
;
883 m_isDetached
= FALSE
;
886 wxThreadInternal::~wxThreadInternal()
890 wxThreadError
wxThreadInternal::Run()
892 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
893 wxT("thread may only be started once after Create()") );
897 SetState(STATE_RUNNING
);
899 return wxTHREAD_NO_ERROR
;
902 void wxThreadInternal::Wait()
904 // if the thread we're waiting for is waiting for the GUI mutex, we will
905 // deadlock so make sure we release it temporarily
906 if ( wxThread::IsMain() )
909 bool isDetached
= m_isDetached
;
910 wxThreadIdType id
= GetId();
912 wxLogTrace(TRACE_THREADS
,
913 _T("Starting to wait for thread %ld to exit."), id
);
915 // wait until the thread terminates (we're blocking in _another_ thread,
919 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
921 // we can't use any member variables any more if the thread is detached
922 // because it could be already deleted
925 // to avoid memory leaks we should call pthread_join(), but it must
927 wxCriticalSectionLocker
lock(m_csJoinFlag
);
929 if ( m_shouldBeJoined
)
931 // FIXME shouldn't we set cancellation type to DISABLED here? If
932 // we're cancelled inside pthread_join(), things will almost
933 // certainly break - but if we disable the cancellation, we
935 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
937 wxLogError(_("Failed to join a thread, potential memory leak "
938 "detected - please restart the program"));
941 m_shouldBeJoined
= FALSE
;
945 // reacquire GUI mutex
946 if ( wxThread::IsMain() )
950 void wxThreadInternal::SignalExit()
952 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
954 SetState(STATE_EXITED
);
956 // wake up all the threads waiting for our termination - if there are any
957 if ( m_shouldBroadcast
)
959 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
962 m_condEnd
.Broadcast();
966 void wxThreadInternal::Pause()
968 // the state is set from the thread which pauses us first, this function
969 // is called later so the state should have been already set
970 wxCHECK_RET( m_state
== STATE_PAUSED
,
971 wxT("thread must first be paused with wxThread::Pause().") );
973 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
975 // wait until the condition is signaled from Resume()
976 m_condSuspend
.Wait();
979 void wxThreadInternal::Resume()
981 wxCHECK_RET( m_state
== STATE_PAUSED
,
982 wxT("can't resume thread which is not suspended.") );
984 // the thread might be not actually paused yet - if there were no call to
985 // TestDestroy() since the last call to Pause() for example
986 if ( IsReallyPaused() )
988 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
991 m_condSuspend
.Signal();
994 SetReallyPaused(FALSE
);
998 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
1002 SetState(STATE_RUNNING
);
1005 // -----------------------------------------------------------------------------
1006 // wxThread static functions
1007 // -----------------------------------------------------------------------------
1009 wxThread
*wxThread::This()
1011 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1014 bool wxThread::IsMain()
1016 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
1019 void wxThread::Yield()
1021 #ifdef HAVE_SCHED_YIELD
1026 void wxThread::Sleep(unsigned long milliseconds
)
1028 wxUsleep(milliseconds
);
1031 int wxThread::GetCPUCount()
1033 #if defined(__LINUX__) && wxUSE_FFILE
1034 // read from proc (can't use wxTextFile here because it's a special file:
1035 // it has 0 size but still can be read from)
1038 wxFFile
file(_T("/proc/cpuinfo"));
1039 if ( file
.IsOpened() )
1041 // slurp the whole file
1043 if ( file
.ReadAll(&s
) )
1045 // (ab)use Replace() to find the number of "processor" strings
1046 size_t count
= s
.Replace(_T("processor"), _T(""));
1052 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1056 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1059 #elif defined(_SC_NPROCESSORS_ONLN)
1060 // this works for Solaris
1061 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1066 #endif // different ways to get number of CPUs
1073 // VMS is a 64 bit system and threads have 64 bit pointers.
1074 // ??? also needed for other systems????
1075 unsigned long long wxThread::GetCurrentId()
1077 return (unsigned long long)pthread_self();
1079 unsigned long wxThread::GetCurrentId()
1081 return (unsigned long)pthread_self();
1085 bool wxThread::SetConcurrency(size_t level
)
1087 #ifdef HAVE_THR_SETCONCURRENCY
1088 int rc
= thr_setconcurrency(level
);
1091 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1095 #else // !HAVE_THR_SETCONCURRENCY
1096 // ok only for the default value
1098 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1101 // -----------------------------------------------------------------------------
1103 // -----------------------------------------------------------------------------
1105 wxThread::wxThread(wxThreadKind kind
)
1107 // add this thread to the global list of all threads
1108 gs_allThreads
.Add(this);
1110 m_internal
= new wxThreadInternal();
1112 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1115 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1117 if ( m_internal
->GetState() != STATE_NEW
)
1119 // don't recreate thread
1120 return wxTHREAD_RUNNING
;
1123 // set up the thread attribute: right now, we only set thread priority
1124 pthread_attr_t attr
;
1125 pthread_attr_init(&attr
);
1127 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1129 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1131 wxLogError(_("Cannot retrieve thread scheduling policy."));
1135 /* the pthread.h contains too many spaces. This is a work-around */
1136 # undef sched_get_priority_max
1137 #undef sched_get_priority_min
1138 #define sched_get_priority_max(_pol_) \
1139 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1140 #define sched_get_priority_min(_pol_) \
1141 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1144 int max_prio
= sched_get_priority_max(policy
),
1145 min_prio
= sched_get_priority_min(policy
),
1146 prio
= m_internal
->GetPriority();
1148 if ( min_prio
== -1 || max_prio
== -1 )
1150 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1153 else if ( max_prio
== min_prio
)
1155 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1157 // notify the programmer that this doesn't work here
1158 wxLogWarning(_("Thread priority setting is ignored."));
1160 //else: we have default priority, so don't complain
1162 // anyhow, don't do anything because priority is just ignored
1166 struct sched_param sp
;
1167 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1169 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1172 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1174 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1176 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1179 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1181 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1182 // this will make the threads created by this process really concurrent
1183 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1185 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1187 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1189 // VZ: assume that this one is always available (it's rather fundamental),
1190 // if this function is ever missing we should try to use
1191 // pthread_detach() instead (after thread creation)
1194 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1196 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1199 // never try to join detached threads
1200 m_internal
->Detach();
1202 //else: threads are created joinable by default, it's ok
1204 // create the new OS thread object
1205 int rc
= pthread_create
1207 m_internal
->GetIdPtr(),
1213 if ( pthread_attr_destroy(&attr
) != 0 )
1215 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1220 m_internal
->SetState(STATE_EXITED
);
1222 return wxTHREAD_NO_RESOURCE
;
1225 return wxTHREAD_NO_ERROR
;
1228 wxThreadError
wxThread::Run()
1230 wxCriticalSectionLocker
lock(m_critsect
);
1232 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1233 wxT("must call wxThread::Create() first") );
1235 return m_internal
->Run();
1238 // -----------------------------------------------------------------------------
1240 // -----------------------------------------------------------------------------
1242 void wxThread::SetPriority(unsigned int prio
)
1244 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1245 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1246 wxT("invalid thread priority") );
1248 wxCriticalSectionLocker
lock(m_critsect
);
1250 switch ( m_internal
->GetState() )
1253 // thread not yet started, priority will be set when it is
1254 m_internal
->SetPriority(prio
);
1259 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1261 struct sched_param sparam
;
1262 sparam
.sched_priority
= prio
;
1264 if ( pthread_setschedparam(m_internal
->GetId(),
1265 SCHED_OTHER
, &sparam
) != 0 )
1267 wxLogError(_("Failed to set thread priority %d."), prio
);
1270 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1275 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1279 unsigned int wxThread::GetPriority() const
1281 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1283 return m_internal
->GetPriority();
1286 wxThreadIdType
wxThread::GetId() const
1288 return m_internal
->GetId();
1291 // -----------------------------------------------------------------------------
1293 // -----------------------------------------------------------------------------
1295 wxThreadError
wxThread::Pause()
1297 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1298 _T("a thread can't pause itself") );
1300 wxCriticalSectionLocker
lock(m_critsect
);
1302 if ( m_internal
->GetState() != STATE_RUNNING
)
1304 wxLogDebug(wxT("Can't pause thread which is not running."));
1306 return wxTHREAD_NOT_RUNNING
;
1309 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1312 // just set a flag, the thread will be really paused only during the next
1313 // call to TestDestroy()
1314 m_internal
->SetState(STATE_PAUSED
);
1316 return wxTHREAD_NO_ERROR
;
1319 wxThreadError
wxThread::Resume()
1321 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1322 _T("a thread can't resume itself") );
1324 wxCriticalSectionLocker
lock(m_critsect
);
1326 wxThreadState state
= m_internal
->GetState();
1331 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1334 m_internal
->Resume();
1336 return wxTHREAD_NO_ERROR
;
1339 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1341 return wxTHREAD_NO_ERROR
;
1344 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1346 return wxTHREAD_MISC_ERROR
;
1350 // -----------------------------------------------------------------------------
1352 // -----------------------------------------------------------------------------
1354 wxThread::ExitCode
wxThread::Wait()
1356 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1357 _T("a thread can't wait for itself") );
1359 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1360 _T("can't wait for detached thread") );
1364 return m_internal
->GetExitCode();
1367 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1369 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1370 _T("a thread can't delete itself") );
1373 wxThreadState state
= m_internal
->GetState();
1375 // ask the thread to stop
1376 m_internal
->SetCancelFlag();
1380 // detached threads won't broadcast about their termination by default
1381 // because usually nobody waits for them - but here we do, so ask the
1382 // thread to notify us
1383 m_internal
->Notify();
1391 // we need to wake up the thread so that PthreadStart() will
1392 // terminate - right now it's blocking on m_condRun
1393 m_internal
->SignalRun();
1402 // resume the thread first (don't call our Resume() because this
1403 // would dead lock when it tries to enter m_critsect)
1404 m_internal
->Resume();
1409 // wait until the thread stops
1414 wxASSERT_MSG( !m_isDetached
,
1415 _T("no return code for detached threads") );
1417 // if it's a joinable thread, it's not deleted yet
1418 *rc
= m_internal
->GetExitCode();
1422 return wxTHREAD_NO_ERROR
;
1425 wxThreadError
wxThread::Kill()
1427 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1428 _T("a thread can't kill itself") );
1430 switch ( m_internal
->GetState() )
1434 return wxTHREAD_NOT_RUNNING
;
1437 // resume the thread first
1443 #ifdef HAVE_PTHREAD_CANCEL
1444 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1447 wxLogError(_("Failed to terminate a thread."));
1449 return wxTHREAD_MISC_ERROR
;
1454 // if we use cleanup function, this will be done from
1455 // wxPthreadCleanup()
1456 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1457 ScheduleThreadForDeletion();
1459 // don't call OnExit() here, it can only be called in the
1460 // threads context and we're in the context of another thread
1463 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1467 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1470 return wxTHREAD_NO_ERROR
;
1474 void wxThread::Exit(ExitCode status
)
1476 wxASSERT_MSG( This() == this,
1477 _T("wxThread::Exit() can only be called in the "
1478 "context of the same thread") );
1480 // from the moment we call OnExit(), the main program may terminate at any
1481 // moment, so mark this thread as being already in process of being
1482 // deleted or wxThreadModule::OnExit() will try to delete it again
1483 ScheduleThreadForDeletion();
1485 // don't enter m_critsect before calling OnExit() because the user code
1486 // might deadlock if, for example, it signals a condition in OnExit() (a
1487 // common case) while the main thread calls any of functions entering
1488 // m_critsect on us (almost all of them do)
1491 // now do enter it because SignalExit() will change our state
1494 // next wake up the threads waiting for us (OTOH, this function won't return
1495 // until someone waited for us!)
1496 m_internal
->SignalExit();
1498 // leave the critical section before entering the dtor which tries to
1502 // delete C++ thread object if this is a detached thread - user is
1503 // responsible for doing this for joinable ones
1506 // FIXME I'm feeling bad about it - what if another thread function is
1507 // called (in another thread context) now? It will try to access
1508 // half destroyed object which will probably result in something
1509 // very bad - but we can't protect this by a crit section unless
1510 // we make it a global object, but this would mean that we can
1511 // only call one thread function at a time :-(
1515 // terminate the thread (pthread_exit() never returns)
1516 pthread_exit(status
);
1518 wxFAIL_MSG(_T("pthread_exit() failed"));
1521 // also test whether we were paused
1522 bool wxThread::TestDestroy()
1524 wxASSERT_MSG( This() == this,
1525 _T("wxThread::TestDestroy() can only be called in the "
1526 "context of the same thread") );
1530 if ( m_internal
->GetState() == STATE_PAUSED
)
1532 m_internal
->SetReallyPaused(TRUE
);
1534 // leave the crit section or the other threads will stop too if they
1535 // try to call any of (seemingly harmless) IsXXX() functions while we
1539 m_internal
->Pause();
1543 // thread wasn't requested to pause, nothing to do
1547 return m_internal
->WasCancelled();
1550 wxThread::~wxThread()
1555 // check that the thread either exited or couldn't be created
1556 if ( m_internal
->GetState() != STATE_EXITED
&&
1557 m_internal
->GetState() != STATE_NEW
)
1559 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1560 "running! The application may crash."), GetId());
1564 #endif // __WXDEBUG__
1568 // remove this thread from the global array
1569 gs_allThreads
.Remove(this);
1571 // detached thread will decrement this counter in DeleteThread(), but it
1572 // is not called for the joinable threads, so do it here
1573 if ( !m_isDetached
)
1575 MutexLock
lock(gs_mutexDeleteThread
);
1576 gs_nThreadsBeingDeleted
--;
1578 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1579 gs_nThreadsBeingDeleted
- 1);
1583 // -----------------------------------------------------------------------------
1585 // -----------------------------------------------------------------------------
1587 bool wxThread::IsRunning() const
1589 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1591 return m_internal
->GetState() == STATE_RUNNING
;
1594 bool wxThread::IsAlive() const
1596 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1598 switch ( m_internal
->GetState() )
1609 bool wxThread::IsPaused() const
1611 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1613 return (m_internal
->GetState() == STATE_PAUSED
);
1616 //--------------------------------------------------------------------
1618 //--------------------------------------------------------------------
1620 class wxThreadModule
: public wxModule
1623 virtual bool OnInit();
1624 virtual void OnExit();
1627 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1630 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1632 bool wxThreadModule::OnInit()
1634 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1637 wxLogSysError(rc
, _("Thread module initialization failed: "
1638 "failed to create thread key"));
1643 gs_tidMain
= pthread_self();
1646 gs_mutexGui
= new wxMutex();
1648 gs_mutexGui
->Lock();
1651 // under Solaris we get a warning from CC when using
1652 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1653 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1658 void wxThreadModule::OnExit()
1660 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1662 // are there any threads left which are being deleted right now?
1663 size_t nThreadsBeingDeleted
;
1665 MutexLock
lock(gs_mutexDeleteThread
);
1666 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1669 if ( nThreadsBeingDeleted
> 0 )
1671 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1672 nThreadsBeingDeleted
);
1674 // have to wait until all of them disappear
1675 gs_condAllDeleted
->Wait();
1678 // terminate any threads left
1679 size_t count
= gs_allThreads
.GetCount();
1682 wxLogDebug(wxT("%u threads were not terminated by the application."),
1686 for ( size_t n
= 0u; n
< count
; n
++ )
1688 // Delete calls the destructor which removes the current entry. We
1689 // should only delete the first one each time.
1690 gs_allThreads
[0]->Delete();
1694 // destroy GUI mutex
1695 gs_mutexGui
->Unlock();
1700 // and free TLD slot
1701 (void)pthread_key_delete(gs_keySelf
);
1704 // ----------------------------------------------------------------------------
1706 // ----------------------------------------------------------------------------
1708 static void ScheduleThreadForDeletion()
1710 MutexLock
lock(gs_mutexDeleteThread
);
1712 if ( gs_nThreadsBeingDeleted
== 0 )
1714 gs_condAllDeleted
= new wxCondition
;
1717 gs_nThreadsBeingDeleted
++;
1719 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1720 gs_nThreadsBeingDeleted
,
1721 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1724 static void DeleteThread(wxThread
*This
)
1726 // gs_mutexDeleteThread should be unlocked before signalling the condition
1727 // or wxThreadModule::OnExit() would deadlock
1729 MutexLock
lock(gs_mutexDeleteThread
);
1731 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1735 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1736 _T("no threads scheduled for deletion, yet we delete "
1740 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1741 gs_nThreadsBeingDeleted
- 1);
1743 if ( !--gs_nThreadsBeingDeleted
)
1745 // no more threads left, signal it
1746 gs_condAllDeleted
->Signal();
1748 delete gs_condAllDeleted
;
1749 gs_condAllDeleted
= (wxCondition
*)NULL
;
1753 void wxMutexGuiEnter()
1756 gs_mutexGui
->Lock();
1760 void wxMutexGuiLeave()
1763 gs_mutexGui
->Unlock();