1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999-2002)
11 // Robert Roebling (1999)
12 // K. S. Sreeram (2002)
13 // Licence: wxWindows licence
14 /////////////////////////////////////////////////////////////////////////////
16 // ============================================================================
18 // ============================================================================
20 // ----------------------------------------------------------------------------
22 // ----------------------------------------------------------------------------
25 #pragma implementation "thread.h"
32 #include "wx/thread.h"
33 #include "wx/module.h"
37 #include "wx/dynarray.h"
49 #ifdef HAVE_THR_SETCONCURRENCY
53 // we use wxFFile under Linux in GetCPUCount()
58 #include <sys/resource.h>
61 // ----------------------------------------------------------------------------
63 // ----------------------------------------------------------------------------
65 // the possible states of the thread and transitions from them
68 STATE_NEW
, // didn't start execution yet (=> RUNNING)
69 STATE_RUNNING
, // running (=> PAUSED or EXITED)
70 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
71 STATE_EXITED
// thread doesn't exist any more
74 // the exit value of a thread which has been cancelled
75 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
77 // trace mask for wxThread operations
78 #define TRACE_THREADS _T("thread")
80 // you can get additional debugging messages for the semaphore operations
81 #define TRACE_SEMA _T("semaphore")
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 static void ScheduleThreadForDeletion();
88 static void DeleteThread(wxThread
*This
);
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 // an (non owning) array of pointers to threads
95 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
97 // an entry for a thread we can wait for
99 // -----------------------------------------------------------------------------
101 // -----------------------------------------------------------------------------
103 // we keep the list of all threads created by the application to be able to
104 // terminate them on exit if there are some left - otherwise the process would
106 static wxArrayThread gs_allThreads
;
108 // the id of the main thread
109 static pthread_t gs_tidMain
;
111 // the key for the pointer to the associated wxThread object
112 static pthread_key_t gs_keySelf
;
114 // the number of threads which are being deleted - the program won't exit
115 // until there are any left
116 static size_t gs_nThreadsBeingDeleted
= 0;
118 // a mutex to protect gs_nThreadsBeingDeleted
119 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
121 // and a condition variable which will be signaled when all
122 // gs_nThreadsBeingDeleted will have been deleted
123 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
126 // this mutex must be acquired before any call to a GUI function
127 static wxMutex
*gs_mutexGui
;
130 // when we wait for a thread to exit, we're blocking on a condition which the
131 // thread signals in its SignalExit() method -- but this condition can't be a
132 // member of the thread itself as a detached thread may delete itself at any
133 // moment and accessing the condition member of the thread after this would
134 // result in a disaster
136 // so instead we maintain a global list of the structs below for the threads
137 // we're interested in waiting on
139 // ============================================================================
140 // wxMutex implementation
141 // ============================================================================
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 // this is a simple wrapper around pthread_mutex_t which provides error
149 class wxMutexInternal
152 wxMutexInternal(wxMutexType mutexType
);
156 wxMutexError
TryLock();
157 wxMutexError
Unlock();
159 bool IsOk() const { return m_isOk
; }
162 pthread_mutex_t m_mutex
;
165 // wxConditionInternal uses our m_mutex
166 friend class wxConditionInternal
;
169 #ifdef HAVE_PTHREAD_MUTEXATTR_T
170 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
171 // in the library, otherwise we wouldn't compile this code at all)
172 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
175 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
180 case wxMUTEX_RECURSIVE
:
181 // support recursive locks like Win32, i.e. a thread can lock a
182 // mutex which it had itself already locked
184 // unfortunately initialization of recursive mutexes is non
185 // portable, so try several methods
186 #ifdef HAVE_PTHREAD_MUTEXATTR_T
188 pthread_mutexattr_t attr
;
189 pthread_mutexattr_init(&attr
);
190 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
192 err
= pthread_mutex_init(&m_mutex
, &attr
);
194 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
195 // we can use this only as initializer so we have to assign it
196 // first to a temp var - assigning directly to m_mutex wouldn't
199 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
202 #else // no recursive mutexes
204 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
208 wxFAIL_MSG( _T("unknown mutex type") );
211 case wxMUTEX_DEFAULT
:
212 err
= pthread_mutex_init(&m_mutex
, NULL
);
219 wxLogApiError( wxT("pthread_mutex_init()"), err
);
223 wxMutexInternal::~wxMutexInternal()
227 int err
= pthread_mutex_destroy(&m_mutex
);
230 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
235 wxMutexError
wxMutexInternal::Lock()
237 int err
= pthread_mutex_lock(&m_mutex
);
241 // only error checking mutexes return this value and so it's an
242 // unexpected situation -- hence use assert, not wxLogDebug
243 wxFAIL_MSG( _T("mutex deadlock prevented") );
244 return wxMUTEX_DEAD_LOCK
;
247 wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized."));
251 return wxMUTEX_NO_ERROR
;
254 wxLogApiError(_T("pthread_mutex_lock()"), err
);
257 return wxMUTEX_MISC_ERROR
;
260 wxMutexError
wxMutexInternal::TryLock()
262 int err
= pthread_mutex_trylock(&m_mutex
);
266 // not an error: mutex is already locked, but we're prepared for
271 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
275 return wxMUTEX_NO_ERROR
;
278 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
281 return wxMUTEX_MISC_ERROR
;
284 wxMutexError
wxMutexInternal::Unlock()
286 int err
= pthread_mutex_unlock(&m_mutex
);
290 // we don't own the mutex
291 return wxMUTEX_UNLOCKED
;
294 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
298 return wxMUTEX_NO_ERROR
;
301 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
304 return wxMUTEX_MISC_ERROR
;
307 // ===========================================================================
308 // wxCondition implementation
309 // ===========================================================================
311 // ---------------------------------------------------------------------------
312 // wxConditionInternal
313 // ---------------------------------------------------------------------------
315 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
316 // with a pthread_mutex_t)
317 class wxConditionInternal
320 wxConditionInternal(wxMutex
& mutex
);
321 ~wxConditionInternal();
323 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
326 wxCondError
WaitTimeout(unsigned long milliseconds
);
328 wxCondError
Signal();
329 wxCondError
Broadcast();
332 // get the POSIX mutex associated with us
333 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
336 pthread_cond_t m_cond
;
341 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
344 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
350 wxLogApiError(_T("pthread_cond_init()"), err
);
354 wxConditionInternal::~wxConditionInternal()
358 int err
= pthread_cond_destroy(&m_cond
);
361 wxLogApiError(_T("pthread_cond_destroy()"), err
);
366 wxCondError
wxConditionInternal::Wait()
368 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
371 wxLogApiError(_T("pthread_cond_wait()"), err
);
373 return wxCOND_MISC_ERROR
;
376 return wxCOND_NO_ERROR
;
379 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
381 wxLongLong curtime
= wxGetLocalTimeMillis();
382 curtime
+= milliseconds
;
383 wxLongLong temp
= curtime
/ 1000;
384 int sec
= temp
.GetLo();
386 temp
= curtime
- temp
;
387 int millis
= temp
.GetLo();
392 tspec
.tv_nsec
= millis
* 1000L * 1000L;
394 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
398 return wxCOND_TIMEOUT
;
401 return wxCOND_NO_ERROR
;
404 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
407 return wxCOND_MISC_ERROR
;
410 wxCondError
wxConditionInternal::Signal()
412 int err
= pthread_cond_signal(&m_cond
);
415 wxLogApiError(_T("pthread_cond_signal()"), err
);
417 return wxCOND_MISC_ERROR
;
420 return wxCOND_NO_ERROR
;
423 wxCondError
wxConditionInternal::Broadcast()
425 int err
= pthread_cond_broadcast(&m_cond
);
428 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
430 return wxCOND_MISC_ERROR
;
433 return wxCOND_NO_ERROR
;
436 // ===========================================================================
437 // wxSemaphore implementation
438 // ===========================================================================
440 // ---------------------------------------------------------------------------
441 // wxSemaphoreInternal
442 // ---------------------------------------------------------------------------
444 // we implement the semaphores using mutexes and conditions instead of using
445 // the sem_xxx() POSIX functions because they're not widely available and also
446 // because it's impossible to implement WaitTimeout() using them
447 class wxSemaphoreInternal
450 wxSemaphoreInternal(int initialcount
, int maxcount
);
452 bool IsOk() const { return m_isOk
; }
455 wxSemaError
TryWait();
456 wxSemaError
WaitTimeout(unsigned long milliseconds
);
470 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
474 if ( (initialcount
< 0 || maxcount
< 0) ||
475 ((maxcount
> 0) && (initialcount
> maxcount
)) )
477 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
483 m_maxcount
= (size_t)maxcount
;
484 m_count
= (size_t)initialcount
;
487 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
490 wxSemaError
wxSemaphoreInternal::Wait()
492 wxMutexLocker
locker(m_mutex
);
494 while ( m_count
== 0 )
496 wxLogTrace(TRACE_SEMA
,
497 "Thread %ld waiting for semaphore to become signalled",
498 wxThread::GetCurrentId());
500 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
501 return wxSEMA_MISC_ERROR
;
503 wxLogTrace(TRACE_SEMA
,
504 "Thread %ld finished waiting for semaphore, count = %lu",
505 wxThread::GetCurrentId(), (unsigned long)m_count
);
510 return wxSEMA_NO_ERROR
;
513 wxSemaError
wxSemaphoreInternal::TryWait()
515 wxMutexLocker
locker(m_mutex
);
522 return wxSEMA_NO_ERROR
;
525 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
527 wxMutexLocker
locker(m_mutex
);
529 wxLongLong startTime
= wxGetLocalTimeMillis();
531 while ( m_count
== 0 )
533 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
534 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
535 if ( remainingTime
<= 0 )
538 return wxSEMA_TIMEOUT
;
541 switch ( m_cond
.WaitTimeout(remainingTime
) )
544 return wxSEMA_TIMEOUT
;
547 return wxSEMA_MISC_ERROR
;
549 case wxCOND_NO_ERROR
:
556 return wxSEMA_NO_ERROR
;
559 wxSemaError
wxSemaphoreInternal::Post()
561 wxMutexLocker
locker(m_mutex
);
563 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
565 return wxSEMA_OVERFLOW
;
570 wxLogTrace(TRACE_SEMA
,
571 "Thread %ld about to signal semaphore, count = %lu",
572 wxThread::GetCurrentId(), (unsigned long)m_count
);
574 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
578 // ===========================================================================
579 // wxThread implementation
580 // ===========================================================================
582 // the thread callback functions must have the C linkage
586 #if HAVE_THREAD_CLEANUP_FUNCTIONS
587 // thread exit function
588 void wxPthreadCleanup(void *ptr
);
589 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
591 void *wxPthreadStart(void *ptr
);
595 // ----------------------------------------------------------------------------
597 // ----------------------------------------------------------------------------
599 class wxThreadInternal
605 // thread entry function
606 static void *PthreadStart(wxThread
*thread
);
611 // unblock the thread allowing it to run
612 void SignalRun() { m_semRun
.Post(); }
613 // ask the thread to terminate
615 // go to sleep until Resume() is called
622 int GetPriority() const { return m_prio
; }
623 void SetPriority(int prio
) { m_prio
= prio
; }
625 wxThreadState
GetState() const { return m_state
; }
626 void SetState(wxThreadState state
)
629 static const wxChar
*stateNames
[] =
637 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
638 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
639 #endif // __WXDEBUG__
644 pthread_t
GetId() const { return m_threadId
; }
645 pthread_t
*GetIdPtr() { return &m_threadId
; }
647 void SetCancelFlag() { m_cancelled
= TRUE
; }
648 bool WasCancelled() const { return m_cancelled
; }
650 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
651 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
654 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
655 bool IsReallyPaused() const { return m_isPaused
; }
657 // tell the thread that it is a detached one
660 wxCriticalSectionLocker
lock(m_csJoinFlag
);
662 m_shouldBeJoined
= FALSE
;
666 #if HAVE_THREAD_CLEANUP_FUNCTIONS
667 // this is used by wxPthreadCleanup() only
668 static void Cleanup(wxThread
*thread
);
669 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
672 pthread_t m_threadId
; // id of the thread
673 wxThreadState m_state
; // see wxThreadState enum
674 int m_prio
; // in wxWindows units: from 0 to 100
676 // this flag is set when the thread should terminate
679 // this flag is set when the thread is blocking on m_semSuspend
682 // the thread exit code - only used for joinable (!detached) threads and
683 // is only valid after the thread termination
684 wxThread::ExitCode m_exitcode
;
686 // many threads may call Wait(), but only one of them should call
687 // pthread_join(), so we have to keep track of this
688 wxCriticalSection m_csJoinFlag
;
689 bool m_shouldBeJoined
;
692 // this semaphore is posted by Run() and the threads Entry() is not
693 // called before it is done
694 wxSemaphore m_semRun
;
696 // this one is signaled when the thread should resume after having been
698 wxSemaphore m_semSuspend
;
701 // ----------------------------------------------------------------------------
702 // thread startup and exit functions
703 // ----------------------------------------------------------------------------
705 void *wxPthreadStart(void *ptr
)
707 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
710 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
712 wxThreadInternal
*pthread
= thread
->m_internal
;
715 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), (long long)pthread
->GetId());
717 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), (long)pthread
->GetId());
720 // associate the thread pointer with the newly created thread so that
721 // wxThread::This() will work
722 int rc
= pthread_setspecific(gs_keySelf
, thread
);
725 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
730 // have to declare this before pthread_cleanup_push() which defines a
734 #if HAVE_THREAD_CLEANUP_FUNCTIONS
735 // install the cleanup handler which will be called if the thread is
737 pthread_cleanup_push(wxPthreadCleanup
, thread
);
738 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
740 // wait for the semaphore to be posted from Run()
741 pthread
->m_semRun
.Wait();
743 // test whether we should run the run at all - may be it was deleted
744 // before it started to Run()?
746 wxCriticalSectionLocker
lock(thread
->m_critsect
);
748 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
749 pthread
->WasCancelled();
754 // call the main entry
755 wxLogTrace(TRACE_THREADS
, _T("Thread %ld about to enter its Entry()."),
757 (long long)pthread
->GetId());
759 (long)pthread
->GetId());
762 pthread
->m_exitcode
= thread
->Entry();
764 wxLogTrace(TRACE_THREADS
, _T("Thread %ld Entry() returned %lu."),
766 (long long)pthread
->GetId(), (unsigned long)pthread
->m_exitcode
);
768 (long)pthread
->GetId(), (unsigned long)pthread
->m_exitcode
);
772 wxCriticalSectionLocker
lock(thread
->m_critsect
);
774 // change the state of the thread to "exited" so that
775 // wxPthreadCleanup handler won't do anything from now (if it's
776 // called before we do pthread_cleanup_pop below)
777 pthread
->SetState(STATE_EXITED
);
781 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
782 // contains the matching '}' for the '{' in push, so they must be used
783 // in the same block!
784 #if HAVE_THREAD_CLEANUP_FUNCTIONS
785 // remove the cleanup handler without executing it
786 pthread_cleanup_pop(FALSE
);
787 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
791 // FIXME: deleting a possibly joinable thread here???
794 return EXITCODE_CANCELLED
;
798 // terminate the thread
799 thread
->Exit(pthread
->m_exitcode
);
801 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
807 #if HAVE_THREAD_CLEANUP_FUNCTIONS
809 // this handler is called when the thread is cancelled
810 extern "C" void wxPthreadCleanup(void *ptr
)
812 wxThreadInternal::Cleanup((wxThread
*)ptr
);
815 void wxThreadInternal::Cleanup(wxThread
*thread
)
818 wxCriticalSectionLocker
lock(thread
->m_critsect
);
819 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
821 // thread is already considered as finished.
826 // exit the thread gracefully
827 thread
->Exit(EXITCODE_CANCELLED
);
830 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
832 // ----------------------------------------------------------------------------
834 // ----------------------------------------------------------------------------
836 wxThreadInternal::wxThreadInternal()
840 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
844 // set to TRUE only when the thread starts waiting on m_semSuspend
847 // defaults for joinable threads
848 m_shouldBeJoined
= TRUE
;
849 m_isDetached
= FALSE
;
852 wxThreadInternal::~wxThreadInternal()
856 wxThreadError
wxThreadInternal::Run()
858 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
859 wxT("thread may only be started once after Create()") );
861 SetState(STATE_RUNNING
);
863 // wake up threads waiting for our start
866 return wxTHREAD_NO_ERROR
;
869 void wxThreadInternal::Wait()
871 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
873 // if the thread we're waiting for is waiting for the GUI mutex, we will
874 // deadlock so make sure we release it temporarily
875 if ( wxThread::IsMain() )
878 wxLogTrace(TRACE_THREADS
,
880 _T("Starting to wait for thread %ld to exit."), (long long)GetId());
882 _T("Starting to wait for thread %ld to exit."), (long)GetId());
885 // to avoid memory leaks we should call pthread_join(), but it must only be
886 // done once so use a critical section to serialize the code below
888 wxCriticalSectionLocker
lock(m_csJoinFlag
);
890 if ( m_shouldBeJoined
)
892 // FIXME shouldn't we set cancellation type to DISABLED here? If
893 // we're cancelled inside pthread_join(), things will almost
894 // certainly break - but if we disable the cancellation, we
896 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
898 // this is a serious problem, so use wxLogError and not
899 // wxLogDebug: it is possible to bring the system to its knees
900 // by creating too many threads and not joining them quite
902 wxLogError(_("Failed to join a thread, potential memory leak "
903 "detected - please restart the program"));
906 m_shouldBeJoined
= FALSE
;
910 // reacquire GUI mutex
911 if ( wxThread::IsMain() )
915 void wxThreadInternal::Pause()
917 // the state is set from the thread which pauses us first, this function
918 // is called later so the state should have been already set
919 wxCHECK_RET( m_state
== STATE_PAUSED
,
920 wxT("thread must first be paused with wxThread::Pause().") );
923 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), (long long)GetId());
925 wxLogTrace(TRACE_THREADS
, _T("Thread %ld goes to sleep."), (long)GetId());
928 // wait until the semaphore is Post()ed from Resume()
932 void wxThreadInternal::Resume()
934 wxCHECK_RET( m_state
== STATE_PAUSED
,
935 wxT("can't resume thread which is not suspended.") );
937 // the thread might be not actually paused yet - if there were no call to
938 // TestDestroy() since the last call to Pause() for example
939 if ( IsReallyPaused() )
942 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), (long long)GetId());
944 wxLogTrace(TRACE_THREADS
, _T("Waking up thread %ld"), (long)GetId());
951 SetReallyPaused(FALSE
);
955 wxLogTrace(TRACE_THREADS
, _T("Thread %ld is not yet really paused"),
963 SetState(STATE_RUNNING
);
966 // -----------------------------------------------------------------------------
967 // wxThread static functions
968 // -----------------------------------------------------------------------------
970 wxThread
*wxThread::This()
972 return (wxThread
*)pthread_getspecific(gs_keySelf
);
975 bool wxThread::IsMain()
977 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
980 void wxThread::Yield()
982 #ifdef HAVE_SCHED_YIELD
987 void wxThread::Sleep(unsigned long milliseconds
)
989 wxUsleep(milliseconds
);
992 int wxThread::GetCPUCount()
994 #if defined(__LINUX__) && wxUSE_FFILE
995 // read from proc (can't use wxTextFile here because it's a special file:
996 // it has 0 size but still can be read from)
999 wxFFile
file(_T("/proc/cpuinfo"));
1000 if ( file
.IsOpened() )
1002 // slurp the whole file
1004 if ( file
.ReadAll(&s
) )
1006 // (ab)use Replace() to find the number of "processor: num" strings
1007 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1013 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1017 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1020 #elif defined(_SC_NPROCESSORS_ONLN)
1021 // this works for Solaris
1022 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1027 #endif // different ways to get number of CPUs
1034 // VMS is a 64 bit system and threads have 64 bit pointers.
1035 // ??? also needed for other systems????
1036 unsigned long long wxThread::GetCurrentId()
1038 return (unsigned long long)pthread_self();
1040 unsigned long wxThread::GetCurrentId()
1042 return (unsigned long)pthread_self();
1046 bool wxThread::SetConcurrency(size_t level
)
1048 #ifdef HAVE_THR_SETCONCURRENCY
1049 int rc
= thr_setconcurrency(level
);
1052 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1056 #else // !HAVE_THR_SETCONCURRENCY
1057 // ok only for the default value
1059 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1062 // -----------------------------------------------------------------------------
1064 // -----------------------------------------------------------------------------
1066 wxThread::wxThread(wxThreadKind kind
)
1068 // add this thread to the global list of all threads
1069 gs_allThreads
.Add(this);
1071 m_internal
= new wxThreadInternal();
1073 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1076 wxThreadError
wxThread::Create(unsigned int WXUNUSED(stackSize
))
1078 if ( m_internal
->GetState() != STATE_NEW
)
1080 // don't recreate thread
1081 return wxTHREAD_RUNNING
;
1084 // set up the thread attribute: right now, we only set thread priority
1085 pthread_attr_t attr
;
1086 pthread_attr_init(&attr
);
1088 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1090 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1092 wxLogError(_("Cannot retrieve thread scheduling policy."));
1096 /* the pthread.h contains too many spaces. This is a work-around */
1097 # undef sched_get_priority_max
1098 #undef sched_get_priority_min
1099 #define sched_get_priority_max(_pol_) \
1100 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1101 #define sched_get_priority_min(_pol_) \
1102 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1105 int max_prio
= sched_get_priority_max(policy
),
1106 min_prio
= sched_get_priority_min(policy
),
1107 prio
= m_internal
->GetPriority();
1109 if ( min_prio
== -1 || max_prio
== -1 )
1111 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1114 else if ( max_prio
== min_prio
)
1116 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1118 // notify the programmer that this doesn't work here
1119 wxLogWarning(_("Thread priority setting is ignored."));
1121 //else: we have default priority, so don't complain
1123 // anyhow, don't do anything because priority is just ignored
1127 struct sched_param sp
;
1128 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1130 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1133 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1135 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1137 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1140 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1142 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1143 // this will make the threads created by this process really concurrent
1144 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1146 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1148 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1150 // VZ: assume that this one is always available (it's rather fundamental),
1151 // if this function is ever missing we should try to use
1152 // pthread_detach() instead (after thread creation)
1155 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1157 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1160 // never try to join detached threads
1161 m_internal
->Detach();
1163 //else: threads are created joinable by default, it's ok
1165 // create the new OS thread object
1166 int rc
= pthread_create
1168 m_internal
->GetIdPtr(),
1174 if ( pthread_attr_destroy(&attr
) != 0 )
1176 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1181 m_internal
->SetState(STATE_EXITED
);
1183 return wxTHREAD_NO_RESOURCE
;
1186 m_state
= STATE_NEW
;
1188 return wxTHREAD_NO_ERROR
;
1191 wxThreadError
wxThread::Run()
1193 wxCriticalSectionLocker
lock(m_critsect
);
1195 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1196 wxT("must call wxThread::Create() first") );
1198 return m_internal
->Run();
1201 // -----------------------------------------------------------------------------
1203 // -----------------------------------------------------------------------------
1205 void wxThread::SetPriority(unsigned int prio
)
1207 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1208 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1209 wxT("invalid thread priority") );
1211 wxCriticalSectionLocker
lock(m_critsect
);
1213 switch ( m_internal
->GetState() )
1216 // thread not yet started, priority will be set when it is
1217 m_internal
->SetPriority(prio
);
1222 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1223 #if defined(__LINUX__)
1224 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1225 // a priority other than 0. Instead, we use the BSD setpriority
1226 // which alllows us to set a 'nice' value between 20 to -20. Only
1227 // super user can set a value less than zero (more negative yields
1228 // higher priority). setpriority set the static priority of a process,
1229 // but this is OK since Linux is configured as a thread per process.
1235 // Map Wx priorites (WXTHREAD_MIN_PRIORITY -
1236 // WXTHREAD_MAX_PRIORITY) into BSD priorities (20 - -20).
1237 // Do calculation of values instead of hard coding them
1238 // to make maintenance easier.
1240 pSpan
= ((float)(WXTHREAD_MAX_PRIORITY
- WXTHREAD_MIN_PRIORITY
)) / 2.0;
1242 // prio starts as ................... // value => (0) >= p <= (n)
1244 fPrio
= ((float)prio
) - pSpan
; // value => (-n) >= p <= (+n)
1246 fPrio
= 0.0 - fPrio
; // value => (+n) <= p >= (-n)
1248 fPrio
= fPrio
* (20. / pSpan
) + .5; // value => (20) <= p >= (-20)
1252 // Clamp prio from 20 - -20;
1253 iPrio
= (iPrio
> 20) ? 20 : iPrio
;
1254 iPrio
= (iPrio
< -20) ? -20 : iPrio
;
1256 if (setpriority(PRIO_PROCESS
, 0, iPrio
) == -1)
1258 wxLogError(_("Failed to set thread priority %d."), prio
);
1263 struct sched_param sparam
;
1264 sparam
.sched_priority
= prio
;
1266 if ( pthread_setschedparam(m_internal
->GetId(),
1267 SCHED_OTHER
, &sparam
) != 0 )
1269 wxLogError(_("Failed to set thread priority %d."), prio
);
1273 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1278 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1282 unsigned int wxThread::GetPriority() const
1284 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1286 return m_internal
->GetPriority();
1289 wxThreadIdType
wxThread::GetId() const
1291 return (wxThreadIdType
) m_internal
->GetId();
1294 // -----------------------------------------------------------------------------
1296 // -----------------------------------------------------------------------------
1298 wxThreadError
wxThread::Pause()
1300 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1301 _T("a thread can't pause itself") );
1303 wxCriticalSectionLocker
lock(m_critsect
);
1305 if ( m_internal
->GetState() != STATE_RUNNING
)
1307 wxLogDebug(wxT("Can't pause thread which is not running."));
1309 return wxTHREAD_NOT_RUNNING
;
1312 // just set a flag, the thread will be really paused only during the next
1313 // call to TestDestroy()
1314 m_internal
->SetState(STATE_PAUSED
);
1316 return wxTHREAD_NO_ERROR
;
1319 wxThreadError
wxThread::Resume()
1321 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1322 _T("a thread can't resume itself") );
1324 wxCriticalSectionLocker
lock(m_critsect
);
1326 wxThreadState state
= m_internal
->GetState();
1331 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1334 m_internal
->Resume();
1336 return wxTHREAD_NO_ERROR
;
1339 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1341 return wxTHREAD_NO_ERROR
;
1344 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1346 return wxTHREAD_MISC_ERROR
;
1350 // -----------------------------------------------------------------------------
1352 // -----------------------------------------------------------------------------
1354 wxThread::ExitCode
wxThread::Wait()
1356 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1357 _T("a thread can't wait for itself") );
1359 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1360 _T("can't wait for detached thread") );
1364 return m_internal
->GetExitCode();
1367 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1369 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1370 _T("a thread can't delete itself") );
1372 bool isDetached
= m_isDetached
;
1375 wxThreadState state
= m_internal
->GetState();
1377 // ask the thread to stop
1378 m_internal
->SetCancelFlag();
1385 // we need to wake up the thread so that PthreadStart() will
1386 // terminate - right now it's blocking on run semaphore in
1388 m_internal
->SignalRun();
1397 // resume the thread first
1398 m_internal
->Resume();
1405 // wait until the thread stops
1410 // return the exit code of the thread
1411 *rc
= m_internal
->GetExitCode();
1414 //else: can't wait for detached threads
1417 return wxTHREAD_NO_ERROR
;
1420 wxThreadError
wxThread::Kill()
1422 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1423 _T("a thread can't kill itself") );
1425 switch ( m_internal
->GetState() )
1429 return wxTHREAD_NOT_RUNNING
;
1432 // resume the thread first
1438 #ifdef HAVE_PTHREAD_CANCEL
1439 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1442 wxLogError(_("Failed to terminate a thread."));
1444 return wxTHREAD_MISC_ERROR
;
1449 // if we use cleanup function, this will be done from
1450 // wxPthreadCleanup()
1451 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1452 ScheduleThreadForDeletion();
1454 // don't call OnExit() here, it can only be called in the
1455 // threads context and we're in the context of another thread
1458 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1462 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1465 return wxTHREAD_NO_ERROR
;
1469 void wxThread::Exit(ExitCode status
)
1471 wxASSERT_MSG( This() == this,
1472 _T("wxThread::Exit() can only be called in the "
1473 "context of the same thread") );
1477 // from the moment we call OnExit(), the main program may terminate at
1478 // any moment, so mark this thread as being already in process of being
1479 // deleted or wxThreadModule::OnExit() will try to delete it again
1480 ScheduleThreadForDeletion();
1483 // don't enter m_critsect before calling OnExit() because the user code
1484 // might deadlock if, for example, it signals a condition in OnExit() (a
1485 // common case) while the main thread calls any of functions entering
1486 // m_critsect on us (almost all of them do)
1489 // delete C++ thread object if this is a detached thread - user is
1490 // responsible for doing this for joinable ones
1493 // FIXME I'm feeling bad about it - what if another thread function is
1494 // called (in another thread context) now? It will try to access
1495 // half destroyed object which will probably result in something
1496 // very bad - but we can't protect this by a crit section unless
1497 // we make it a global object, but this would mean that we can
1498 // only call one thread function at a time :-(
1502 // terminate the thread (pthread_exit() never returns)
1503 pthread_exit(status
);
1505 wxFAIL_MSG(_T("pthread_exit() failed"));
1508 // also test whether we were paused
1509 bool wxThread::TestDestroy()
1511 wxASSERT_MSG( This() == this,
1512 _T("wxThread::TestDestroy() can only be called in the "
1513 "context of the same thread") );
1517 if ( m_internal
->GetState() == STATE_PAUSED
)
1519 m_internal
->SetReallyPaused(TRUE
);
1521 // leave the crit section or the other threads will stop too if they
1522 // try to call any of (seemingly harmless) IsXXX() functions while we
1526 m_internal
->Pause();
1530 // thread wasn't requested to pause, nothing to do
1534 return m_internal
->WasCancelled();
1537 wxThread::~wxThread()
1542 // check that the thread either exited or couldn't be created
1543 if ( m_internal
->GetState() != STATE_EXITED
&&
1544 m_internal
->GetState() != STATE_NEW
)
1546 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1547 "running! The application may crash."), GetId());
1551 #endif // __WXDEBUG__
1555 // remove this thread from the global array
1556 gs_allThreads
.Remove(this);
1559 // -----------------------------------------------------------------------------
1561 // -----------------------------------------------------------------------------
1563 bool wxThread::IsRunning() const
1565 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1567 return m_internal
->GetState() == STATE_RUNNING
;
1570 bool wxThread::IsAlive() const
1572 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1574 switch ( m_internal
->GetState() )
1585 bool wxThread::IsPaused() const
1587 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1589 return (m_internal
->GetState() == STATE_PAUSED
);
1592 //--------------------------------------------------------------------
1594 //--------------------------------------------------------------------
1596 class wxThreadModule
: public wxModule
1599 virtual bool OnInit();
1600 virtual void OnExit();
1603 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1606 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1608 bool wxThreadModule::OnInit()
1610 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1613 wxLogSysError(rc
, _("Thread module initialization failed: "
1614 "failed to create thread key"));
1619 gs_tidMain
= pthread_self();
1622 gs_mutexGui
= new wxMutex();
1624 gs_mutexGui
->Lock();
1627 gs_mutexDeleteThread
= new wxMutex();
1628 gs_condAllDeleted
= new wxCondition( *gs_mutexDeleteThread
);
1633 void wxThreadModule::OnExit()
1635 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1637 // are there any threads left which are being deleted right now?
1638 size_t nThreadsBeingDeleted
;
1641 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1642 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1644 if ( nThreadsBeingDeleted
> 0 )
1646 wxLogTrace(TRACE_THREADS
,
1647 _T("Waiting for %lu threads to disappear"),
1648 (unsigned long)nThreadsBeingDeleted
);
1650 // have to wait until all of them disappear
1651 gs_condAllDeleted
->Wait();
1655 // terminate any threads left
1656 size_t count
= gs_allThreads
.GetCount();
1659 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1660 (unsigned long)count
);
1663 for ( size_t n
= 0u; n
< count
; n
++ )
1665 // Delete calls the destructor which removes the current entry. We
1666 // should only delete the first one each time.
1667 gs_allThreads
[0]->Delete();
1671 // destroy GUI mutex
1672 gs_mutexGui
->Unlock();
1677 // and free TLD slot
1678 (void)pthread_key_delete(gs_keySelf
);
1680 delete gs_condAllDeleted
;
1681 delete gs_mutexDeleteThread
;
1684 // ----------------------------------------------------------------------------
1686 // ----------------------------------------------------------------------------
1688 static void ScheduleThreadForDeletion()
1690 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1692 gs_nThreadsBeingDeleted
++;
1694 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1695 (unsigned long)gs_nThreadsBeingDeleted
,
1696 gs_nThreadsBeingDeleted
== 1 ? "" : "s");
1699 static void DeleteThread(wxThread
*This
)
1701 // gs_mutexDeleteThread should be unlocked before signalling the condition
1702 // or wxThreadModule::OnExit() would deadlock
1703 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1705 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1709 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1710 _T("no threads scheduled for deletion, yet we delete one?") );
1712 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1713 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1715 if ( !--gs_nThreadsBeingDeleted
)
1717 // no more threads left, signal it
1718 gs_condAllDeleted
->Signal();
1722 void wxMutexGuiEnter()
1725 gs_mutexGui
->Lock();
1729 void wxMutexGuiLeave()
1732 gs_mutexGui
->Unlock();
1736 // ----------------------------------------------------------------------------
1737 // include common implementation code
1738 // ----------------------------------------------------------------------------
1740 #include "wx/thrimpl.cpp"
1742 #endif // wxUSE_THREADS