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 class wxThreadInternal
499 // thread entry function
500 static void *PthreadStart(void *ptr
);
502 #if HAVE_THREAD_CLEANUP_FUNCTIONS
503 // thread exit function
504 static void PthreadCleanup(void *ptr
);
510 // ask the thread to terminate
512 // wake up threads waiting for our termination
514 // wake up threads waiting for our start
515 void SignalRun() { m_condRun
.Signal(); }
516 // go to sleep until Resume() is called
523 int GetPriority() const { return m_prio
; }
524 void SetPriority(int prio
) { m_prio
= prio
; }
526 wxThreadState
GetState() const { return m_state
; }
527 void SetState(wxThreadState state
) { m_state
= state
; }
529 pthread_t
GetId() const { return m_threadId
; }
530 pthread_t
*GetIdPtr() { return &m_threadId
; }
532 void SetCancelFlag() { m_cancelled
= TRUE
; }
533 bool WasCancelled() const { return m_cancelled
; }
535 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
536 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
539 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
540 bool IsReallyPaused() const { return m_isPaused
; }
542 // tell the thread that it is a detached one
545 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
548 // but even detached threads need to notifyus about their termination
549 // sometimes - tell the thread that it should do it
550 void Notify() { m_shouldBroadcast
= TRUE
; }
553 pthread_t m_threadId
; // id of the thread
554 wxThreadState m_state
; // see wxThreadState enum
555 int m_prio
; // in wxWindows units: from 0 to 100
557 // this flag is set when the thread should terminate
560 // this flag is set when the thread is blocking on m_condSuspend
563 // the thread exit code - only used for joinable (!detached) threads and
564 // is only valid after the thread termination
565 wxThread::ExitCode m_exitcode
;
567 // many threads may call Wait(), but only one of them should call
568 // pthread_join(), so we have to keep track of this
569 wxCriticalSection m_csJoinFlag
;
570 bool m_shouldBeJoined
;
571 bool m_shouldBroadcast
;
574 // VZ: it's possible that we might do with less than three different
575 // condition objects - for example, m_condRun and m_condEnd a priori
576 // won't be used in the same time. But for now I prefer this may be a
577 // bit less efficient but safer solution of having distinct condition
578 // variables for each purpose.
580 // this condition is signaled by Run() and the threads Entry() is not
581 // called before it is done
582 wxCondition m_condRun
;
584 // this one is signaled when the thread should resume after having been
586 wxCondition m_condSuspend
;
588 // finally this one is signalled when the thread exits
589 wxCondition m_condEnd
;
592 // ----------------------------------------------------------------------------
593 // thread startup and exit functions
594 // ----------------------------------------------------------------------------
596 void *wxThreadInternal::PthreadStart(void *ptr
)
598 wxThread
*thread
= (wxThread
*)ptr
;
599 wxThreadInternal
*pthread
= thread
->m_internal
;
601 // associate the thread pointer with the newly created thread so that
602 // wxThread::This() will work
603 int rc
= pthread_setspecific(gs_keySelf
, thread
);
606 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
611 // have to declare this before pthread_cleanup_push() which defines a
615 #if HAVE_THREAD_CLEANUP_FUNCTIONS
616 // install the cleanup handler which will be called if the thread is
618 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
619 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
621 // wait for the condition to be signaled from Run()
622 pthread
->m_condRun
.Wait();
624 // test whether we should run the run at all - may be it was deleted
625 // before it started to Run()?
627 wxCriticalSectionLocker
lock(thread
->m_critsect
);
629 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
630 pthread
->WasCancelled();
635 // call the main entry
636 pthread
->m_exitcode
= thread
->Entry();
638 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
642 wxCriticalSectionLocker
lock(thread
->m_critsect
);
644 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
647 // change the state of the thread to "exited" so that
648 // PthreadCleanup handler won't do anything from now (if it's
649 // called before we do pthread_cleanup_pop below)
650 pthread
->SetState(STATE_EXITED
);
654 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
655 // contains the matching '}' for the '{' in push, so they must be used
656 // in the same block!
657 #if HAVE_THREAD_CLEANUP_FUNCTIONS
658 // remove the cleanup handler without executing it
659 pthread_cleanup_pop(FALSE
);
660 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
666 return EXITCODE_CANCELLED
;
670 // terminate the thread
671 thread
->Exit(pthread
->m_exitcode
);
673 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
679 #if HAVE_THREAD_CLEANUP_FUNCTIONS
681 // this handler is called when the thread is cancelled
682 void wxThreadInternal::PthreadCleanup(void *ptr
)
684 wxThread
*thread
= (wxThread
*) ptr
;
687 wxCriticalSectionLocker
lock(thread
->m_critsect
);
688 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
690 // thread is already considered as finished.
695 // exit the thread gracefully
696 thread
->Exit(EXITCODE_CANCELLED
);
699 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
701 // ----------------------------------------------------------------------------
703 // ----------------------------------------------------------------------------
705 wxThreadInternal::wxThreadInternal()
709 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
713 // set to TRUE only when the thread starts waiting on m_condSuspend
716 // defaults for joinable threads
717 m_shouldBeJoined
= TRUE
;
718 m_shouldBroadcast
= TRUE
;
719 m_isDetached
= FALSE
;
722 wxThreadInternal::~wxThreadInternal()
726 wxThreadError
wxThreadInternal::Run()
728 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
729 wxT("thread may only be started once after Create()") );
733 SetState(STATE_RUNNING
);
735 return wxTHREAD_NO_ERROR
;
738 void wxThreadInternal::Wait()
740 // if the thread we're waiting for is waiting for the GUI mutex, we will
741 // deadlock so make sure we release it temporarily
742 if ( wxThread::IsMain() )
745 bool isDetached
= m_isDetached
;
746 long id
= (long)GetId();
747 wxLogTrace(TRACE_THREADS
, _T("Starting to wait for thread %ld to exit."),
750 // wait until the thread terminates (we're blocking in _another_ thread,
754 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
756 // we can't use any member variables any more if the thread is detached
757 // because it could be already deleted
760 // to avoid memory leaks we should call pthread_join(), but it must
762 wxCriticalSectionLocker
lock(m_csJoinFlag
);
764 if ( m_shouldBeJoined
)
766 // FIXME shouldn't we set cancellation type to DISABLED here? If
767 // we're cancelled inside pthread_join(), things will almost
768 // certainly break - but if we disable the cancellation, we
770 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
772 wxLogError(_("Failed to join a thread, potential memory leak "
773 "detected - please restart the program"));
776 m_shouldBeJoined
= FALSE
;
780 // reacquire GUI mutex
781 if ( wxThread::IsMain() )
785 void wxThreadInternal::SignalExit()
787 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
789 SetState(STATE_EXITED
);
791 // wake up all the threads waiting for our termination - if there are any
792 if ( m_shouldBroadcast
)
794 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
797 m_condEnd
.Broadcast();
801 void wxThreadInternal::Pause()
803 // the state is set from the thread which pauses us first, this function
804 // is called later so the state should have been already set
805 wxCHECK_RET( m_state
== STATE_PAUSED
,
806 wxT("thread must first be paused with wxThread::Pause().") );
808 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
810 // wait until the condition is signaled from Resume()
811 m_condSuspend
.Wait();
814 void wxThreadInternal::Resume()
816 wxCHECK_RET( m_state
== STATE_PAUSED
,
817 wxT("can't resume thread which is not suspended.") );
819 // the thread might be not actually paused yet - if there were no call to
820 // TestDestroy() since the last call to Pause() for example
821 if ( IsReallyPaused() )
823 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
826 m_condSuspend
.Signal();
829 SetReallyPaused(FALSE
);
833 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
837 SetState(STATE_RUNNING
);
840 // -----------------------------------------------------------------------------
841 // wxThread static functions
842 // -----------------------------------------------------------------------------
844 wxThread
*wxThread::This()
846 return (wxThread
*)pthread_getspecific(gs_keySelf
);
849 bool wxThread::IsMain()
851 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
854 void wxThread::Yield()
856 #ifdef HAVE_SCHED_YIELD
861 void wxThread::Sleep(unsigned long milliseconds
)
863 wxUsleep(milliseconds
);
866 int wxThread::GetCPUCount()
868 #if defined(__LINUX__) && wxUSE_FFILE
869 // read from proc (can't use wxTextFile here because it's a special file:
870 // it has 0 size but still can be read from)
873 wxFFile
file(_T("/proc/cpuinfo"));
874 if ( file
.IsOpened() )
876 // slurp the whole file
878 if ( file
.ReadAll(&s
) )
880 // (ab)use Replace() to find the number of "processor" strings
881 size_t count
= s
.Replace(_T("processor"), _T(""));
887 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
891 wxLogDebug(_T("failed to read /proc/cpuinfo"));
894 #elif defined(_SC_NPROCESSORS_ONLN)
895 // this works for Solaris
896 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
901 #endif // different ways to get number of CPUs
907 bool wxThread::SetConcurrency(size_t level
)
909 #ifdef HAVE_THR_SETCONCURRENCY
910 int rc
= thr_setconcurrency(level
);
913 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
917 #else // !HAVE_THR_SETCONCURRENCY
918 // ok only for the default value
920 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
923 // -----------------------------------------------------------------------------
925 // -----------------------------------------------------------------------------
927 wxThread::wxThread(wxThreadKind kind
)
929 // add this thread to the global list of all threads
930 gs_allThreads
.Add(this);
932 m_internal
= new wxThreadInternal();
934 m_isDetached
= kind
== wxTHREAD_DETACHED
;
937 wxThreadError
wxThread::Create()
939 if ( m_internal
->GetState() != STATE_NEW
)
941 // don't recreate thread
942 return wxTHREAD_RUNNING
;
945 // set up the thread attribute: right now, we only set thread priority
947 pthread_attr_init(&attr
);
949 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
951 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
953 wxLogError(_("Cannot retrieve thread scheduling policy."));
957 /* the pthread.h contains too many spaces. This is a work-around */
958 # undef sched_get_priority_max
959 #undef sched_get_priority_min
960 #define sched_get_priority_max(_pol_) \
961 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
962 #define sched_get_priority_min(_pol_) \
963 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
966 int max_prio
= sched_get_priority_max(policy
),
967 min_prio
= sched_get_priority_min(policy
),
968 prio
= m_internal
->GetPriority();
970 if ( min_prio
== -1 || max_prio
== -1 )
972 wxLogError(_("Cannot get priority range for scheduling policy %d."),
975 else if ( max_prio
== min_prio
)
977 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
979 // notify the programmer that this doesn't work here
980 wxLogWarning(_("Thread priority setting is ignored."));
982 //else: we have default priority, so don't complain
984 // anyhow, don't do anything because priority is just ignored
988 struct sched_param sp
;
989 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
991 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
994 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
996 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
998 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1001 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1003 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1004 // this will make the threads created by this process really concurrent
1005 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1007 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1009 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1011 // VZ: assume that this one is always available (it's rather fundamental),
1012 // if this function is ever missing we should try to use
1013 // pthread_detach() instead (after thread creation)
1016 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1018 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1021 // never try to join detached threads
1022 m_internal
->Detach();
1024 //else: threads are created joinable by default, it's ok
1026 // create the new OS thread object
1027 int rc
= pthread_create
1029 m_internal
->GetIdPtr(),
1031 wxThreadInternal::PthreadStart
,
1035 if ( pthread_attr_destroy(&attr
) != 0 )
1037 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1042 m_internal
->SetState(STATE_EXITED
);
1044 return wxTHREAD_NO_RESOURCE
;
1047 return wxTHREAD_NO_ERROR
;
1050 wxThreadError
wxThread::Run()
1052 wxCriticalSectionLocker
lock(m_critsect
);
1054 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1055 wxT("must call wxThread::Create() first") );
1057 return m_internal
->Run();
1060 // -----------------------------------------------------------------------------
1062 // -----------------------------------------------------------------------------
1064 void wxThread::SetPriority(unsigned int prio
)
1066 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1067 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1068 wxT("invalid thread priority") );
1070 wxCriticalSectionLocker
lock(m_critsect
);
1072 switch ( m_internal
->GetState() )
1075 // thread not yet started, priority will be set when it is
1076 m_internal
->SetPriority(prio
);
1081 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1083 struct sched_param sparam
;
1084 sparam
.sched_priority
= prio
;
1086 if ( pthread_setschedparam(m_internal
->GetId(),
1087 SCHED_OTHER
, &sparam
) != 0 )
1089 wxLogError(_("Failed to set thread priority %d."), prio
);
1092 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1097 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1101 unsigned int wxThread::GetPriority() const
1103 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1105 return m_internal
->GetPriority();
1108 unsigned long wxThread::GetId() const
1110 return (unsigned long)m_internal
->GetId();
1113 // -----------------------------------------------------------------------------
1115 // -----------------------------------------------------------------------------
1117 wxThreadError
wxThread::Pause()
1119 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1120 _T("a thread can't pause itself") );
1122 wxCriticalSectionLocker
lock(m_critsect
);
1124 if ( m_internal
->GetState() != STATE_RUNNING
)
1126 wxLogDebug(wxT("Can't pause thread which is not running."));
1128 return wxTHREAD_NOT_RUNNING
;
1131 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1134 // just set a flag, the thread will be really paused only during the next
1135 // call to TestDestroy()
1136 m_internal
->SetState(STATE_PAUSED
);
1138 return wxTHREAD_NO_ERROR
;
1141 wxThreadError
wxThread::Resume()
1143 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1144 _T("a thread can't resume itself") );
1146 wxCriticalSectionLocker
lock(m_critsect
);
1148 wxThreadState state
= m_internal
->GetState();
1153 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1156 m_internal
->Resume();
1158 return wxTHREAD_NO_ERROR
;
1161 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1163 return wxTHREAD_NO_ERROR
;
1166 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1168 return wxTHREAD_MISC_ERROR
;
1172 // -----------------------------------------------------------------------------
1174 // -----------------------------------------------------------------------------
1176 wxThread::ExitCode
wxThread::Wait()
1178 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1179 _T("a thread can't wait for itself") );
1181 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1182 _T("can't wait for detached thread") );
1186 return m_internal
->GetExitCode();
1189 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1191 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1192 _T("a thread can't delete itself") );
1195 wxThreadState state
= m_internal
->GetState();
1197 // ask the thread to stop
1198 m_internal
->SetCancelFlag();
1202 // detached threads won't broadcast about their termination by default
1203 // because usually nobody waits for them - but here we do, so ask the
1204 // thread to notify us
1205 m_internal
->Notify();
1213 // we need to wake up the thread so that PthreadStart() will
1214 // terminate - right now it's blocking on m_condRun
1215 m_internal
->SignalRun();
1224 // resume the thread first (don't call our Resume() because this
1225 // would dead lock when it tries to enter m_critsect)
1226 m_internal
->Resume();
1231 // wait until the thread stops
1236 wxASSERT_MSG( !m_isDetached
,
1237 _T("no return code for detached threads") );
1239 // if it's a joinable thread, it's not deleted yet
1240 *rc
= m_internal
->GetExitCode();
1244 return wxTHREAD_NO_ERROR
;
1247 wxThreadError
wxThread::Kill()
1249 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1250 _T("a thread can't kill itself") );
1252 switch ( m_internal
->GetState() )
1256 return wxTHREAD_NOT_RUNNING
;
1259 // resume the thread first
1265 #ifdef HAVE_PTHREAD_CANCEL
1266 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1269 wxLogError(_("Failed to terminate a thread."));
1271 return wxTHREAD_MISC_ERROR
;
1276 // if we use cleanup function, this will be done from
1278 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1279 ScheduleThreadForDeletion();
1281 // don't call OnExit() here, it can only be called in the
1282 // threads context and we're in the context of another thread
1285 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1289 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1292 return wxTHREAD_NO_ERROR
;
1296 void wxThread::Exit(ExitCode status
)
1298 wxASSERT_MSG( This() == this,
1299 _T("wxThread::Exit() can only be called in the "
1300 "context of the same thread") );
1302 // from the moment we call OnExit(), the main program may terminate at any
1303 // moment, so mark this thread as being already in process of being
1304 // deleted or wxThreadModule::OnExit() will try to delete it again
1305 ScheduleThreadForDeletion();
1307 // don't enter m_critsect before calling OnExit() because the user code
1308 // might deadlock if, for example, it signals a condition in OnExit() (a
1309 // common case) while the main thread calls any of functions entering
1310 // m_critsect on us (almost all of them do)
1313 // now do enter it because SignalExit() will change our state
1316 // next wake up the threads waiting for us (OTOH, this function won't return
1317 // until someone waited for us!)
1318 m_internal
->SignalExit();
1320 // leave the critical section before entering the dtor which tries to
1324 // delete C++ thread object if this is a detached thread - user is
1325 // responsible for doing this for joinable ones
1328 // FIXME I'm feeling bad about it - what if another thread function is
1329 // called (in another thread context) now? It will try to access
1330 // half destroyed object which will probably result in something
1331 // very bad - but we can't protect this by a crit section unless
1332 // we make it a global object, but this would mean that we can
1333 // only call one thread function at a time :-(
1337 // terminate the thread (pthread_exit() never returns)
1338 pthread_exit(status
);
1340 wxFAIL_MSG(_T("pthread_exit() failed"));
1343 // also test whether we were paused
1344 bool wxThread::TestDestroy()
1346 wxASSERT_MSG( This() == this,
1347 _T("wxThread::TestDestroy() can only be called in the "
1348 "context of the same thread") );
1352 if ( m_internal
->GetState() == STATE_PAUSED
)
1354 m_internal
->SetReallyPaused(TRUE
);
1356 // leave the crit section or the other threads will stop too if they
1357 // try to call any of (seemingly harmless) IsXXX() functions while we
1361 m_internal
->Pause();
1365 // thread wasn't requested to pause, nothing to do
1369 return m_internal
->WasCancelled();
1372 wxThread::~wxThread()
1377 // check that the thread either exited or couldn't be created
1378 if ( m_internal
->GetState() != STATE_EXITED
&&
1379 m_internal
->GetState() != STATE_NEW
)
1381 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1382 "running! The application may crash."), GetId());
1386 #endif // __WXDEBUG__
1390 // remove this thread from the global array
1391 gs_allThreads
.Remove(this);
1393 // detached thread will decrement this counter in DeleteThread(), but it
1394 // is not called for the joinable threads, so do it here
1395 if ( !m_isDetached
)
1397 MutexLock
lock(gs_mutexDeleteThread
);
1398 gs_nThreadsBeingDeleted
--;
1400 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1401 gs_nThreadsBeingDeleted
- 1);
1405 // -----------------------------------------------------------------------------
1407 // -----------------------------------------------------------------------------
1409 bool wxThread::IsRunning() const
1411 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1413 return m_internal
->GetState() == STATE_RUNNING
;
1416 bool wxThread::IsAlive() const
1418 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1420 switch ( m_internal
->GetState() )
1431 bool wxThread::IsPaused() const
1433 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1435 return (m_internal
->GetState() == STATE_PAUSED
);
1438 //--------------------------------------------------------------------
1440 //--------------------------------------------------------------------
1442 class wxThreadModule
: public wxModule
1445 virtual bool OnInit();
1446 virtual void OnExit();
1449 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1452 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1454 bool wxThreadModule::OnInit()
1456 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1459 wxLogSysError(rc
, _("Thread module initialization failed: "
1460 "failed to create thread key"));
1465 gs_tidMain
= pthread_self();
1468 gs_mutexGui
= new wxMutex();
1470 gs_mutexGui
->Lock();
1473 // under Solaris we get a warning from CC when using
1474 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1475 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1480 void wxThreadModule::OnExit()
1482 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1484 // are there any threads left which are being deleted right now?
1485 size_t nThreadsBeingDeleted
;
1487 MutexLock
lock(gs_mutexDeleteThread
);
1488 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1491 if ( nThreadsBeingDeleted
> 0 )
1493 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1494 nThreadsBeingDeleted
);
1496 // have to wait until all of them disappear
1497 gs_condAllDeleted
->Wait();
1500 // terminate any threads left
1501 size_t count
= gs_allThreads
.GetCount();
1504 wxLogDebug(wxT("%u threads were not terminated by the application."),
1508 for ( size_t n
= 0u; n
< count
; n
++ )
1510 // Delete calls the destructor which removes the current entry. We
1511 // should only delete the first one each time.
1512 gs_allThreads
[0]->Delete();
1516 // destroy GUI mutex
1517 gs_mutexGui
->Unlock();
1522 // and free TLD slot
1523 (void)pthread_key_delete(gs_keySelf
);
1526 // ----------------------------------------------------------------------------
1528 // ----------------------------------------------------------------------------
1530 static void ScheduleThreadForDeletion()
1532 MutexLock
lock(gs_mutexDeleteThread
);
1534 if ( gs_nThreadsBeingDeleted
== 0 )
1536 gs_condAllDeleted
= new wxCondition
;
1539 gs_nThreadsBeingDeleted
++;
1541 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1542 gs_nThreadsBeingDeleted
,
1543 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1546 static void DeleteThread(wxThread
*This
)
1548 // gs_mutexDeleteThread should be unlocked before signalling the condition
1549 // or wxThreadModule::OnExit() would deadlock
1551 MutexLock
lock(gs_mutexDeleteThread
);
1553 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1557 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1558 _T("no threads scheduled for deletion, yet we delete "
1562 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1563 gs_nThreadsBeingDeleted
- 1);
1565 if ( !--gs_nThreadsBeingDeleted
)
1567 // no more threads left, signal it
1568 gs_condAllDeleted
->Signal();
1570 delete gs_condAllDeleted
;
1571 gs_condAllDeleted
= (wxCondition
*)NULL
;
1575 void wxMutexGuiEnter()
1578 gs_mutexGui
->Lock();
1582 void wxMutexGuiLeave()
1585 gs_mutexGui
->Unlock();