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)
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"
48 #ifdef HAVE_THR_SETCONCURRENCY
52 // we use wxFFile under Linux in GetCPUCount()
57 // ----------------------------------------------------------------------------
59 // ----------------------------------------------------------------------------
61 // the possible states of the thread and transitions from them
64 STATE_NEW
, // didn't start execution yet (=> RUNNING)
65 STATE_RUNNING
, // running (=> PAUSED or EXITED)
66 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
67 STATE_EXITED
// thread doesn't exist any more
70 // the exit value of a thread which has been cancelled
71 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
74 #define TRACE_THREADS _T("thread")
76 // ----------------------------------------------------------------------------
78 // ----------------------------------------------------------------------------
80 static void ScheduleThreadForDeletion();
81 static void DeleteThread(wxThread
*This
);
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 // same as wxMutexLocker but for "native" mutex
91 MutexLock(pthread_mutex_t
& mutex
)
94 if ( pthread_mutex_lock(m_mutex
) != 0 )
96 wxLogDebug(_T("pthread_mutex_lock() failed"));
102 if ( pthread_mutex_unlock(m_mutex
) != 0 )
104 wxLogDebug(_T("pthread_mutex_unlock() failed"));
109 pthread_mutex_t
*m_mutex
;
112 // ----------------------------------------------------------------------------
114 // ----------------------------------------------------------------------------
116 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
118 // -----------------------------------------------------------------------------
120 // -----------------------------------------------------------------------------
122 // we keep the list of all threads created by the application to be able to
123 // terminate them on exit if there are some left - otherwise the process would
125 static wxArrayThread gs_allThreads
;
127 // the id of the main thread
128 static pthread_t gs_tidMain
;
130 // the key for the pointer to the associated wxThread object
131 static pthread_key_t gs_keySelf
;
133 // the number of threads which are being deleted - the program won't exit
134 // until there are any left
135 static size_t gs_nThreadsBeingDeleted
= 0;
137 // a mutex to protect gs_nThreadsBeingDeleted
138 static pthread_mutex_t gs_mutexDeleteThread
;
140 // and a condition variable which will be signaled when all
141 // gs_nThreadsBeingDeleted will have been deleted
142 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
145 // this mutex must be acquired before any call to a GUI function
146 static wxMutex
*gs_mutexGui
;
149 // ============================================================================
151 // ============================================================================
153 //--------------------------------------------------------------------
154 // wxMutex (Posix implementation)
155 //--------------------------------------------------------------------
157 class wxMutexInternal
160 pthread_mutex_t m_mutex
;
165 m_internal
= new wxMutexInternal
;
167 // support recursive locks like Win32, i.e. a thread can lock a mutex which
168 // it had itself already locked
170 // but initialization of recursive mutexes is non portable <sigh>, so try
172 #ifdef HAVE_PTHREAD_MUTEXATTR_T
173 pthread_mutexattr_t attr
;
174 pthread_mutexattr_init(&attr
);
175 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
177 pthread_mutex_init(&(m_internal
->m_mutex
), &attr
);
178 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
179 // we can use this only as initializer so we have to assign it first to a
180 // temp var - assigning directly to m_mutex wouldn't even compile
181 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
182 m_internal
->m_mutex
= mutex
;
183 #else // no recursive mutexes
184 pthread_mutex_init(&(m_internal
->m_mutex
), NULL
);
185 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
193 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
195 pthread_mutex_destroy( &(m_internal
->m_mutex
) );
199 wxMutexError
wxMutex::Lock()
201 int err
= pthread_mutex_lock( &(m_internal
->m_mutex
) );
204 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
206 return wxMUTEX_DEAD_LOCK
;
211 return wxMUTEX_NO_ERROR
;
214 wxMutexError
wxMutex::TryLock()
221 int err
= pthread_mutex_trylock( &(m_internal
->m_mutex
) );
224 case EBUSY
: return wxMUTEX_BUSY
;
229 return wxMUTEX_NO_ERROR
;
232 wxMutexError
wxMutex::Unlock()
240 wxLogDebug(wxT("Unlocking not locked mutex."));
242 return wxMUTEX_UNLOCKED
;
245 pthread_mutex_unlock( &(m_internal
->m_mutex
) );
247 return wxMUTEX_NO_ERROR
;
250 //--------------------------------------------------------------------
251 // wxCondition (Posix implementation)
252 //--------------------------------------------------------------------
254 // The native POSIX condition variables are dumb: if the condition is signaled
255 // before another thread starts to wait on it, the signal is lost and so this
256 // other thread will be never woken up. It's much more convenient to us to
257 // remember that the condition was signaled and to return from Wait()
258 // immediately in this case (this is more like Win32 automatic event objects)
260 class wxConditionInternal
263 wxConditionInternal();
264 ~wxConditionInternal();
267 bool WaitWithTimeout(const timespec
* ts
);
277 bool m_wasSignaled
; // TRUE if condition was signaled while
278 // nobody waited for it
279 size_t m_nWaiters
; // TRUE if someone already waits for us
281 pthread_mutex_t m_mutexProtect
; // protects access to vars above
283 pthread_mutex_t m_mutex
; // the mutex used with the condition
284 pthread_cond_t m_condition
; // the condition itself
287 wxConditionInternal::wxConditionInternal()
289 m_wasSignaled
= FALSE
;
292 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
294 // this is supposed to never happen
295 wxFAIL_MSG( _T("pthread_cond_init() failed") );
298 if ( pthread_mutex_init(&m_mutex
, (pthread_mutexattr_t
*)NULL
) != 0 ||
299 pthread_mutex_init(&m_mutexProtect
, NULL
) != 0 )
302 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
305 // initially the mutex is locked, so no thread can Signal() or Broadcast()
306 // until another thread starts to Wait()
307 if ( pthread_mutex_lock(&m_mutex
) != 0 )
309 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
313 wxConditionInternal::~wxConditionInternal()
315 if ( pthread_cond_destroy( &m_condition
) != 0 )
317 wxLogDebug(_T("Failed to destroy condition variable (some "
318 "threads are probably still waiting on it?)"));
321 if ( pthread_mutex_unlock( &m_mutex
) != 0 )
323 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
326 if ( pthread_mutex_destroy( &m_mutex
) != 0 ||
327 pthread_mutex_destroy( &m_mutexProtect
) != 0 )
329 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
333 void wxConditionInternal::WaitDone()
335 MutexLock
lock(m_mutexProtect
);
337 m_wasSignaled
= FALSE
;
341 bool wxConditionInternal::ShouldWait()
343 MutexLock
lock(m_mutexProtect
);
347 // the condition was signaled before we started to wait, reset the
349 m_wasSignaled
= FALSE
;
354 // we start to wait for it
360 bool wxConditionInternal::HasWaiters()
362 MutexLock
lock(m_mutexProtect
);
366 // someone waits for us, signal the condition normally
370 // nobody waits for us and may be never will - so just remember that the
371 // condition was signaled and don't do anything else
372 m_wasSignaled
= TRUE
;
377 void wxConditionInternal::Wait()
381 if ( pthread_cond_wait( &m_condition
, &m_mutex
) != 0 )
383 // not supposed to ever happen
384 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
391 bool wxConditionInternal::WaitWithTimeout(const timespec
* ts
)
397 switch ( pthread_cond_timedwait( &m_condition
, &m_mutex
, ts
) )
400 // condition signaled
405 wxLogDebug(_T("pthread_cond_timedwait() failed"));
411 // wait interrupted or timeout elapsed
417 // the condition had already been signaled before
426 void wxConditionInternal::Signal()
430 MutexLock
lock(m_mutex
);
432 if ( pthread_cond_signal( &m_condition
) != 0 )
434 // shouldn't ever happen
435 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
440 void wxConditionInternal::Broadcast()
444 MutexLock
lock(m_mutex
);
446 if ( pthread_cond_broadcast( &m_condition
) != 0 )
448 // shouldn't ever happen
449 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
454 wxCondition::wxCondition()
456 m_internal
= new wxConditionInternal
;
459 wxCondition::~wxCondition()
464 void wxCondition::Wait()
469 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
473 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
474 tspec
.tv_nsec
= nsec
;
476 return m_internal
->WaitWithTimeout(&tspec
);
479 void wxCondition::Signal()
481 m_internal
->Signal();
484 void wxCondition::Broadcast()
486 m_internal
->Broadcast();
489 //--------------------------------------------------------------------
490 // wxThread (Posix implementation)
491 //--------------------------------------------------------------------
493 #if HAVE_THREAD_CLEANUP_FUNCTIONS
495 // thread exit function
496 extern "C" void wxPthreadCleanup(void *ptr
);
498 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
500 class wxThreadInternal
506 // thread entry function
507 static void *PthreadStart(void *ptr
);
512 // ask the thread to terminate
514 // wake up threads waiting for our termination
516 // wake up threads waiting for our start
517 void SignalRun() { m_condRun
.Signal(); }
518 // go to sleep until Resume() is called
525 int GetPriority() const { return m_prio
; }
526 void SetPriority(int prio
) { m_prio
= prio
; }
528 wxThreadState
GetState() const { return m_state
; }
529 void SetState(wxThreadState state
) { m_state
= state
; }
531 pthread_t
GetId() const { return m_threadId
; }
532 pthread_t
*GetIdPtr() { return &m_threadId
; }
534 void SetCancelFlag() { m_cancelled
= TRUE
; }
535 bool WasCancelled() const { return m_cancelled
; }
537 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
538 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
541 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
542 bool IsReallyPaused() const { return m_isPaused
; }
544 // tell the thread that it is a detached one
547 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
550 // but even detached threads need to notifyus about their termination
551 // sometimes - tell the thread that it should do it
552 void Notify() { m_shouldBroadcast
= TRUE
; }
554 #if HAVE_THREAD_CLEANUP_FUNCTIONS
555 // this is used by wxPthreadCleanup() only
556 static void Cleanup(wxThread
*thread
);
557 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
560 pthread_t m_threadId
; // id of the thread
561 wxThreadState m_state
; // see wxThreadState enum
562 int m_prio
; // in wxWindows units: from 0 to 100
564 // this flag is set when the thread should terminate
567 // this flag is set when the thread is blocking on m_condSuspend
570 // the thread exit code - only used for joinable (!detached) threads and
571 // is only valid after the thread termination
572 wxThread::ExitCode m_exitcode
;
574 // many threads may call Wait(), but only one of them should call
575 // pthread_join(), so we have to keep track of this
576 wxCriticalSection m_csJoinFlag
;
577 bool m_shouldBeJoined
;
578 bool m_shouldBroadcast
;
581 // VZ: it's possible that we might do with less than three different
582 // condition objects - for example, m_condRun and m_condEnd a priori
583 // won't be used in the same time. But for now I prefer this may be a
584 // bit less efficient but safer solution of having distinct condition
585 // variables for each purpose.
587 // this condition is signaled by Run() and the threads Entry() is not
588 // called before it is done
589 wxCondition m_condRun
;
591 // this one is signaled when the thread should resume after having been
593 wxCondition m_condSuspend
;
595 // finally this one is signalled when the thread exits
596 wxCondition m_condEnd
;
599 // ----------------------------------------------------------------------------
600 // thread startup and exit functions
601 // ----------------------------------------------------------------------------
603 void *wxThreadInternal::PthreadStart(void *ptr
)
605 wxThread
*thread
= (wxThread
*)ptr
;
606 wxThreadInternal
*pthread
= thread
->m_internal
;
608 // associate the thread pointer with the newly created thread so that
609 // wxThread::This() will work
610 int rc
= pthread_setspecific(gs_keySelf
, thread
);
613 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
618 // have to declare this before pthread_cleanup_push() which defines a
622 #if HAVE_THREAD_CLEANUP_FUNCTIONS
623 // install the cleanup handler which will be called if the thread is
625 pthread_cleanup_push(wxPthreadCleanup
, ptr
);
626 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
628 // wait for the condition to be signaled from Run()
629 pthread
->m_condRun
.Wait();
631 // test whether we should run the run at all - may be it was deleted
632 // before it started to Run()?
634 wxCriticalSectionLocker
lock(thread
->m_critsect
);
636 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
637 pthread
->WasCancelled();
642 // call the main entry
643 pthread
->m_exitcode
= thread
->Entry();
645 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
649 wxCriticalSectionLocker
lock(thread
->m_critsect
);
651 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
654 // change the state of the thread to "exited" so that
655 // wxPthreadCleanup handler won't do anything from now (if it's
656 // called before we do pthread_cleanup_pop below)
657 pthread
->SetState(STATE_EXITED
);
661 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
662 // contains the matching '}' for the '{' in push, so they must be used
663 // in the same block!
664 #if HAVE_THREAD_CLEANUP_FUNCTIONS
665 // remove the cleanup handler without executing it
666 pthread_cleanup_pop(FALSE
);
667 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
673 return EXITCODE_CANCELLED
;
677 // terminate the thread
678 thread
->Exit(pthread
->m_exitcode
);
680 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
686 #if HAVE_THREAD_CLEANUP_FUNCTIONS
688 // this handler is called when the thread is cancelled
689 extern "C" void wxPthreadCleanup(void *ptr
)
691 wxThreadInternal::Cleanup((wxThread
*)ptr
);
694 void wxThreadInternal::Cleanup(wxThread
*thread
)
697 wxCriticalSectionLocker
lock(thread
->m_critsect
);
698 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
700 // thread is already considered as finished.
705 // exit the thread gracefully
706 thread
->Exit(EXITCODE_CANCELLED
);
709 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
711 // ----------------------------------------------------------------------------
713 // ----------------------------------------------------------------------------
715 wxThreadInternal::wxThreadInternal()
719 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
723 // set to TRUE only when the thread starts waiting on m_condSuspend
726 // defaults for joinable threads
727 m_shouldBeJoined
= TRUE
;
728 m_shouldBroadcast
= TRUE
;
729 m_isDetached
= FALSE
;
732 wxThreadInternal::~wxThreadInternal()
736 wxThreadError
wxThreadInternal::Run()
738 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
739 wxT("thread may only be started once after Create()") );
743 SetState(STATE_RUNNING
);
745 return wxTHREAD_NO_ERROR
;
748 void wxThreadInternal::Wait()
750 // if the thread we're waiting for is waiting for the GUI mutex, we will
751 // deadlock so make sure we release it temporarily
752 if ( wxThread::IsMain() )
755 bool isDetached
= m_isDetached
;
757 long long id
= (long long)GetId();
759 long id
= (long)GetId();
761 wxLogTrace(TRACE_THREADS
, _T("Starting to wait for thread %ld to exit."),
764 // wait until the thread terminates (we're blocking in _another_ thread,
768 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
770 // we can't use any member variables any more if the thread is detached
771 // because it could be already deleted
774 // to avoid memory leaks we should call pthread_join(), but it must
776 wxCriticalSectionLocker
lock(m_csJoinFlag
);
778 if ( m_shouldBeJoined
)
780 // FIXME shouldn't we set cancellation type to DISABLED here? If
781 // we're cancelled inside pthread_join(), things will almost
782 // certainly break - but if we disable the cancellation, we
784 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
786 wxLogError(_("Failed to join a thread, potential memory leak "
787 "detected - please restart the program"));
790 m_shouldBeJoined
= FALSE
;
794 // reacquire GUI mutex
795 if ( wxThread::IsMain() )
799 void wxThreadInternal::SignalExit()
801 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
803 SetState(STATE_EXITED
);
805 // wake up all the threads waiting for our termination - if there are any
806 if ( m_shouldBroadcast
)
808 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
811 m_condEnd
.Broadcast();
815 void wxThreadInternal::Pause()
817 // the state is set from the thread which pauses us first, this function
818 // is called later so the state should have been already set
819 wxCHECK_RET( m_state
== STATE_PAUSED
,
820 wxT("thread must first be paused with wxThread::Pause().") );
822 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
824 // wait until the condition is signaled from Resume()
825 m_condSuspend
.Wait();
828 void wxThreadInternal::Resume()
830 wxCHECK_RET( m_state
== STATE_PAUSED
,
831 wxT("can't resume thread which is not suspended.") );
833 // the thread might be not actually paused yet - if there were no call to
834 // TestDestroy() since the last call to Pause() for example
835 if ( IsReallyPaused() )
837 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
840 m_condSuspend
.Signal();
843 SetReallyPaused(FALSE
);
847 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
851 SetState(STATE_RUNNING
);
854 // -----------------------------------------------------------------------------
855 // wxThread static functions
856 // -----------------------------------------------------------------------------
858 wxThread
*wxThread::This()
860 return (wxThread
*)pthread_getspecific(gs_keySelf
);
863 bool wxThread::IsMain()
865 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
868 void wxThread::Yield()
870 #ifdef HAVE_SCHED_YIELD
875 void wxThread::Sleep(unsigned long milliseconds
)
877 wxUsleep(milliseconds
);
880 int wxThread::GetCPUCount()
882 #if defined(__LINUX__) && wxUSE_FFILE
883 // read from proc (can't use wxTextFile here because it's a special file:
884 // it has 0 size but still can be read from)
887 wxFFile
file(_T("/proc/cpuinfo"));
888 if ( file
.IsOpened() )
890 // slurp the whole file
892 if ( file
.ReadAll(&s
) )
894 // (ab)use Replace() to find the number of "processor" strings
895 size_t count
= s
.Replace(_T("processor"), _T(""));
901 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
905 wxLogDebug(_T("failed to read /proc/cpuinfo"));
908 #elif defined(_SC_NPROCESSORS_ONLN)
909 // this works for Solaris
910 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
915 #endif // different ways to get number of CPUs
921 bool wxThread::SetConcurrency(size_t level
)
923 #ifdef HAVE_THR_SETCONCURRENCY
924 int rc
= thr_setconcurrency(level
);
927 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
931 #else // !HAVE_THR_SETCONCURRENCY
932 // ok only for the default value
934 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
937 // -----------------------------------------------------------------------------
939 // -----------------------------------------------------------------------------
941 wxThread::wxThread(wxThreadKind kind
)
943 // add this thread to the global list of all threads
944 gs_allThreads
.Add(this);
946 m_internal
= new wxThreadInternal();
948 m_isDetached
= kind
== wxTHREAD_DETACHED
;
951 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
953 if ( m_internal
->GetState() != STATE_NEW
)
955 // don't recreate thread
956 return wxTHREAD_RUNNING
;
959 // set up the thread attribute: right now, we only set thread priority
961 pthread_attr_init(&attr
);
963 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
965 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
967 wxLogError(_("Cannot retrieve thread scheduling policy."));
971 /* the pthread.h contains too many spaces. This is a work-around */
972 # undef sched_get_priority_max
973 #undef sched_get_priority_min
974 #define sched_get_priority_max(_pol_) \
975 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
976 #define sched_get_priority_min(_pol_) \
977 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
980 int max_prio
= sched_get_priority_max(policy
),
981 min_prio
= sched_get_priority_min(policy
),
982 prio
= m_internal
->GetPriority();
984 if ( min_prio
== -1 || max_prio
== -1 )
986 wxLogError(_("Cannot get priority range for scheduling policy %d."),
989 else if ( max_prio
== min_prio
)
991 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
993 // notify the programmer that this doesn't work here
994 wxLogWarning(_("Thread priority setting is ignored."));
996 //else: we have default priority, so don't complain
998 // anyhow, don't do anything because priority is just ignored
1002 struct sched_param sp
;
1003 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1005 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1008 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1010 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1012 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1015 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1017 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1018 // this will make the threads created by this process really concurrent
1019 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1021 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1023 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1025 // VZ: assume that this one is always available (it's rather fundamental),
1026 // if this function is ever missing we should try to use
1027 // pthread_detach() instead (after thread creation)
1030 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1032 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1035 // never try to join detached threads
1036 m_internal
->Detach();
1038 //else: threads are created joinable by default, it's ok
1040 // create the new OS thread object
1041 int rc
= pthread_create
1043 m_internal
->GetIdPtr(),
1045 wxThreadInternal::PthreadStart
,
1049 if ( pthread_attr_destroy(&attr
) != 0 )
1051 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1056 m_internal
->SetState(STATE_EXITED
);
1058 return wxTHREAD_NO_RESOURCE
;
1061 return wxTHREAD_NO_ERROR
;
1064 wxThreadError
wxThread::Run()
1066 wxCriticalSectionLocker
lock(m_critsect
);
1068 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1069 wxT("must call wxThread::Create() first") );
1071 return m_internal
->Run();
1074 // -----------------------------------------------------------------------------
1076 // -----------------------------------------------------------------------------
1078 void wxThread::SetPriority(unsigned int prio
)
1080 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1081 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1082 wxT("invalid thread priority") );
1084 wxCriticalSectionLocker
lock(m_critsect
);
1086 switch ( m_internal
->GetState() )
1089 // thread not yet started, priority will be set when it is
1090 m_internal
->SetPriority(prio
);
1095 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1097 struct sched_param sparam
;
1098 sparam
.sched_priority
= prio
;
1100 if ( pthread_setschedparam(m_internal
->GetId(),
1101 SCHED_OTHER
, &sparam
) != 0 )
1103 wxLogError(_("Failed to set thread priority %d."), prio
);
1106 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1111 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1115 unsigned int wxThread::GetPriority() const
1117 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1119 return m_internal
->GetPriority();
1123 unsigned long long wxThread::GetId() const
1125 return (unsigned long long)m_internal
->GetId();
1127 unsigned long wxThread::GetId() const
1129 return (unsigned long)m_internal
->GetId();
1133 // -----------------------------------------------------------------------------
1135 // -----------------------------------------------------------------------------
1137 wxThreadError
wxThread::Pause()
1139 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1140 _T("a thread can't pause itself") );
1142 wxCriticalSectionLocker
lock(m_critsect
);
1144 if ( m_internal
->GetState() != STATE_RUNNING
)
1146 wxLogDebug(wxT("Can't pause thread which is not running."));
1148 return wxTHREAD_NOT_RUNNING
;
1151 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1154 // just set a flag, the thread will be really paused only during the next
1155 // call to TestDestroy()
1156 m_internal
->SetState(STATE_PAUSED
);
1158 return wxTHREAD_NO_ERROR
;
1161 wxThreadError
wxThread::Resume()
1163 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1164 _T("a thread can't resume itself") );
1166 wxCriticalSectionLocker
lock(m_critsect
);
1168 wxThreadState state
= m_internal
->GetState();
1173 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1176 m_internal
->Resume();
1178 return wxTHREAD_NO_ERROR
;
1181 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1183 return wxTHREAD_NO_ERROR
;
1186 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1188 return wxTHREAD_MISC_ERROR
;
1192 // -----------------------------------------------------------------------------
1194 // -----------------------------------------------------------------------------
1196 wxThread::ExitCode
wxThread::Wait()
1198 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1199 _T("a thread can't wait for itself") );
1201 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1202 _T("can't wait for detached thread") );
1206 return m_internal
->GetExitCode();
1209 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1211 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1212 _T("a thread can't delete itself") );
1215 wxThreadState state
= m_internal
->GetState();
1217 // ask the thread to stop
1218 m_internal
->SetCancelFlag();
1222 // detached threads won't broadcast about their termination by default
1223 // because usually nobody waits for them - but here we do, so ask the
1224 // thread to notify us
1225 m_internal
->Notify();
1233 // we need to wake up the thread so that PthreadStart() will
1234 // terminate - right now it's blocking on m_condRun
1235 m_internal
->SignalRun();
1244 // resume the thread first (don't call our Resume() because this
1245 // would dead lock when it tries to enter m_critsect)
1246 m_internal
->Resume();
1251 // wait until the thread stops
1256 wxASSERT_MSG( !m_isDetached
,
1257 _T("no return code for detached threads") );
1259 // if it's a joinable thread, it's not deleted yet
1260 *rc
= m_internal
->GetExitCode();
1264 return wxTHREAD_NO_ERROR
;
1267 wxThreadError
wxThread::Kill()
1269 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1270 _T("a thread can't kill itself") );
1272 switch ( m_internal
->GetState() )
1276 return wxTHREAD_NOT_RUNNING
;
1279 // resume the thread first
1285 #ifdef HAVE_PTHREAD_CANCEL
1286 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1289 wxLogError(_("Failed to terminate a thread."));
1291 return wxTHREAD_MISC_ERROR
;
1296 // if we use cleanup function, this will be done from
1297 // wxPthreadCleanup()
1298 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1299 ScheduleThreadForDeletion();
1301 // don't call OnExit() here, it can only be called in the
1302 // threads context and we're in the context of another thread
1305 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1309 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1312 return wxTHREAD_NO_ERROR
;
1316 void wxThread::Exit(ExitCode status
)
1318 wxASSERT_MSG( This() == this,
1319 _T("wxThread::Exit() can only be called in the "
1320 "context of the same thread") );
1322 // from the moment we call OnExit(), the main program may terminate at any
1323 // moment, so mark this thread as being already in process of being
1324 // deleted or wxThreadModule::OnExit() will try to delete it again
1325 ScheduleThreadForDeletion();
1327 // don't enter m_critsect before calling OnExit() because the user code
1328 // might deadlock if, for example, it signals a condition in OnExit() (a
1329 // common case) while the main thread calls any of functions entering
1330 // m_critsect on us (almost all of them do)
1333 // now do enter it because SignalExit() will change our state
1336 // next wake up the threads waiting for us (OTOH, this function won't return
1337 // until someone waited for us!)
1338 m_internal
->SignalExit();
1340 // leave the critical section before entering the dtor which tries to
1344 // delete C++ thread object if this is a detached thread - user is
1345 // responsible for doing this for joinable ones
1348 // FIXME I'm feeling bad about it - what if another thread function is
1349 // called (in another thread context) now? It will try to access
1350 // half destroyed object which will probably result in something
1351 // very bad - but we can't protect this by a crit section unless
1352 // we make it a global object, but this would mean that we can
1353 // only call one thread function at a time :-(
1357 // terminate the thread (pthread_exit() never returns)
1358 pthread_exit(status
);
1360 wxFAIL_MSG(_T("pthread_exit() failed"));
1363 // also test whether we were paused
1364 bool wxThread::TestDestroy()
1366 wxASSERT_MSG( This() == this,
1367 _T("wxThread::TestDestroy() can only be called in the "
1368 "context of the same thread") );
1372 if ( m_internal
->GetState() == STATE_PAUSED
)
1374 m_internal
->SetReallyPaused(TRUE
);
1376 // leave the crit section or the other threads will stop too if they
1377 // try to call any of (seemingly harmless) IsXXX() functions while we
1381 m_internal
->Pause();
1385 // thread wasn't requested to pause, nothing to do
1389 return m_internal
->WasCancelled();
1392 wxThread::~wxThread()
1397 // check that the thread either exited or couldn't be created
1398 if ( m_internal
->GetState() != STATE_EXITED
&&
1399 m_internal
->GetState() != STATE_NEW
)
1401 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1402 "running! The application may crash."), GetId());
1406 #endif // __WXDEBUG__
1410 // remove this thread from the global array
1411 gs_allThreads
.Remove(this);
1413 // detached thread will decrement this counter in DeleteThread(), but it
1414 // is not called for the joinable threads, so do it here
1415 if ( !m_isDetached
)
1417 MutexLock
lock(gs_mutexDeleteThread
);
1418 gs_nThreadsBeingDeleted
--;
1420 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1421 gs_nThreadsBeingDeleted
- 1);
1425 // -----------------------------------------------------------------------------
1427 // -----------------------------------------------------------------------------
1429 bool wxThread::IsRunning() const
1431 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1433 return m_internal
->GetState() == STATE_RUNNING
;
1436 bool wxThread::IsAlive() const
1438 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1440 switch ( m_internal
->GetState() )
1451 bool wxThread::IsPaused() const
1453 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1455 return (m_internal
->GetState() == STATE_PAUSED
);
1458 //--------------------------------------------------------------------
1460 //--------------------------------------------------------------------
1462 class wxThreadModule
: public wxModule
1465 virtual bool OnInit();
1466 virtual void OnExit();
1469 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1472 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1474 bool wxThreadModule::OnInit()
1476 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1479 wxLogSysError(rc
, _("Thread module initialization failed: "
1480 "failed to create thread key"));
1485 gs_tidMain
= pthread_self();
1488 gs_mutexGui
= new wxMutex();
1490 gs_mutexGui
->Lock();
1493 // under Solaris we get a warning from CC when using
1494 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1495 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1500 void wxThreadModule::OnExit()
1502 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1504 // are there any threads left which are being deleted right now?
1505 size_t nThreadsBeingDeleted
;
1507 MutexLock
lock(gs_mutexDeleteThread
);
1508 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1511 if ( nThreadsBeingDeleted
> 0 )
1513 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1514 nThreadsBeingDeleted
);
1516 // have to wait until all of them disappear
1517 gs_condAllDeleted
->Wait();
1520 // terminate any threads left
1521 size_t count
= gs_allThreads
.GetCount();
1524 wxLogDebug(wxT("%u threads were not terminated by the application."),
1528 for ( size_t n
= 0u; n
< count
; n
++ )
1530 // Delete calls the destructor which removes the current entry. We
1531 // should only delete the first one each time.
1532 gs_allThreads
[0]->Delete();
1536 // destroy GUI mutex
1537 gs_mutexGui
->Unlock();
1542 // and free TLD slot
1543 (void)pthread_key_delete(gs_keySelf
);
1546 // ----------------------------------------------------------------------------
1548 // ----------------------------------------------------------------------------
1550 static void ScheduleThreadForDeletion()
1552 MutexLock
lock(gs_mutexDeleteThread
);
1554 if ( gs_nThreadsBeingDeleted
== 0 )
1556 gs_condAllDeleted
= new wxCondition
;
1559 gs_nThreadsBeingDeleted
++;
1561 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1562 gs_nThreadsBeingDeleted
,
1563 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1566 static void DeleteThread(wxThread
*This
)
1568 // gs_mutexDeleteThread should be unlocked before signalling the condition
1569 // or wxThreadModule::OnExit() would deadlock
1571 MutexLock
lock(gs_mutexDeleteThread
);
1573 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1577 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1578 _T("no threads scheduled for deletion, yet we delete "
1582 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1583 gs_nThreadsBeingDeleted
- 1);
1585 if ( !--gs_nThreadsBeingDeleted
)
1587 // no more threads left, signal it
1588 gs_condAllDeleted
->Signal();
1590 delete gs_condAllDeleted
;
1591 gs_condAllDeleted
= (wxCondition
*)NULL
;
1595 void wxMutexGuiEnter()
1598 gs_mutexGui
->Lock();
1602 void wxMutexGuiLeave()
1605 gs_mutexGui
->Unlock();