1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // Licence: wxWindows licence
13 /////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
24 #pragma implementation "thread.h"
31 #include "wx/thread.h"
32 #include "wx/module.h"
36 #include "wx/dynarray.h"
47 #ifdef HAVE_THR_SETCONCURRENCY
51 // we use wxFFile under Linux in GetCPUCount()
56 // ----------------------------------------------------------------------------
58 // ----------------------------------------------------------------------------
60 // the possible states of the thread and transitions from them
63 STATE_NEW
, // didn't start execution yet (=> RUNNING)
64 STATE_RUNNING
, // running (=> PAUSED or EXITED)
65 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
66 STATE_EXITED
// thread doesn't exist any more
69 // the exit value of a thread which has been cancelled
70 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
73 #define TRACE_THREADS _T("thread")
75 // ----------------------------------------------------------------------------
76 // pseudo template types
77 // ----------------------------------------------------------------------------
79 WX_DECLARE_LIST(pthread_mutex_t
, wxMutexList
);
81 #include "wx/listimpl.cpp"
82 WX_DEFINE_LIST(wxMutexList
);
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 static void ScheduleThreadForDeletion();
89 static void DeleteThread(wxThread
*This
);
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 // same as wxMutexLocker but for "native" mutex
99 MutexLock(pthread_mutex_t
& mutex
)
102 if ( pthread_mutex_lock(m_mutex
) != 0 )
104 wxLogDebug(_T("pthread_mutex_lock() failed"));
110 if ( pthread_mutex_unlock(m_mutex
) != 0 )
112 wxLogDebug(_T("pthread_mutex_unlock() failed"));
117 pthread_mutex_t
*m_mutex
;
120 // ----------------------------------------------------------------------------
122 // ----------------------------------------------------------------------------
124 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
126 // -----------------------------------------------------------------------------
128 // -----------------------------------------------------------------------------
130 // we keep the list of all threads created by the application to be able to
131 // terminate them on exit if there are some left - otherwise the process would
133 static wxArrayThread gs_allThreads
;
135 // the id of the main thread
136 static pthread_t gs_tidMain
;
138 // the key for the pointer to the associated wxThread object
139 static pthread_key_t gs_keySelf
;
141 // the number of threads which are being deleted - the program won't exit
142 // until there are any left
143 static size_t gs_nThreadsBeingDeleted
= 0;
145 // a mutex to protect gs_nThreadsBeingDeleted
146 static pthread_mutex_t gs_mutexDeleteThread
;
148 // and a condition variable which will be signaled when all
149 // gs_nThreadsBeingDeleted will have been deleted
150 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
153 // this mutex must be acquired before any call to a GUI function
154 static wxMutex
*gs_mutexGui
;
157 // ============================================================================
158 // wxMutex implementation
159 // ============================================================================
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 class wxMutexInternal
172 wxMutexError
TryLock();
173 wxMutexError
Unlock();
176 pthread_mutex_t m_mutex
;
179 wxMutexInternal::wxMutexInternal()
181 // support recursive locks like Win32, i.e. a thread can lock a mutex which
182 // it had itself already locked
184 // but initialization of recursive mutexes is non portable <sigh>, so try
186 #ifdef HAVE_PTHREAD_MUTEXATTR_T
187 pthread_mutexattr_t attr
;
188 pthread_mutexattr_init(&attr
);
189 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
191 pthread_mutex_init(&m_mutex
, &attr
);
192 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
193 // we can use this only as initializer so we have to assign it first to a
194 // temp var - assigning directly to m_mutex wouldn't even compile
195 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
197 #else // no recursive mutexes
198 pthread_mutex_init(&m_mutex
, NULL
);
200 // used by TryLock() below
201 #define NO_RECURSIVE_MUTEXES
202 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
205 wxMutexInternal::~wxMutexInternal()
207 pthread_mutex_destroy(&m_mutex
);
210 wxMutexError
wxMutexInternal::Lock()
212 int err
= pthread_mutex_lock(&m_mutex
);
216 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
217 return wxMUTEX_DEAD_LOCK
;
220 wxFAIL_MSG( _T("unexpected pthread_mutex_lock() return") );
224 wxLogDebug(_T("Failed to lock the mutex."));
225 return wxMUTEX_MISC_ERROR
;
228 return wxMUTEX_NO_ERROR
;
232 wxMutexError
wxMutexInternal::TryLock()
234 int err
= pthread_mutex_trylock(&m_mutex
);
241 wxFAIL_MSG( _T("unexpected pthread_mutex_trylock() return") );
245 wxLogDebug(_T("Failed to try to lock the mutex."));
246 return wxMUTEX_MISC_ERROR
;
249 return wxMUTEX_NO_ERROR
;
253 wxMutexError
wxMutexInternal::Unlock()
255 int err
= pthread_mutex_unlock(&m_mutex
);
259 // we don't own the mutex
260 return wxMUTEX_UNLOCKED
;
263 wxFAIL_MSG( _T("unexpected pthread_mutex_unlock() return") );
267 wxLogDebug(_T("Failed to unlock the mutex."));
268 return wxMUTEX_MISC_ERROR
;
271 return wxMUTEX_NO_ERROR
;
275 // ----------------------------------------------------------------------------
277 // ----------------------------------------------------------------------------
279 // TODO: this is completely generic, move it to common code?
283 m_internal
= new wxMutexInternal
;
291 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked
);
296 wxMutexError
wxMutex::Lock()
298 wxMutexError err
= m_internal
->Lock();
308 wxMutexError
wxMutex::TryLock()
312 #ifdef NO_RECURSIVE_MUTEXES
313 return wxMUTEX_DEAD_LOCK
;
314 #else // have recursive mutexes on this platform
315 // we will succeed in locking it when we have it already locked
316 return wxMUTEX_NO_ERROR
;
317 #endif // recursive/non-recursive mutexes
320 wxMutexError err
= m_internal
->TryLock();
329 wxMutexError
wxMutex::Unlock()
337 wxLogDebug(wxT("Unlocking not locked mutex."));
339 return wxMUTEX_UNLOCKED
;
342 return m_internal
->Unlock();
345 // ============================================================================
346 // wxCondition implementation
347 // ============================================================================
349 // ----------------------------------------------------------------------------
350 // wxConditionInternal
351 // ----------------------------------------------------------------------------
353 // The native POSIX condition variables are dumb: if the condition is signaled
354 // before another thread starts to wait on it, the signal is lost and so this
355 // other thread will be never woken up. It's much more convenient to us to
356 // remember that the condition was signaled and to return from Wait()
357 // immediately in this case (this is more like Win32 automatic event objects)
358 class wxConditionInternal
361 wxConditionInternal();
362 ~wxConditionInternal();
364 // wait with the given timeout or indefinitely if NULL
365 bool Wait(const timespec
* ts
= NULL
);
367 void Signal(bool all
= FALSE
);
370 // the number of Signal() calls we "missed", i.e. which were done while
371 // there were no threads to wait for them
372 size_t m_nQueuedSignals
;
374 // counts all pending waiters
377 // the condition itself
378 pthread_cond_t m_condition
;
380 // the mutex used with the conditon: it also protects the counters above
381 pthread_mutex_t m_mutex
;
384 wxConditionInternal::wxConditionInternal()
389 if ( pthread_cond_init(&m_condition
, (pthread_condattr_t
*)NULL
) != 0 )
391 // this is supposed to never happen
392 wxFAIL_MSG( _T("pthread_cond_init() failed") );
395 if ( pthread_mutex_init(&m_mutex
, NULL
) != 0 )
398 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
402 wxConditionInternal::~wxConditionInternal()
404 if ( pthread_cond_destroy( &m_condition
) != 0 )
406 wxLogDebug(_T("Failed to destroy condition variable (some "
407 "threads are probably still waiting on it?)"));
410 if ( pthread_mutex_destroy( &m_mutex
) != 0 )
412 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
416 bool wxConditionInternal::Wait(const timespec
* ts
)
418 MutexLock
lock(m_mutex
);
420 if ( m_nQueuedSignals
)
424 wxLogTrace(TRACE_THREADS
,
425 _T("wxCondition(%08x)::Wait(): Has been signaled before"),
431 // there are no queued signals, so start really waiting
434 // calling wait function below unlocks the mutex and Signal() or
435 // Broadcast() will be able to continue to run now if they were
436 // blocking for it in the loop locking all mutexes)
437 wxLogTrace(TRACE_THREADS
,
438 _T("wxCondition(%08x)::Wait(): starting to wait"), this);
440 int err
= ts
? pthread_cond_timedwait(&m_condition
, &m_mutex
, ts
)
441 : pthread_cond_wait(&m_condition
, &m_mutex
);
445 // condition was signaled
446 wxLogTrace(TRACE_THREADS
,
447 _T("wxCondition(%08x)::Wait(): ok"), this);
451 wxLogDebug(_T("unexpected pthread_cond_[timed]wait() return"));
456 // The condition has not been signaled, so we have to
457 // decrement the counter manually
460 // wait interrupted or timeout elapsed
461 wxLogTrace(TRACE_THREADS
,
462 _T("wxCondition(%08x)::Wait(): timeout/intr"), this);
468 void wxConditionInternal::Signal(bool all
)
470 // make sure that only one Signal() or Broadcast() is in progress
471 MutexLock
lock(m_mutex
);
473 // Are there any waiters?
474 if ( m_nWaiters
== 0 )
476 // No, there are not, so don't signal but keep in mind for the next
483 // now we can finally signal it
484 wxLogTrace(TRACE_THREADS
, _T("wxCondition(%08x)::Signal(): preparing to %s"),
485 this, all
? _T("broadcast") : _T("signal"));
487 int err
= all
? pthread_cond_broadcast(&m_condition
)
488 : pthread_cond_signal(&m_condition
);
501 // shouldn't ever happen
502 wxFAIL_MSG(_T("pthread_cond_{broadcast|signal}() failed"));
506 // ----------------------------------------------------------------------------
508 // ----------------------------------------------------------------------------
510 wxCondition::wxCondition()
512 m_internal
= new wxConditionInternal
;
515 wxCondition::~wxCondition()
520 void wxCondition::Wait()
522 (void)m_internal
->Wait();
525 bool wxCondition::Wait(unsigned long sec
, unsigned long nsec
)
529 tspec
.tv_sec
= time(0L) + sec
; // FIXME is time(0) correct here?
530 tspec
.tv_nsec
= nsec
;
532 return m_internal
->Wait(&tspec
);
535 void wxCondition::Signal()
537 m_internal
->Signal();
540 void wxCondition::Broadcast()
542 m_internal
->Signal(TRUE
/* all */);
545 // ============================================================================
546 // wxThread implementation
547 // ============================================================================
549 // the thread callback functions must have the C linkage
553 #if HAVE_THREAD_CLEANUP_FUNCTIONS
554 // thread exit function
555 void wxPthreadCleanup(void *ptr
);
556 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
558 void *wxPthreadStart(void *ptr
);
562 // ----------------------------------------------------------------------------
564 // ----------------------------------------------------------------------------
566 class wxThreadInternal
572 // thread entry function
573 static void *PthreadStart(wxThread
*thread
);
578 // ask the thread to terminate
580 // wake up threads waiting for our termination
582 // wake up threads waiting for our start
583 void SignalRun() { m_condRun
.Signal(); }
584 // go to sleep until Resume() is called
591 int GetPriority() const { return m_prio
; }
592 void SetPriority(int prio
) { m_prio
= prio
; }
594 wxThreadState
GetState() const { return m_state
; }
595 void SetState(wxThreadState state
) { m_state
= state
; }
597 pthread_t
GetId() const { return m_threadId
; }
598 pthread_t
*GetIdPtr() { return &m_threadId
; }
600 void SetCancelFlag() { m_cancelled
= TRUE
; }
601 bool WasCancelled() const { return m_cancelled
; }
603 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
604 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
607 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
608 bool IsReallyPaused() const { return m_isPaused
; }
610 // tell the thread that it is a detached one
613 m_shouldBeJoined
= m_shouldBroadcast
= FALSE
;
616 // but even detached threads need to notifyus about their termination
617 // sometimes - tell the thread that it should do it
618 void Notify() { m_shouldBroadcast
= TRUE
; }
620 #if HAVE_THREAD_CLEANUP_FUNCTIONS
621 // this is used by wxPthreadCleanup() only
622 static void Cleanup(wxThread
*thread
);
623 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
626 pthread_t m_threadId
; // id of the thread
627 wxThreadState m_state
; // see wxThreadState enum
628 int m_prio
; // in wxWindows units: from 0 to 100
630 // this flag is set when the thread should terminate
633 // this flag is set when the thread is blocking on m_condSuspend
636 // the thread exit code - only used for joinable (!detached) threads and
637 // is only valid after the thread termination
638 wxThread::ExitCode m_exitcode
;
640 // many threads may call Wait(), but only one of them should call
641 // pthread_join(), so we have to keep track of this
642 wxCriticalSection m_csJoinFlag
;
643 bool m_shouldBeJoined
;
644 bool m_shouldBroadcast
;
647 // VZ: it's possible that we might do with less than three different
648 // condition objects - for example, m_condRun and m_condEnd a priori
649 // won't be used in the same time. But for now I prefer this may be a
650 // bit less efficient but safer solution of having distinct condition
651 // variables for each purpose.
653 // this condition is signaled by Run() and the threads Entry() is not
654 // called before it is done
655 wxCondition m_condRun
;
657 // this one is signaled when the thread should resume after having been
659 wxCondition m_condSuspend
;
661 // finally this one is signalled when the thread exits
662 wxCondition m_condEnd
;
665 // ----------------------------------------------------------------------------
666 // thread startup and exit functions
667 // ----------------------------------------------------------------------------
669 void *wxPthreadStart(void *ptr
)
671 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
674 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
676 wxThreadInternal
*pthread
= thread
->m_internal
;
678 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), pthread
->GetId());
680 // associate the thread pointer with the newly created thread so that
681 // wxThread::This() will work
682 int rc
= pthread_setspecific(gs_keySelf
, thread
);
685 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
690 // have to declare this before pthread_cleanup_push() which defines a
694 #if HAVE_THREAD_CLEANUP_FUNCTIONS
695 // install the cleanup handler which will be called if the thread is
697 pthread_cleanup_push(wxPthreadCleanup
, thread
);
698 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
700 // wait for the condition to be signaled from Run()
701 pthread
->m_condRun
.Wait();
703 // test whether we should run the run at all - may be it was deleted
704 // before it started to Run()?
706 wxCriticalSectionLocker
lock(thread
->m_critsect
);
708 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
709 pthread
->WasCancelled();
714 // call the main entry
715 pthread
->m_exitcode
= thread
->Entry();
717 wxLogTrace(TRACE_THREADS
, _T("Thread %ld left its Entry()."),
721 wxCriticalSectionLocker
lock(thread
->m_critsect
);
723 wxLogTrace(TRACE_THREADS
, _T("Thread %ld changes state to EXITED."),
726 // change the state of the thread to "exited" so that
727 // wxPthreadCleanup handler won't do anything from now (if it's
728 // called before we do pthread_cleanup_pop below)
729 pthread
->SetState(STATE_EXITED
);
733 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
734 // contains the matching '}' for the '{' in push, so they must be used
735 // in the same block!
736 #if HAVE_THREAD_CLEANUP_FUNCTIONS
737 // remove the cleanup handler without executing it
738 pthread_cleanup_pop(FALSE
);
739 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
745 return EXITCODE_CANCELLED
;
749 // terminate the thread
750 thread
->Exit(pthread
->m_exitcode
);
752 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
758 #if HAVE_THREAD_CLEANUP_FUNCTIONS
760 // this handler is called when the thread is cancelled
761 extern "C" void wxPthreadCleanup(void *ptr
)
763 wxThreadInternal::Cleanup((wxThread
*)ptr
);
766 void wxThreadInternal::Cleanup(wxThread
*thread
)
769 wxCriticalSectionLocker
lock(thread
->m_critsect
);
770 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
772 // thread is already considered as finished.
777 // exit the thread gracefully
778 thread
->Exit(EXITCODE_CANCELLED
);
781 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
783 // ----------------------------------------------------------------------------
785 // ----------------------------------------------------------------------------
787 wxThreadInternal::wxThreadInternal()
791 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
795 // set to TRUE only when the thread starts waiting on m_condSuspend
798 // defaults for joinable threads
799 m_shouldBeJoined
= TRUE
;
800 m_shouldBroadcast
= TRUE
;
801 m_isDetached
= FALSE
;
804 wxThreadInternal::~wxThreadInternal()
808 wxThreadError
wxThreadInternal::Run()
810 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
811 wxT("thread may only be started once after Create()") );
815 SetState(STATE_RUNNING
);
817 return wxTHREAD_NO_ERROR
;
820 void wxThreadInternal::Wait()
822 // if the thread we're waiting for is waiting for the GUI mutex, we will
823 // deadlock so make sure we release it temporarily
824 if ( wxThread::IsMain() )
827 bool isDetached
= m_isDetached
;
828 wxThreadIdType id
= (wxThreadIdType
) GetId();
830 wxLogTrace(TRACE_THREADS
,
831 _T("Starting to wait for thread %ld to exit."), id
);
833 // wait until the thread terminates (we're blocking in _another_ thread,
837 wxLogTrace(TRACE_THREADS
, _T("Finished waiting for thread %ld."), id
);
839 // we can't use any member variables any more if the thread is detached
840 // because it could be already deleted
843 // to avoid memory leaks we should call pthread_join(), but it must
845 wxCriticalSectionLocker
lock(m_csJoinFlag
);
847 if ( m_shouldBeJoined
)
849 // FIXME shouldn't we set cancellation type to DISABLED here? If
850 // we're cancelled inside pthread_join(), things will almost
851 // certainly break - but if we disable the cancellation, we
853 if ( pthread_join((pthread_t
)id
, &m_exitcode
) != 0 )
855 wxLogError(_("Failed to join a thread, potential memory leak "
856 "detected - please restart the program"));
859 m_shouldBeJoined
= FALSE
;
863 // reacquire GUI mutex
864 if ( wxThread::IsMain() )
868 void wxThreadInternal::SignalExit()
870 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to exit."), GetId());
872 SetState(STATE_EXITED
);
874 // wake up all the threads waiting for our termination - if there are any
875 if ( m_shouldBroadcast
)
877 wxLogTrace(TRACE_THREADS
, _T("Thread %ld signals end condition."),
880 m_condEnd
.Broadcast();
884 void wxThreadInternal::Pause()
886 // the state is set from the thread which pauses us first, this function
887 // is called later so the state should have been already set
888 wxCHECK_RET( m_state
== STATE_PAUSED
,
889 wxT("thread must first be paused with wxThread::Pause().") );
891 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), GetId());
893 // wait until the condition is signaled from Resume()
894 m_condSuspend
.Wait();
897 void wxThreadInternal::Resume()
899 wxCHECK_RET( m_state
== STATE_PAUSED
,
900 wxT("can't resume thread which is not suspended.") );
902 // the thread might be not actually paused yet - if there were no call to
903 // TestDestroy() since the last call to Pause() for example
904 if ( IsReallyPaused() )
906 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), GetId());
909 m_condSuspend
.Signal();
912 SetReallyPaused(FALSE
);
916 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
920 SetState(STATE_RUNNING
);
923 // -----------------------------------------------------------------------------
924 // wxThread static functions
925 // -----------------------------------------------------------------------------
927 wxThread
*wxThread::This()
929 return (wxThread
*)pthread_getspecific(gs_keySelf
);
932 bool wxThread::IsMain()
934 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
937 void wxThread::Yield()
939 #ifdef HAVE_SCHED_YIELD
944 void wxThread::Sleep(unsigned long milliseconds
)
946 wxUsleep(milliseconds
);
949 int wxThread::GetCPUCount()
951 #if defined(__LINUX__) && wxUSE_FFILE
952 // read from proc (can't use wxTextFile here because it's a special file:
953 // it has 0 size but still can be read from)
956 wxFFile
file(_T("/proc/cpuinfo"));
957 if ( file
.IsOpened() )
959 // slurp the whole file
961 if ( file
.ReadAll(&s
) )
963 // (ab)use Replace() to find the number of "processor" strings
964 size_t count
= s
.Replace(_T("processor"), _T(""));
970 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
974 wxLogDebug(_T("failed to read /proc/cpuinfo"));
977 #elif defined(_SC_NPROCESSORS_ONLN)
978 // this works for Solaris
979 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
984 #endif // different ways to get number of CPUs
991 // VMS is a 64 bit system and threads have 64 bit pointers.
992 // ??? also needed for other systems????
993 unsigned long long wxThread::GetCurrentId()
995 return (unsigned long long)pthread_self();
997 unsigned long wxThread::GetCurrentId()
999 return (unsigned long)pthread_self();
1003 bool wxThread::SetConcurrency(size_t level
)
1005 #ifdef HAVE_THR_SETCONCURRENCY
1006 int rc
= thr_setconcurrency(level
);
1009 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1013 #else // !HAVE_THR_SETCONCURRENCY
1014 // ok only for the default value
1016 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1019 // -----------------------------------------------------------------------------
1021 // -----------------------------------------------------------------------------
1023 wxThread::wxThread(wxThreadKind kind
)
1025 // add this thread to the global list of all threads
1026 gs_allThreads
.Add(this);
1028 m_internal
= new wxThreadInternal();
1030 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1033 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1035 if ( m_internal
->GetState() != STATE_NEW
)
1037 // don't recreate thread
1038 return wxTHREAD_RUNNING
;
1041 // set up the thread attribute: right now, we only set thread priority
1042 pthread_attr_t attr
;
1043 pthread_attr_init(&attr
);
1045 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1047 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1049 wxLogError(_("Cannot retrieve thread scheduling policy."));
1053 /* the pthread.h contains too many spaces. This is a work-around */
1054 # undef sched_get_priority_max
1055 #undef sched_get_priority_min
1056 #define sched_get_priority_max(_pol_) \
1057 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1058 #define sched_get_priority_min(_pol_) \
1059 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1062 int max_prio
= sched_get_priority_max(policy
),
1063 min_prio
= sched_get_priority_min(policy
),
1064 prio
= m_internal
->GetPriority();
1066 if ( min_prio
== -1 || max_prio
== -1 )
1068 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1071 else if ( max_prio
== min_prio
)
1073 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1075 // notify the programmer that this doesn't work here
1076 wxLogWarning(_("Thread priority setting is ignored."));
1078 //else: we have default priority, so don't complain
1080 // anyhow, don't do anything because priority is just ignored
1084 struct sched_param sp
;
1085 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1087 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1090 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1092 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1094 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1097 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1099 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1100 // this will make the threads created by this process really concurrent
1101 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1103 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1105 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1107 // VZ: assume that this one is always available (it's rather fundamental),
1108 // if this function is ever missing we should try to use
1109 // pthread_detach() instead (after thread creation)
1112 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1114 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1117 // never try to join detached threads
1118 m_internal
->Detach();
1120 //else: threads are created joinable by default, it's ok
1122 // create the new OS thread object
1123 int rc
= pthread_create
1125 m_internal
->GetIdPtr(),
1131 if ( pthread_attr_destroy(&attr
) != 0 )
1133 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1138 m_internal
->SetState(STATE_EXITED
);
1140 return wxTHREAD_NO_RESOURCE
;
1143 return wxTHREAD_NO_ERROR
;
1146 wxThreadError
wxThread::Run()
1148 wxCriticalSectionLocker
lock(m_critsect
);
1150 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1151 wxT("must call wxThread::Create() first") );
1153 return m_internal
->Run();
1156 // -----------------------------------------------------------------------------
1158 // -----------------------------------------------------------------------------
1160 void wxThread::SetPriority(unsigned int prio
)
1162 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1163 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1164 wxT("invalid thread priority") );
1166 wxCriticalSectionLocker
lock(m_critsect
);
1168 switch ( m_internal
->GetState() )
1171 // thread not yet started, priority will be set when it is
1172 m_internal
->SetPriority(prio
);
1177 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1179 struct sched_param sparam
;
1180 sparam
.sched_priority
= prio
;
1182 if ( pthread_setschedparam(m_internal
->GetId(),
1183 SCHED_OTHER
, &sparam
) != 0 )
1185 wxLogError(_("Failed to set thread priority %d."), prio
);
1188 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1193 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1197 unsigned int wxThread::GetPriority() const
1199 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1201 return m_internal
->GetPriority();
1204 wxThreadIdType
wxThread::GetId() const
1206 return (wxThreadIdType
) m_internal
->GetId();
1209 // -----------------------------------------------------------------------------
1211 // -----------------------------------------------------------------------------
1213 wxThreadError
wxThread::Pause()
1215 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1216 _T("a thread can't pause itself") );
1218 wxCriticalSectionLocker
lock(m_critsect
);
1220 if ( m_internal
->GetState() != STATE_RUNNING
)
1222 wxLogDebug(wxT("Can't pause thread which is not running."));
1224 return wxTHREAD_NOT_RUNNING
;
1227 wxLogTrace(TRACE_THREADS
, _T("Asking thread %ld to pause."),
1230 // just set a flag, the thread will be really paused only during the next
1231 // call to TestDestroy()
1232 m_internal
->SetState(STATE_PAUSED
);
1234 return wxTHREAD_NO_ERROR
;
1237 wxThreadError
wxThread::Resume()
1239 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1240 _T("a thread can't resume itself") );
1242 wxCriticalSectionLocker
lock(m_critsect
);
1244 wxThreadState state
= m_internal
->GetState();
1249 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1252 m_internal
->Resume();
1254 return wxTHREAD_NO_ERROR
;
1257 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1259 return wxTHREAD_NO_ERROR
;
1262 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1264 return wxTHREAD_MISC_ERROR
;
1268 // -----------------------------------------------------------------------------
1270 // -----------------------------------------------------------------------------
1272 wxThread::ExitCode
wxThread::Wait()
1274 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1275 _T("a thread can't wait for itself") );
1277 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1278 _T("can't wait for detached thread") );
1282 return m_internal
->GetExitCode();
1285 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1287 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1288 _T("a thread can't delete itself") );
1291 wxThreadState state
= m_internal
->GetState();
1293 // ask the thread to stop
1294 m_internal
->SetCancelFlag();
1298 // detached threads won't broadcast about their termination by default
1299 // because usually nobody waits for them - but here we do, so ask the
1300 // thread to notify us
1301 m_internal
->Notify();
1309 // we need to wake up the thread so that PthreadStart() will
1310 // terminate - right now it's blocking on m_condRun
1311 m_internal
->SignalRun();
1320 // resume the thread first (don't call our Resume() because this
1321 // would dead lock when it tries to enter m_critsect)
1322 m_internal
->Resume();
1327 // wait until the thread stops
1332 wxASSERT_MSG( !m_isDetached
,
1333 _T("no return code for detached threads") );
1335 // if it's a joinable thread, it's not deleted yet
1336 *rc
= m_internal
->GetExitCode();
1340 return wxTHREAD_NO_ERROR
;
1343 wxThreadError
wxThread::Kill()
1345 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1346 _T("a thread can't kill itself") );
1348 switch ( m_internal
->GetState() )
1352 return wxTHREAD_NOT_RUNNING
;
1355 // resume the thread first
1361 #ifdef HAVE_PTHREAD_CANCEL
1362 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1365 wxLogError(_("Failed to terminate a thread."));
1367 return wxTHREAD_MISC_ERROR
;
1372 // if we use cleanup function, this will be done from
1373 // wxPthreadCleanup()
1374 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1375 ScheduleThreadForDeletion();
1377 // don't call OnExit() here, it can only be called in the
1378 // threads context and we're in the context of another thread
1381 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1385 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1388 return wxTHREAD_NO_ERROR
;
1392 void wxThread::Exit(ExitCode status
)
1394 wxASSERT_MSG( This() == this,
1395 _T("wxThread::Exit() can only be called in the "
1396 "context of the same thread") );
1398 // from the moment we call OnExit(), the main program may terminate at any
1399 // moment, so mark this thread as being already in process of being
1400 // deleted or wxThreadModule::OnExit() will try to delete it again
1401 ScheduleThreadForDeletion();
1403 // don't enter m_critsect before calling OnExit() because the user code
1404 // might deadlock if, for example, it signals a condition in OnExit() (a
1405 // common case) while the main thread calls any of functions entering
1406 // m_critsect on us (almost all of them do)
1409 // now do enter it because SignalExit() will change our state
1412 // next wake up the threads waiting for us (OTOH, this function won't return
1413 // until someone waited for us!)
1414 m_internal
->SignalExit();
1416 // leave the critical section before entering the dtor which tries to
1420 // delete C++ thread object if this is a detached thread - user is
1421 // responsible for doing this for joinable ones
1424 // FIXME I'm feeling bad about it - what if another thread function is
1425 // called (in another thread context) now? It will try to access
1426 // half destroyed object which will probably result in something
1427 // very bad - but we can't protect this by a crit section unless
1428 // we make it a global object, but this would mean that we can
1429 // only call one thread function at a time :-(
1433 // terminate the thread (pthread_exit() never returns)
1434 pthread_exit(status
);
1436 wxFAIL_MSG(_T("pthread_exit() failed"));
1439 // also test whether we were paused
1440 bool wxThread::TestDestroy()
1442 wxASSERT_MSG( This() == this,
1443 _T("wxThread::TestDestroy() can only be called in the "
1444 "context of the same thread") );
1448 if ( m_internal
->GetState() == STATE_PAUSED
)
1450 m_internal
->SetReallyPaused(TRUE
);
1452 // leave the crit section or the other threads will stop too if they
1453 // try to call any of (seemingly harmless) IsXXX() functions while we
1457 m_internal
->Pause();
1461 // thread wasn't requested to pause, nothing to do
1465 return m_internal
->WasCancelled();
1468 wxThread::~wxThread()
1473 // check that the thread either exited or couldn't be created
1474 if ( m_internal
->GetState() != STATE_EXITED
&&
1475 m_internal
->GetState() != STATE_NEW
)
1477 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1478 "running! The application may crash."), GetId());
1482 #endif // __WXDEBUG__
1486 // remove this thread from the global array
1487 gs_allThreads
.Remove(this);
1489 // detached thread will decrement this counter in DeleteThread(), but it
1490 // is not called for the joinable threads, so do it here
1491 if ( !m_isDetached
)
1493 MutexLock
lock(gs_mutexDeleteThread
);
1494 gs_nThreadsBeingDeleted
--;
1496 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1497 gs_nThreadsBeingDeleted
- 1);
1501 // -----------------------------------------------------------------------------
1503 // -----------------------------------------------------------------------------
1505 bool wxThread::IsRunning() const
1507 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1509 return m_internal
->GetState() == STATE_RUNNING
;
1512 bool wxThread::IsAlive() const
1514 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1516 switch ( m_internal
->GetState() )
1527 bool wxThread::IsPaused() const
1529 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1531 return (m_internal
->GetState() == STATE_PAUSED
);
1534 //--------------------------------------------------------------------
1536 //--------------------------------------------------------------------
1538 class wxThreadModule
: public wxModule
1541 virtual bool OnInit();
1542 virtual void OnExit();
1545 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1548 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1550 bool wxThreadModule::OnInit()
1552 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1555 wxLogSysError(rc
, _("Thread module initialization failed: "
1556 "failed to create thread key"));
1561 gs_tidMain
= pthread_self();
1564 gs_mutexGui
= new wxMutex();
1566 gs_mutexGui
->Lock();
1569 // under Solaris we get a warning from CC when using
1570 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1571 pthread_mutex_init(&gs_mutexDeleteThread
, NULL
);
1576 void wxThreadModule::OnExit()
1578 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1580 // are there any threads left which are being deleted right now?
1581 size_t nThreadsBeingDeleted
;
1583 MutexLock
lock(gs_mutexDeleteThread
);
1584 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1587 if ( nThreadsBeingDeleted
> 0 )
1589 wxLogTrace(TRACE_THREADS
, _T("Waiting for %u threads to disappear"),
1590 nThreadsBeingDeleted
);
1592 // have to wait until all of them disappear
1593 gs_condAllDeleted
->Wait();
1596 // terminate any threads left
1597 size_t count
= gs_allThreads
.GetCount();
1600 wxLogDebug(wxT("%u threads were not terminated by the application."),
1604 for ( size_t n
= 0u; n
< count
; n
++ )
1606 // Delete calls the destructor which removes the current entry. We
1607 // should only delete the first one each time.
1608 gs_allThreads
[0]->Delete();
1612 // destroy GUI mutex
1613 gs_mutexGui
->Unlock();
1618 // and free TLD slot
1619 (void)pthread_key_delete(gs_keySelf
);
1622 // ----------------------------------------------------------------------------
1624 // ----------------------------------------------------------------------------
1626 static void ScheduleThreadForDeletion()
1628 MutexLock
lock(gs_mutexDeleteThread
);
1630 if ( gs_nThreadsBeingDeleted
== 0 )
1632 gs_condAllDeleted
= new wxCondition
;
1635 gs_nThreadsBeingDeleted
++;
1637 wxLogTrace(TRACE_THREADS
, _T("%u thread%s waiting to be deleted"),
1638 gs_nThreadsBeingDeleted
,
1639 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1642 static void DeleteThread(wxThread
*This
)
1644 // gs_mutexDeleteThread should be unlocked before signalling the condition
1645 // or wxThreadModule::OnExit() would deadlock
1647 MutexLock
lock(gs_mutexDeleteThread
);
1649 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1653 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1654 _T("no threads scheduled for deletion, yet we delete "
1658 wxLogTrace(TRACE_THREADS
, _T("%u scheduled for deletion threads left."),
1659 gs_nThreadsBeingDeleted
- 1);
1661 if ( !--gs_nThreadsBeingDeleted
)
1663 // no more threads left, signal it
1664 gs_condAllDeleted
->Signal();
1666 delete gs_condAllDeleted
;
1667 gs_condAllDeleted
= (wxCondition
*)NULL
;
1671 void wxMutexGuiEnter()
1674 gs_mutexGui
->Lock();
1678 void wxMutexGuiLeave()
1681 gs_mutexGui
->Unlock();