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 pthread_mutex_init(&(m_internal
->m_mutex
),
168 (pthread_mutexattr_t
*) NULL
);
175 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
177 pthread_mutex_destroy( &(m_internal
->m_mutex
) );
181 wxMutexError
wxMutex::Lock()
183 int err
= pthread_mutex_lock( &(m_internal
->m_mutex
) );
186 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
188 return wxMUTEX_DEAD_LOCK
;
193 return wxMUTEX_NO_ERROR
;
196 wxMutexError
wxMutex::TryLock()
203 int err
= pthread_mutex_trylock( &(m_internal
->m_mutex
) );
206 case EBUSY
: return wxMUTEX_BUSY
;
211 return wxMUTEX_NO_ERROR
;
214 wxMutexError
wxMutex::Unlock()
222 wxLogDebug(wxT("Unlocking not locked mutex."));
224 return wxMUTEX_UNLOCKED
;
227 pthread_mutex_unlock( &(m_internal
->m_mutex
) );
229 return wxMUTEX_NO_ERROR
;
232 //--------------------------------------------------------------------
233 // wxCondition (Posix implementation)
234 //--------------------------------------------------------------------
236 // The native POSIX condition variables are dumb: if the condition is signaled
237 // before another thread starts to wait on it, the signal is lost and so this
238 // other thread will be never woken up. It's much more convenient to us to
239 // remember that the condition was signaled and to return from Wait()
240 // immediately in this case (this is more like Win32 automatic event objects)
242 class wxConditionInternal
245 wxConditionInternal();
246 ~wxConditionInternal();
249 bool WaitWithTimeout(const timespec
* ts
);
259 bool m_wasSignaled
; // TRUE if condition was signaled while
260 // nobody waited for it
261 size_t m_nWaiters
; // TRUE if someone already waits for us
263 pthread_mutex_t m_mutexProtect
; // protects access to vars above
265 pthread_mutex_t m_mutex
; // the mutex used with the condition
266 pthread_cond_t m_condition
; // the condition itself
269 wxConditionInternal::wxConditionInternal()
271 m_wasSignaled
= FALSE
;
274 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
276 // this is supposed to never happen
277 wxFAIL_MSG( _T("pthread_cond_init() failed") );
280 if ( pthread_mutex_init(&m_mutex
, (pthread_mutexattr_t
*)NULL
) != 0 ||
281 pthread_mutex_init(&m_mutexProtect
, NULL
) != 0 )
284 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
287 // initially the mutex is locked, so no thread can Signal() or Broadcast()
288 // until another thread starts to Wait()
289 if ( pthread_mutex_lock(&m_mutex
) != 0 )
291 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
295 wxConditionInternal::~wxConditionInternal()
297 if ( pthread_cond_destroy( &m_condition
) != 0 )
299 wxLogDebug(_T("Failed to destroy condition variable (some "
300 "threads are probably still waiting on it?)"));
303 if ( pthread_mutex_unlock( &m_mutex
) != 0 )
305 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
308 if ( pthread_mutex_destroy( &m_mutex
) != 0 ||
309 pthread_mutex_destroy( &m_mutexProtect
) != 0 )
311 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
315 void wxConditionInternal::WaitDone()
317 MutexLock
lock(m_mutexProtect
);
319 m_wasSignaled
= FALSE
;
323 bool wxConditionInternal::ShouldWait()
325 MutexLock
lock(m_mutexProtect
);
329 // the condition was signaled before we started to wait, reset the
331 m_wasSignaled
= FALSE
;
336 // we start to wait for it
342 bool wxConditionInternal::HasWaiters()
344 MutexLock
lock(m_mutexProtect
);
348 // someone waits for us, signal the condition normally
352 // nobody waits for us and may be never will - so just remember that the
353 // condition was signaled and don't do anything else
354 m_wasSignaled
= TRUE
;
359 void wxConditionInternal::Wait()
363 if ( pthread_cond_wait( &m_condition
, &m_mutex
) != 0 )
365 // not supposed to ever happen
366 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
373 bool wxConditionInternal::WaitWithTimeout(const timespec
* ts
)
379 switch ( pthread_cond_timedwait( &m_condition
, &m_mutex
, ts
) )
382 // condition signaled
387 wxLogDebug(_T("pthread_cond_timedwait() failed"));
393 // wait interrupted or timeout elapsed
399 // the condition had already been signaled before
408 void wxConditionInternal::Signal()
412 MutexLock
lock(m_mutex
);
414 if ( pthread_cond_signal( &m_condition
) != 0 )
416 // shouldn't ever happen
417 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
422 void wxConditionInternal::Broadcast()
426 MutexLock
lock(m_mutex
);
428 if ( pthread_cond_broadcast( &m_condition
) != 0 )
430 // shouldn't ever happen
431 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
436 wxCondition::wxCondition()
438 m_internal
= new wxConditionInternal
;
441 wxCondition::~wxCondition()
446 void wxCondition::Wait()
451 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
455 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
456 tspec
.tv_nsec
= nsec
;
458 return m_internal
->WaitWithTimeout(&tspec
);
461 void wxCondition::Signal()
463 m_internal
->Signal();
466 void wxCondition::Broadcast()
468 m_internal
->Broadcast();
471 //--------------------------------------------------------------------
472 // wxThread (Posix implementation)
473 //--------------------------------------------------------------------
475 class wxThreadInternal
481 // thread entry function
482 static void *PthreadStart(void *ptr
);
484 #if HAVE_THREAD_CLEANUP_FUNCTIONS
485 // thread exit function
486 static void PthreadCleanup(void *ptr
);
492 // ask the thread to terminate
494 // wake up threads waiting for our termination
496 // wake up threads waiting for our start
497 void SignalRun() { m_condRun
.Signal(); }
498 // go to sleep until Resume() is called
505 int GetPriority() const { return m_prio
; }
506 void SetPriority(int prio
) { m_prio
= prio
; }
508 wxThreadState
GetState() const { return m_state
; }
509 void SetState(wxThreadState state
) { m_state
= state
; }
511 pthread_t
GetId() const { return m_threadId
; }
512 pthread_t
*GetIdPtr() { return &m_threadId
; }
514 void SetCancelFlag() { m_cancelled
= TRUE
; }
515 bool WasCancelled() const { return m_cancelled
; }
517 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
518 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
521 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
522 bool IsReallyPaused() const { return m_isPaused
; }
524 // tell the thread that it is a detached one
527 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
530 // but even detached threads need to notifyus about their termination
531 // sometimes - tell the thread that it should do it
532 void Notify() { m_shouldBroadcast
= TRUE
; }
535 pthread_t m_threadId
; // id of the thread
536 wxThreadState m_state
; // see wxThreadState enum
537 int m_prio
; // in wxWindows units: from 0 to 100
539 // this flag is set when the thread should terminate
542 // this flag is set when the thread is blocking on m_condSuspend
545 // the thread exit code - only used for joinable (!detached) threads and
546 // is only valid after the thread termination
547 wxThread::ExitCode m_exitcode
;
549 // many threads may call Wait(), but only one of them should call
550 // pthread_join(), so we have to keep track of this
551 wxCriticalSection m_csJoinFlag
;
552 bool m_shouldBeJoined
;
553 bool m_shouldBroadcast
;
556 // VZ: it's possible that we might do with less than three different
557 // condition objects - for example, m_condRun and m_condEnd a priori
558 // won't be used in the same time. But for now I prefer this may be a
559 // bit less efficient but safer solution of having distinct condition
560 // variables for each purpose.
562 // this condition is signaled by Run() and the threads Entry() is not
563 // called before it is done
564 wxCondition m_condRun
;
566 // this one is signaled when the thread should resume after having been
568 wxCondition m_condSuspend
;
570 // finally this one is signalled when the thread exits
571 wxCondition m_condEnd
;
574 // ----------------------------------------------------------------------------
575 // thread startup and exit functions
576 // ----------------------------------------------------------------------------
578 void *wxThreadInternal::PthreadStart(void *ptr
)
580 wxThread
*thread
= (wxThread
*)ptr
;
581 wxThreadInternal
*pthread
= thread
->m_internal
;
583 // associate the thread pointer with the newly created thread so that
584 // wxThread::This() will work
585 int rc
= pthread_setspecific(gs_keySelf
, thread
);
588 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
593 // have to declare this before pthread_cleanup_push() which defines a
597 #if HAVE_THREAD_CLEANUP_FUNCTIONS
598 // install the cleanup handler which will be called if the thread is
600 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
601 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
603 // wait for the condition to be signaled from Run()
604 pthread
->m_condRun
.Wait();
606 // test whether we should run the run at all - may be it was deleted
607 // before it started to Run()?
609 wxCriticalSectionLocker
lock(thread
->m_critsect
);
611 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
612 pthread
->WasCancelled();
617 // call the main entry
618 pthread
->m_exitcode
= thread
->Entry();
620 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
624 wxCriticalSectionLocker
lock(thread
->m_critsect
);
626 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
629 // change the state of the thread to "exited" so that
630 // PthreadCleanup handler won't do anything from now (if it's
631 // called before we do pthread_cleanup_pop below)
632 pthread
->SetState(STATE_EXITED
);
636 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
637 // contains the matching '}' for the '{' in push, so they must be used
638 // in the same block!
639 #if HAVE_THREAD_CLEANUP_FUNCTIONS
640 // remove the cleanup handler without executing it
641 pthread_cleanup_pop(FALSE
);
642 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
648 return EXITCODE_CANCELLED
;
652 // terminate the thread
653 thread
->Exit(pthread
->m_exitcode
);
655 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
661 #if HAVE_THREAD_CLEANUP_FUNCTIONS
663 // this handler is called when the thread is cancelled
664 void wxThreadInternal::PthreadCleanup(void *ptr
)
666 wxThread
*thread
= (wxThread
*) ptr
;
669 wxCriticalSectionLocker
lock(thread
->m_critsect
);
670 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
672 // thread is already considered as finished.
677 // exit the thread gracefully
678 thread
->Exit(EXITCODE_CANCELLED
);
681 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
683 // ----------------------------------------------------------------------------
685 // ----------------------------------------------------------------------------
687 wxThreadInternal::wxThreadInternal()
691 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
695 // set to TRUE only when the thread starts waiting on m_condSuspend
698 // defaults for joinable threads
699 m_shouldBeJoined
= TRUE
;
700 m_shouldBroadcast
= TRUE
;
701 m_isDetached
= FALSE
;
704 wxThreadInternal::~wxThreadInternal()
708 wxThreadError
wxThreadInternal::Run()
710 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
711 wxT("thread may only be started once after Create()") );
715 SetState(STATE_RUNNING
);
717 return wxTHREAD_NO_ERROR
;
720 void wxThreadInternal::Wait()
722 // if the thread we're waiting for is waiting for the GUI mutex, we will
723 // deadlock so make sure we release it temporarily
724 if ( wxThread::IsMain() )
727 bool isDetached
= m_isDetached
;
728 long id
= (long)GetId();
729 wxLogTrace(TRACE_THREADS
, _T("Starting to wait for thread %ld to exit."),
732 // wait until the thread terminates (we're blocking in _another_ thread,
736 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
738 // we can't use any member variables any more if the thread is detached
739 // because it could be already deleted
742 // to avoid memory leaks we should call pthread_join(), but it must
744 wxCriticalSectionLocker
lock(m_csJoinFlag
);
746 if ( m_shouldBeJoined
)
748 // FIXME shouldn't we set cancellation type to DISABLED here? If
749 // we're cancelled inside pthread_join(), things will almost
750 // certainly break - but if we disable the cancellation, we
752 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
754 wxLogError(_("Failed to join a thread, potential memory leak "
755 "detected - please restart the program"));
758 m_shouldBeJoined
= FALSE
;
762 // reacquire GUI mutex
763 if ( wxThread::IsMain() )
767 void wxThreadInternal::SignalExit()
769 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
771 SetState(STATE_EXITED
);
773 // wake up all the threads waiting for our termination - if there are any
774 if ( m_shouldBroadcast
)
776 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
779 m_condEnd
.Broadcast();
783 void wxThreadInternal::Pause()
785 // the state is set from the thread which pauses us first, this function
786 // is called later so the state should have been already set
787 wxCHECK_RET( m_state
== STATE_PAUSED
,
788 wxT("thread must first be paused with wxThread::Pause().") );
790 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
792 // wait until the condition is signaled from Resume()
793 m_condSuspend
.Wait();
796 void wxThreadInternal::Resume()
798 wxCHECK_RET( m_state
== STATE_PAUSED
,
799 wxT("can't resume thread which is not suspended.") );
801 // the thread might be not actually paused yet - if there were no call to
802 // TestDestroy() since the last call to Pause() for example
803 if ( IsReallyPaused() )
805 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
808 m_condSuspend
.Signal();
811 SetReallyPaused(FALSE
);
815 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
819 SetState(STATE_RUNNING
);
822 // -----------------------------------------------------------------------------
823 // wxThread static functions
824 // -----------------------------------------------------------------------------
826 wxThread
*wxThread::This()
828 return (wxThread
*)pthread_getspecific(gs_keySelf
);
831 bool wxThread::IsMain()
833 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
836 void wxThread::Yield()
838 #ifdef HAVE_SCHED_YIELD
843 void wxThread::Sleep(unsigned long milliseconds
)
845 wxUsleep(milliseconds
);
848 int wxThread::GetCPUCount()
850 #if defined(__LINUX__)
851 // read from proc (can't use wxTextFile here because it's a special file:
852 // it has 0 size but still can be read from)
855 wxFFile
file(_T("/proc/cpuinfo"));
856 if ( file
.IsOpened() )
858 // slurp the whole file
860 if ( file
.ReadAll(&s
) )
862 // (ab)use Replace() to find the number of "processor" strings
863 size_t count
= s
.Replace(_T("processor"), _T(""));
869 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
873 wxLogDebug(_T("failed to read /proc/cpuinfo"));
876 #elif defined(_SC_NPROCESSORS_ONLN)
877 // this works for Solaris
878 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
883 #endif // different ways to get number of CPUs
889 bool wxThread::SetConcurrency(size_t level
)
891 #ifdef HAVE_THR_SETCONCURRENCY
892 int rc
= thr_setconcurrency(level
);
895 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
899 #else // !HAVE_THR_SETCONCURRENCY
900 // ok only for the default value
902 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
905 // -----------------------------------------------------------------------------
907 // -----------------------------------------------------------------------------
909 wxThread::wxThread(wxThreadKind kind
)
911 // add this thread to the global list of all threads
912 gs_allThreads
.Add(this);
914 m_internal
= new wxThreadInternal();
916 m_isDetached
= kind
== wxTHREAD_DETACHED
;
919 wxThreadError
wxThread::Create()
921 if ( m_internal
->GetState() != STATE_NEW
)
923 // don't recreate thread
924 return wxTHREAD_RUNNING
;
927 // set up the thread attribute: right now, we only set thread priority
929 pthread_attr_init(&attr
);
931 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
933 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
935 wxLogError(_("Cannot retrieve thread scheduling policy."));
939 /* the pthread.h contains too many spaces. This is a work-around */
940 # undef sched_get_priority_max
941 #undef sched_get_priority_min
942 #define sched_get_priority_max(_pol_) \
943 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
944 #define sched_get_priority_min(_pol_) \
945 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
948 int max_prio
= sched_get_priority_max(policy
),
949 min_prio
= sched_get_priority_min(policy
),
950 prio
= m_internal
->GetPriority();
952 if ( min_prio
== -1 || max_prio
== -1 )
954 wxLogError(_("Cannot get priority range for scheduling policy %d."),
957 else if ( max_prio
== min_prio
)
959 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
961 // notify the programmer that this doesn't work here
962 wxLogWarning(_("Thread priority setting is ignored."));
964 //else: we have default priority, so don't complain
966 // anyhow, don't do anything because priority is just ignored
970 struct sched_param sp
;
971 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
973 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
976 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
978 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
980 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
983 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
985 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
986 // this will make the threads created by this process really concurrent
987 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
989 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
991 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
993 // VZ: assume that this one is always available (it's rather fundamental),
994 // if this function is ever missing we should try to use
995 // pthread_detach() instead (after thread creation)
998 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1000 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1003 // never try to join detached threads
1004 m_internal
->Detach();
1006 //else: threads are created joinable by default, it's ok
1008 // create the new OS thread object
1009 int rc
= pthread_create
1011 m_internal
->GetIdPtr(),
1013 wxThreadInternal::PthreadStart
,
1017 if ( pthread_attr_destroy(&attr
) != 0 )
1019 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1024 m_internal
->SetState(STATE_EXITED
);
1026 return wxTHREAD_NO_RESOURCE
;
1029 return wxTHREAD_NO_ERROR
;
1032 wxThreadError
wxThread::Run()
1034 wxCriticalSectionLocker
lock(m_critsect
);
1036 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1037 wxT("must call wxThread::Create() first") );
1039 return m_internal
->Run();
1042 // -----------------------------------------------------------------------------
1044 // -----------------------------------------------------------------------------
1046 void wxThread::SetPriority(unsigned int prio
)
1048 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1049 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1050 wxT("invalid thread priority") );
1052 wxCriticalSectionLocker
lock(m_critsect
);
1054 switch ( m_internal
->GetState() )
1057 // thread not yet started, priority will be set when it is
1058 m_internal
->SetPriority(prio
);
1063 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1065 struct sched_param sparam
;
1066 sparam
.sched_priority
= prio
;
1068 if ( pthread_setschedparam(m_internal
->GetId(),
1069 SCHED_OTHER
, &sparam
) != 0 )
1071 wxLogError(_("Failed to set thread priority %d."), prio
);
1074 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1079 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1083 unsigned int wxThread::GetPriority() const
1085 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1087 return m_internal
->GetPriority();
1090 unsigned long wxThread::GetId() const
1092 return (unsigned long)m_internal
->GetId();
1095 // -----------------------------------------------------------------------------
1097 // -----------------------------------------------------------------------------
1099 wxThreadError
wxThread::Pause()
1101 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1102 _T("a thread can't pause itself") );
1104 wxCriticalSectionLocker
lock(m_critsect
);
1106 if ( m_internal
->GetState() != STATE_RUNNING
)
1108 wxLogDebug(wxT("Can't pause thread which is not running."));
1110 return wxTHREAD_NOT_RUNNING
;
1113 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1116 // just set a flag, the thread will be really paused only during the next
1117 // call to TestDestroy()
1118 m_internal
->SetState(STATE_PAUSED
);
1120 return wxTHREAD_NO_ERROR
;
1123 wxThreadError
wxThread::Resume()
1125 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1126 _T("a thread can't resume itself") );
1128 wxCriticalSectionLocker
lock(m_critsect
);
1130 wxThreadState state
= m_internal
->GetState();
1135 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1138 m_internal
->Resume();
1140 return wxTHREAD_NO_ERROR
;
1143 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1145 return wxTHREAD_NO_ERROR
;
1148 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1150 return wxTHREAD_MISC_ERROR
;
1154 // -----------------------------------------------------------------------------
1156 // -----------------------------------------------------------------------------
1158 wxThread::ExitCode
wxThread::Wait()
1160 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1161 _T("a thread can't wait for itself") );
1163 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1164 _T("can't wait for detached thread") );
1168 return m_internal
->GetExitCode();
1171 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1173 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1174 _T("a thread can't delete itself") );
1177 wxThreadState state
= m_internal
->GetState();
1179 // ask the thread to stop
1180 m_internal
->SetCancelFlag();
1184 // detached threads won't broadcast about their termination by default
1185 // because usually nobody waits for them - but here we do, so ask the
1186 // thread to notify us
1187 m_internal
->Notify();
1195 // we need to wake up the thread so that PthreadStart() will
1196 // terminate - right now it's blocking on m_condRun
1197 m_internal
->SignalRun();
1206 // resume the thread first (don't call our Resume() because this
1207 // would dead lock when it tries to enter m_critsect)
1208 m_internal
->Resume();
1213 // wait until the thread stops
1218 wxASSERT_MSG( !m_isDetached
,
1219 _T("no return code for detached threads") );
1221 // if it's a joinable thread, it's not deleted yet
1222 *rc
= m_internal
->GetExitCode();
1226 return wxTHREAD_NO_ERROR
;
1229 wxThreadError
wxThread::Kill()
1231 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1232 _T("a thread can't kill itself") );
1234 switch ( m_internal
->GetState() )
1238 return wxTHREAD_NOT_RUNNING
;
1241 // resume the thread first
1247 #ifdef HAVE_PTHREAD_CANCEL
1248 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1251 wxLogError(_("Failed to terminate a thread."));
1253 return wxTHREAD_MISC_ERROR
;
1258 // if we use cleanup function, this will be done from
1260 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1261 ScheduleThreadForDeletion();
1263 // don't call OnExit() here, it can only be called in the
1264 // threads context and we're in the context of another thread
1267 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1271 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1274 return wxTHREAD_NO_ERROR
;
1278 void wxThread::Exit(ExitCode status
)
1280 wxASSERT_MSG( This() == this,
1281 _T("wxThread::Exit() can only be called in the "
1282 "context of the same thread") );
1284 // from the moment we call OnExit(), the main program may terminate at any
1285 // moment, so mark this thread as being already in process of being
1286 // deleted or wxThreadModule::OnExit() will try to delete it again
1287 ScheduleThreadForDeletion();
1289 // don't enter m_critsect before calling OnExit() because the user code
1290 // might deadlock if, for example, it signals a condition in OnExit() (a
1291 // common case) while the main thread calls any of functions entering
1292 // m_critsect on us (almost all of them do)
1295 // now do enter it because SignalExit() will change our state
1298 // next wake up the threads waiting for us (OTOH, this function won't return
1299 // until someone waited for us!)
1300 m_internal
->SignalExit();
1302 // leave the critical section before entering the dtor which tries to
1306 // delete C++ thread object if this is a detached thread - user is
1307 // responsible for doing this for joinable ones
1310 // FIXME I'm feeling bad about it - what if another thread function is
1311 // called (in another thread context) now? It will try to access
1312 // half destroyed object which will probably result in something
1313 // very bad - but we can't protect this by a crit section unless
1314 // we make it a global object, but this would mean that we can
1315 // only call one thread function at a time :-(
1319 // terminate the thread (pthread_exit() never returns)
1320 pthread_exit(status
);
1322 wxFAIL_MSG(_T("pthread_exit() failed"));
1325 // also test whether we were paused
1326 bool wxThread::TestDestroy()
1328 wxASSERT_MSG( This() == this,
1329 _T("wxThread::TestDestroy() can only be called in the "
1330 "context of the same thread") );
1334 if ( m_internal
->GetState() == STATE_PAUSED
)
1336 m_internal
->SetReallyPaused(TRUE
);
1338 // leave the crit section or the other threads will stop too if they
1339 // try to call any of (seemingly harmless) IsXXX() functions while we
1343 m_internal
->Pause();
1347 // thread wasn't requested to pause, nothing to do
1351 return m_internal
->WasCancelled();
1354 wxThread::~wxThread()
1359 // check that the thread either exited or couldn't be created
1360 if ( m_internal
->GetState() != STATE_EXITED
&&
1361 m_internal
->GetState() != STATE_NEW
)
1363 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1364 "running! The application may crash."), GetId());
1368 #endif // __WXDEBUG__
1372 // remove this thread from the global array
1373 gs_allThreads
.Remove(this);
1375 // detached thread will decrement this counter in DeleteThread(), but it
1376 // is not called for the joinable threads, so do it here
1377 if ( !m_isDetached
)
1379 MutexLock
lock(gs_mutexDeleteThread
);
1380 gs_nThreadsBeingDeleted
--;
1382 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1383 gs_nThreadsBeingDeleted
- 1);
1387 // -----------------------------------------------------------------------------
1389 // -----------------------------------------------------------------------------
1391 bool wxThread::IsRunning() const
1393 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1395 return m_internal
->GetState() == STATE_RUNNING
;
1398 bool wxThread::IsAlive() const
1400 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1402 switch ( m_internal
->GetState() )
1413 bool wxThread::IsPaused() const
1415 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1417 return (m_internal
->GetState() == STATE_PAUSED
);
1420 //--------------------------------------------------------------------
1422 //--------------------------------------------------------------------
1424 class wxThreadModule
: public wxModule
1427 virtual bool OnInit();
1428 virtual void OnExit();
1431 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1434 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1436 bool wxThreadModule::OnInit()
1438 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1441 wxLogSysError(rc
, _("Thread module initialization failed: "
1442 "failed to create thread key"));
1447 gs_tidMain
= pthread_self();
1450 gs_mutexGui
= new wxMutex();
1452 gs_mutexGui
->Lock();
1455 // under Solaris we get a warning from CC when using
1456 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1457 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1462 void wxThreadModule::OnExit()
1464 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1466 // are there any threads left which are being deleted right now?
1467 size_t nThreadsBeingDeleted
;
1469 MutexLock
lock(gs_mutexDeleteThread
);
1470 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1473 if ( nThreadsBeingDeleted
> 0 )
1475 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1476 nThreadsBeingDeleted
);
1478 // have to wait until all of them disappear
1479 gs_condAllDeleted
->Wait();
1482 // terminate any threads left
1483 size_t count
= gs_allThreads
.GetCount();
1486 wxLogDebug(wxT("%u threads were not terminated by the application."),
1490 for ( size_t n
= 0u; n
< count
; n
++ )
1492 // Delete calls the destructor which removes the current entry. We
1493 // should only delete the first one each time.
1494 gs_allThreads
[0]->Delete();
1498 // destroy GUI mutex
1499 gs_mutexGui
->Unlock();
1504 // and free TLD slot
1505 (void)pthread_key_delete(gs_keySelf
);
1508 // ----------------------------------------------------------------------------
1510 // ----------------------------------------------------------------------------
1512 static void ScheduleThreadForDeletion()
1514 MutexLock
lock(gs_mutexDeleteThread
);
1516 if ( gs_nThreadsBeingDeleted
== 0 )
1518 gs_condAllDeleted
= new wxCondition
;
1521 gs_nThreadsBeingDeleted
++;
1523 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1524 gs_nThreadsBeingDeleted
,
1525 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1528 static void DeleteThread(wxThread
*This
)
1530 // gs_mutexDeleteThread should be unlocked before signalling the condition
1531 // or wxThreadModule::OnExit() would deadlock
1533 MutexLock
lock(gs_mutexDeleteThread
);
1535 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1539 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1540 _T("no threads scheduled for deletion, yet we delete "
1544 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1545 gs_nThreadsBeingDeleted
- 1);
1547 if ( !--gs_nThreadsBeingDeleted
)
1549 // no more threads left, signal it
1550 gs_condAllDeleted
->Signal();
1552 delete gs_condAllDeleted
;
1553 gs_condAllDeleted
= (wxCondition
*)NULL
;
1557 void wxMutexGuiEnter()
1560 gs_mutexGui
->Lock();
1564 void wxMutexGuiLeave()
1567 gs_mutexGui
->Unlock();