1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/unix/threadpsx.cpp
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 // ----------------------------------------------------------------------------
24 // for compilers that support precompilation, includes "wx.h".
25 #include "wx/wxprec.h"
29 #include "wx/thread.h"
32 #include "wx/dynarray.h"
37 #include "wx/stopwatch.h"
38 #include "wx/module.h"
50 #ifdef HAVE_THR_SETCONCURRENCY
54 // we use wxFFile under Linux in GetCPUCount()
59 #include <sys/resource.h>
63 #define THR_ID(thr) ((long long)(thr)->GetId())
65 #define THR_ID(thr) ((long)(thr)->GetId())
68 // ----------------------------------------------------------------------------
70 // ----------------------------------------------------------------------------
72 // the possible states of the thread and transitions from them
75 STATE_NEW
, // didn't start execution yet (=> RUNNING)
76 STATE_RUNNING
, // running (=> PAUSED or EXITED)
77 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
78 STATE_EXITED
// thread doesn't exist any more
81 // the exit value of a thread which has been cancelled
82 static const wxThread::ExitCode EXITCODE_CANCELLED
= (wxThread::ExitCode
)-1;
84 // trace mask for wxThread operations
85 #define TRACE_THREADS _T("thread")
87 // you can get additional debugging messages for the semaphore operations
88 #define TRACE_SEMA _T("semaphore")
90 // ----------------------------------------------------------------------------
92 // ----------------------------------------------------------------------------
94 static void ScheduleThreadForDeletion();
95 static void DeleteThread(wxThread
*This
);
97 // ----------------------------------------------------------------------------
99 // ----------------------------------------------------------------------------
101 // an (non owning) array of pointers to threads
102 WX_DEFINE_ARRAY_PTR(wxThread
*, wxArrayThread
);
104 // an entry for a thread we can wait for
106 // -----------------------------------------------------------------------------
108 // -----------------------------------------------------------------------------
110 // we keep the list of all threads created by the application to be able to
111 // terminate them on exit if there are some left - otherwise the process would
113 static wxArrayThread gs_allThreads
;
115 // a mutex to protect gs_allThreads
116 static wxMutex
*gs_mutexAllThreads
= NULL
;
118 // the id of the main thread
119 static pthread_t gs_tidMain
= (pthread_t
)-1;
121 // the key for the pointer to the associated wxThread object
122 static pthread_key_t gs_keySelf
;
124 // the number of threads which are being deleted - the program won't exit
125 // until there are any left
126 static size_t gs_nThreadsBeingDeleted
= 0;
128 // a mutex to protect gs_nThreadsBeingDeleted
129 static wxMutex
*gs_mutexDeleteThread
= (wxMutex
*)NULL
;
131 // and a condition variable which will be signaled when all
132 // gs_nThreadsBeingDeleted will have been deleted
133 static wxCondition
*gs_condAllDeleted
= (wxCondition
*)NULL
;
135 // this mutex must be acquired before any call to a GUI function
136 // (it's not inside #if wxUSE_GUI because this file is compiled as part
138 static wxMutex
*gs_mutexGui
= NULL
;
140 // when we wait for a thread to exit, we're blocking on a condition which the
141 // thread signals in its SignalExit() method -- but this condition can't be a
142 // member of the thread itself as a detached thread may delete itself at any
143 // moment and accessing the condition member of the thread after this would
144 // result in a disaster
146 // so instead we maintain a global list of the structs below for the threads
147 // we're interested in waiting on
149 // ============================================================================
150 // wxMutex implementation
151 // ============================================================================
153 // ----------------------------------------------------------------------------
155 // ----------------------------------------------------------------------------
157 // this is a simple wrapper around pthread_mutex_t which provides error
159 class wxMutexInternal
162 wxMutexInternal(wxMutexType mutexType
);
166 wxMutexError
Lock(unsigned long ms
);
167 wxMutexError
TryLock();
168 wxMutexError
Unlock();
170 bool IsOk() const { return m_isOk
; }
173 // convert the result of pthread_mutex_[timed]lock() call to wx return code
174 wxMutexError
HandleLockResult(int err
);
177 pthread_mutex_t m_mutex
;
180 // wxConditionInternal uses our m_mutex
181 friend class wxConditionInternal
;
184 #if defined(HAVE_PTHREAD_MUTEXATTR_T) && \
185 wxUSE_UNIX && !defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE_DECL)
186 // on some systems pthread_mutexattr_settype() is not in the headers (but it is
187 // in the library, otherwise we wouldn't compile this code at all)
188 extern "C" int pthread_mutexattr_settype(pthread_mutexattr_t
*, int);
191 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
196 case wxMUTEX_RECURSIVE
:
197 // support recursive locks like Win32, i.e. a thread can lock a
198 // mutex which it had itself already locked
200 // unfortunately initialization of recursive mutexes is non
201 // portable, so try several methods
202 #ifdef HAVE_PTHREAD_MUTEXATTR_T
204 pthread_mutexattr_t attr
;
205 pthread_mutexattr_init(&attr
);
206 pthread_mutexattr_settype(&attr
, PTHREAD_MUTEX_RECURSIVE
);
208 err
= pthread_mutex_init(&m_mutex
, &attr
);
210 #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER)
211 // we can use this only as initializer so we have to assign it
212 // first to a temp var - assigning directly to m_mutex wouldn't
215 pthread_mutex_t mutex
= PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP
;
218 #else // no recursive mutexes
220 #endif // HAVE_PTHREAD_MUTEXATTR_T/...
224 wxFAIL_MSG( _T("unknown mutex type") );
227 case wxMUTEX_DEFAULT
:
228 err
= pthread_mutex_init(&m_mutex
, NULL
);
235 wxLogApiError( wxT("pthread_mutex_init()"), err
);
239 wxMutexInternal::~wxMutexInternal()
243 int err
= pthread_mutex_destroy(&m_mutex
);
246 wxLogApiError( wxT("pthread_mutex_destroy()"), err
);
251 wxMutexError
wxMutexInternal::Lock()
253 return HandleLockResult(pthread_mutex_lock(&m_mutex
));
256 wxMutexError
wxMutexInternal::Lock(unsigned long ms
)
258 static const long MSEC_IN_SEC
= 1000;
259 static const long NSEC_IN_MSEC
= 1000000;
260 static const long NSEC_IN_USEC
= 1000;
261 static const long NSEC_IN_SEC
= MSEC_IN_SEC
* NSEC_IN_MSEC
;
263 time_t seconds
= ms
/MSEC_IN_SEC
;
264 long nanoseconds
= (ms
% MSEC_IN_SEC
) * NSEC_IN_MSEC
;
265 timespec ts
= { 0, 0 };
267 // normally we should use clock_gettime(CLOCK_REALTIME) here but this
268 // function is in librt and we don't link with it currently, so use
269 // gettimeofday() instead -- if it turns out that this is really too
270 // imprecise, we should modify configure to check if clock_gettime() is
271 // available and whether it requires -lrt and use it instead
273 if ( clock_gettime(CLOCK_REALTIME
, &ts
) == 0 )
278 if ( wxGetTimeOfDay(&tv
) != -1 )
280 ts
.tv_sec
= tv
.tv_sec
;
281 ts
.tv_nsec
= tv
.tv_usec
*NSEC_IN_USEC
;
284 else // fall back on system timer
286 ts
.tv_sec
= time(NULL
);
289 ts
.tv_sec
+= seconds
;
290 ts
.tv_nsec
+= nanoseconds
;
291 if ( ts
.tv_nsec
> NSEC_IN_SEC
)
294 ts
.tv_nsec
-= NSEC_IN_SEC
;
297 return HandleLockResult(pthread_mutex_timedlock(&m_mutex
, &ts
));
300 wxMutexError
wxMutexInternal::HandleLockResult(int err
)
305 // only error checking mutexes return this value and so it's an
306 // unexpected situation -- hence use assert, not wxLogDebug
307 wxFAIL_MSG( _T("mutex deadlock prevented") );
308 return wxMUTEX_DEAD_LOCK
;
311 wxLogDebug(_T("pthread_mutex_[timed]lock(): mutex not initialized"));
315 return wxMUTEX_TIMEOUT
;
318 return wxMUTEX_NO_ERROR
;
321 wxLogApiError(_T("pthread_mutex_[timed]lock()"), err
);
324 return wxMUTEX_MISC_ERROR
;
328 wxMutexError
wxMutexInternal::TryLock()
330 int err
= pthread_mutex_trylock(&m_mutex
);
334 // not an error: mutex is already locked, but we're prepared for
339 wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized."));
343 return wxMUTEX_NO_ERROR
;
346 wxLogApiError(_T("pthread_mutex_trylock()"), err
);
349 return wxMUTEX_MISC_ERROR
;
352 wxMutexError
wxMutexInternal::Unlock()
354 int err
= pthread_mutex_unlock(&m_mutex
);
358 // we don't own the mutex
359 return wxMUTEX_UNLOCKED
;
362 wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized."));
366 return wxMUTEX_NO_ERROR
;
369 wxLogApiError(_T("pthread_mutex_unlock()"), err
);
372 return wxMUTEX_MISC_ERROR
;
375 // ===========================================================================
376 // wxCondition implementation
377 // ===========================================================================
379 // ---------------------------------------------------------------------------
380 // wxConditionInternal
381 // ---------------------------------------------------------------------------
383 // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence
384 // with a pthread_mutex_t)
385 class wxConditionInternal
388 wxConditionInternal(wxMutex
& mutex
);
389 ~wxConditionInternal();
391 bool IsOk() const { return m_isOk
&& m_mutex
.IsOk(); }
394 wxCondError
WaitTimeout(unsigned long milliseconds
);
396 wxCondError
Signal();
397 wxCondError
Broadcast();
400 // get the POSIX mutex associated with us
401 pthread_mutex_t
*GetPMutex() const { return &m_mutex
.m_internal
->m_mutex
; }
404 pthread_cond_t m_cond
;
409 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
412 int err
= pthread_cond_init(&m_cond
, NULL
/* default attributes */);
418 wxLogApiError(_T("pthread_cond_init()"), err
);
422 wxConditionInternal::~wxConditionInternal()
426 int err
= pthread_cond_destroy(&m_cond
);
429 wxLogApiError(_T("pthread_cond_destroy()"), err
);
434 wxCondError
wxConditionInternal::Wait()
436 int err
= pthread_cond_wait(&m_cond
, GetPMutex());
439 wxLogApiError(_T("pthread_cond_wait()"), err
);
441 return wxCOND_MISC_ERROR
;
444 return wxCOND_NO_ERROR
;
447 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
449 wxLongLong curtime
= wxGetLocalTimeMillis();
450 curtime
+= milliseconds
;
451 wxLongLong temp
= curtime
/ 1000;
452 int sec
= temp
.GetLo();
454 temp
= curtime
- temp
;
455 int millis
= temp
.GetLo();
460 tspec
.tv_nsec
= millis
* 1000L * 1000L;
462 int err
= pthread_cond_timedwait( &m_cond
, GetPMutex(), &tspec
);
466 return wxCOND_TIMEOUT
;
469 return wxCOND_NO_ERROR
;
472 wxLogApiError(_T("pthread_cond_timedwait()"), err
);
475 return wxCOND_MISC_ERROR
;
478 wxCondError
wxConditionInternal::Signal()
480 int err
= pthread_cond_signal(&m_cond
);
483 wxLogApiError(_T("pthread_cond_signal()"), err
);
485 return wxCOND_MISC_ERROR
;
488 return wxCOND_NO_ERROR
;
491 wxCondError
wxConditionInternal::Broadcast()
493 int err
= pthread_cond_broadcast(&m_cond
);
496 wxLogApiError(_T("pthread_cond_broadcast()"), err
);
498 return wxCOND_MISC_ERROR
;
501 return wxCOND_NO_ERROR
;
504 // ===========================================================================
505 // wxSemaphore implementation
506 // ===========================================================================
508 // ---------------------------------------------------------------------------
509 // wxSemaphoreInternal
510 // ---------------------------------------------------------------------------
512 // we implement the semaphores using mutexes and conditions instead of using
513 // the sem_xxx() POSIX functions because they're not widely available and also
514 // because it's impossible to implement WaitTimeout() using them
515 class wxSemaphoreInternal
518 wxSemaphoreInternal(int initialcount
, int maxcount
);
520 bool IsOk() const { return m_isOk
; }
523 wxSemaError
TryWait();
524 wxSemaError
WaitTimeout(unsigned long milliseconds
);
538 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
542 if ( (initialcount
< 0 || maxcount
< 0) ||
543 ((maxcount
> 0) && (initialcount
> maxcount
)) )
545 wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") );
551 m_maxcount
= (size_t)maxcount
;
552 m_count
= (size_t)initialcount
;
555 m_isOk
= m_mutex
.IsOk() && m_cond
.IsOk();
558 wxSemaError
wxSemaphoreInternal::Wait()
560 wxMutexLocker
locker(m_mutex
);
562 while ( m_count
== 0 )
564 wxLogTrace(TRACE_SEMA
,
565 _T("Thread %ld waiting for semaphore to become signalled"),
566 wxThread::GetCurrentId());
568 if ( m_cond
.Wait() != wxCOND_NO_ERROR
)
569 return wxSEMA_MISC_ERROR
;
571 wxLogTrace(TRACE_SEMA
,
572 _T("Thread %ld finished waiting for semaphore, count = %lu"),
573 wxThread::GetCurrentId(), (unsigned long)m_count
);
578 return wxSEMA_NO_ERROR
;
581 wxSemaError
wxSemaphoreInternal::TryWait()
583 wxMutexLocker
locker(m_mutex
);
590 return wxSEMA_NO_ERROR
;
593 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
595 wxMutexLocker
locker(m_mutex
);
597 wxLongLong startTime
= wxGetLocalTimeMillis();
599 while ( m_count
== 0 )
601 wxLongLong elapsed
= wxGetLocalTimeMillis() - startTime
;
602 long remainingTime
= (long)milliseconds
- (long)elapsed
.GetLo();
603 if ( remainingTime
<= 0 )
606 return wxSEMA_TIMEOUT
;
609 switch ( m_cond
.WaitTimeout(remainingTime
) )
612 return wxSEMA_TIMEOUT
;
615 return wxSEMA_MISC_ERROR
;
617 case wxCOND_NO_ERROR
:
624 return wxSEMA_NO_ERROR
;
627 wxSemaError
wxSemaphoreInternal::Post()
629 wxMutexLocker
locker(m_mutex
);
631 if ( m_maxcount
> 0 && m_count
== m_maxcount
)
633 return wxSEMA_OVERFLOW
;
638 wxLogTrace(TRACE_SEMA
,
639 _T("Thread %ld about to signal semaphore, count = %lu"),
640 wxThread::GetCurrentId(), (unsigned long)m_count
);
642 return m_cond
.Signal() == wxCOND_NO_ERROR
? wxSEMA_NO_ERROR
646 // ===========================================================================
647 // wxThread implementation
648 // ===========================================================================
650 // the thread callback functions must have the C linkage
654 #ifdef wxHAVE_PTHREAD_CLEANUP
655 // thread exit function
656 void wxPthreadCleanup(void *ptr
);
657 #endif // wxHAVE_PTHREAD_CLEANUP
659 void *wxPthreadStart(void *ptr
);
663 // ----------------------------------------------------------------------------
665 // ----------------------------------------------------------------------------
667 class wxThreadInternal
673 // thread entry function
674 static void *PthreadStart(wxThread
*thread
);
679 // unblock the thread allowing it to run
680 void SignalRun() { m_semRun
.Post(); }
681 // ask the thread to terminate
683 // go to sleep until Resume() is called
690 int GetPriority() const { return m_prio
; }
691 void SetPriority(int prio
) { m_prio
= prio
; }
693 wxThreadState
GetState() const { return m_state
; }
694 void SetState(wxThreadState state
)
697 static const wxChar
*stateNames
[] =
705 wxLogTrace(TRACE_THREADS
, _T("Thread %ld: %s => %s."),
706 (long)GetId(), stateNames
[m_state
], stateNames
[state
]);
707 #endif // __WXDEBUG__
712 pthread_t
GetId() const { return m_threadId
; }
713 pthread_t
*GetIdPtr() { return &m_threadId
; }
715 void SetCancelFlag() { m_cancelled
= true; }
716 bool WasCancelled() const { return m_cancelled
; }
718 void SetExitCode(wxThread::ExitCode exitcode
) { m_exitcode
= exitcode
; }
719 wxThread::ExitCode
GetExitCode() const { return m_exitcode
; }
722 void SetReallyPaused(bool paused
) { m_isPaused
= paused
; }
723 bool IsReallyPaused() const { return m_isPaused
; }
725 // tell the thread that it is a detached one
728 wxCriticalSectionLocker
lock(m_csJoinFlag
);
730 m_shouldBeJoined
= false;
734 #ifdef wxHAVE_PTHREAD_CLEANUP
735 // this is used by wxPthreadCleanup() only
736 static void Cleanup(wxThread
*thread
);
737 #endif // wxHAVE_PTHREAD_CLEANUP
740 pthread_t m_threadId
; // id of the thread
741 wxThreadState m_state
; // see wxThreadState enum
742 int m_prio
; // in wxWidgets units: from 0 to 100
744 // this flag is set when the thread should terminate
747 // this flag is set when the thread is blocking on m_semSuspend
750 // the thread exit code - only used for joinable (!detached) threads and
751 // is only valid after the thread termination
752 wxThread::ExitCode m_exitcode
;
754 // many threads may call Wait(), but only one of them should call
755 // pthread_join(), so we have to keep track of this
756 wxCriticalSection m_csJoinFlag
;
757 bool m_shouldBeJoined
;
760 // this semaphore is posted by Run() and the threads Entry() is not
761 // called before it is done
762 wxSemaphore m_semRun
;
764 // this one is signaled when the thread should resume after having been
766 wxSemaphore m_semSuspend
;
769 // ----------------------------------------------------------------------------
770 // thread startup and exit functions
771 // ----------------------------------------------------------------------------
773 void *wxPthreadStart(void *ptr
)
775 return wxThreadInternal::PthreadStart((wxThread
*)ptr
);
778 void *wxThreadInternal::PthreadStart(wxThread
*thread
)
780 wxThreadInternal
*pthread
= thread
->m_internal
;
782 wxLogTrace(TRACE_THREADS
, _T("Thread %ld started."), THR_ID(pthread
));
784 // associate the thread pointer with the newly created thread so that
785 // wxThread::This() will work
786 int rc
= pthread_setspecific(gs_keySelf
, thread
);
789 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
794 // have to declare this before pthread_cleanup_push() which defines a
798 #ifdef wxHAVE_PTHREAD_CLEANUP
799 // install the cleanup handler which will be called if the thread is
801 pthread_cleanup_push(wxPthreadCleanup
, thread
);
802 #endif // wxHAVE_PTHREAD_CLEANUP
804 // wait for the semaphore to be posted from Run()
805 pthread
->m_semRun
.Wait();
807 // test whether we should run the run at all - may be it was deleted
808 // before it started to Run()?
810 wxCriticalSectionLocker
lock(thread
->m_critsect
);
812 dontRunAtAll
= pthread
->GetState() == STATE_NEW
&&
813 pthread
->WasCancelled();
818 // call the main entry
819 wxLogTrace(TRACE_THREADS
,
820 _T("Thread %ld about to enter its Entry()."),
823 pthread
->m_exitcode
= thread
->Entry();
825 wxLogTrace(TRACE_THREADS
,
826 _T("Thread %ld Entry() returned %lu."),
827 THR_ID(pthread
), wxPtrToUInt(pthread
->m_exitcode
));
830 wxCriticalSectionLocker
lock(thread
->m_critsect
);
832 // change the state of the thread to "exited" so that
833 // wxPthreadCleanup handler won't do anything from now (if it's
834 // called before we do pthread_cleanup_pop below)
835 pthread
->SetState(STATE_EXITED
);
839 // NB: pthread_cleanup_push/pop() are macros and pop contains the matching
840 // '}' for the '{' in push, so they must be used in the same block!
841 #ifdef wxHAVE_PTHREAD_CLEANUP
843 // under Tru64 we get a warning from macro expansion
845 #pragma message disable(declbutnotref)
848 // remove the cleanup handler without executing it
849 pthread_cleanup_pop(FALSE
);
852 #pragma message restore
854 #endif // wxHAVE_PTHREAD_CLEANUP
858 // FIXME: deleting a possibly joinable thread here???
861 return EXITCODE_CANCELLED
;
865 // terminate the thread
866 thread
->Exit(pthread
->m_exitcode
);
868 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
874 #ifdef wxHAVE_PTHREAD_CLEANUP
876 // this handler is called when the thread is cancelled
877 extern "C" void wxPthreadCleanup(void *ptr
)
879 wxThreadInternal::Cleanup((wxThread
*)ptr
);
882 void wxThreadInternal::Cleanup(wxThread
*thread
)
884 if (pthread_getspecific(gs_keySelf
) == 0) return;
886 wxCriticalSectionLocker
lock(thread
->m_critsect
);
887 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
889 // thread is already considered as finished.
894 // exit the thread gracefully
895 thread
->Exit(EXITCODE_CANCELLED
);
898 #endif // wxHAVE_PTHREAD_CLEANUP
900 // ----------------------------------------------------------------------------
902 // ----------------------------------------------------------------------------
904 wxThreadInternal::wxThreadInternal()
908 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
912 // set to true only when the thread starts waiting on m_semSuspend
915 // defaults for joinable threads
916 m_shouldBeJoined
= true;
917 m_isDetached
= false;
920 wxThreadInternal::~wxThreadInternal()
924 wxThreadError
wxThreadInternal::Run()
926 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
927 wxT("thread may only be started once after Create()") );
929 SetState(STATE_RUNNING
);
931 // wake up threads waiting for our start
934 return wxTHREAD_NO_ERROR
;
937 void wxThreadInternal::Wait()
939 wxCHECK_RET( !m_isDetached
, _T("can't wait for a detached thread") );
941 // if the thread we're waiting for is waiting for the GUI mutex, we will
942 // deadlock so make sure we release it temporarily
943 if ( wxThread::IsMain() )
946 wxLogTrace(TRACE_THREADS
,
947 _T("Starting to wait for thread %ld to exit."),
950 // to avoid memory leaks we should call pthread_join(), but it must only be
951 // done once so use a critical section to serialize the code below
953 wxCriticalSectionLocker
lock(m_csJoinFlag
);
955 if ( m_shouldBeJoined
)
957 // FIXME shouldn't we set cancellation type to DISABLED here? If
958 // we're cancelled inside pthread_join(), things will almost
959 // certainly break - but if we disable the cancellation, we
961 if ( pthread_join(GetId(), &m_exitcode
) != 0 )
963 // this is a serious problem, so use wxLogError and not
964 // wxLogDebug: it is possible to bring the system to its knees
965 // by creating too many threads and not joining them quite
967 wxLogError(_("Failed to join a thread, potential memory leak detected - please restart the program"));
970 m_shouldBeJoined
= false;
974 // reacquire GUI mutex
975 if ( wxThread::IsMain() )
979 void wxThreadInternal::Pause()
981 // the state is set from the thread which pauses us first, this function
982 // is called later so the state should have been already set
983 wxCHECK_RET( m_state
== STATE_PAUSED
,
984 wxT("thread must first be paused with wxThread::Pause().") );
986 wxLogTrace(TRACE_THREADS
,
987 _T("Thread %ld goes to sleep."), THR_ID(this));
989 // wait until the semaphore is Post()ed from Resume()
993 void wxThreadInternal::Resume()
995 wxCHECK_RET( m_state
== STATE_PAUSED
,
996 wxT("can't resume thread which is not suspended.") );
998 // the thread might be not actually paused yet - if there were no call to
999 // TestDestroy() since the last call to Pause() for example
1000 if ( IsReallyPaused() )
1002 wxLogTrace(TRACE_THREADS
,
1003 _T("Waking up thread %ld"), THR_ID(this));
1006 m_semSuspend
.Post();
1009 SetReallyPaused(false);
1013 wxLogTrace(TRACE_THREADS
,
1014 _T("Thread %ld is not yet really paused"), THR_ID(this));
1017 SetState(STATE_RUNNING
);
1020 // -----------------------------------------------------------------------------
1021 // wxThread static functions
1022 // -----------------------------------------------------------------------------
1024 wxThread
*wxThread::This()
1026 return (wxThread
*)pthread_getspecific(gs_keySelf
);
1029 bool wxThread::IsMain()
1031 return (bool)pthread_equal(pthread_self(), gs_tidMain
) || gs_tidMain
== (pthread_t
)-1;
1034 void wxThread::Yield()
1036 #ifdef HAVE_SCHED_YIELD
1041 void wxThread::Sleep(unsigned long milliseconds
)
1043 wxMilliSleep(milliseconds
);
1046 int wxThread::GetCPUCount()
1048 #if defined(_SC_NPROCESSORS_ONLN)
1049 // this works for Solaris and Linux 2.6
1050 int rc
= sysconf(_SC_NPROCESSORS_ONLN
);
1055 #elif defined(__LINUX__) && wxUSE_FFILE
1056 // read from proc (can't use wxTextFile here because it's a special file:
1057 // it has 0 size but still can be read from)
1060 wxFFile
file(_T("/proc/cpuinfo"));
1061 if ( file
.IsOpened() )
1063 // slurp the whole file
1065 if ( file
.ReadAll(&s
) )
1067 // (ab)use Replace() to find the number of "processor: num" strings
1068 size_t count
= s
.Replace(_T("processor\t:"), _T(""));
1074 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
1078 wxLogDebug(_T("failed to read /proc/cpuinfo"));
1081 #endif // different ways to get number of CPUs
1087 // VMS is a 64 bit system and threads have 64 bit pointers.
1088 // FIXME: also needed for other systems????
1090 unsigned long long wxThread::GetCurrentId()
1092 return (unsigned long long)pthread_self();
1097 unsigned long wxThread::GetCurrentId()
1099 return (unsigned long)pthread_self();
1102 #endif // __VMS/!__VMS
1105 bool wxThread::SetConcurrency(size_t level
)
1107 #ifdef HAVE_THR_SETCONCURRENCY
1108 int rc
= thr_setconcurrency(level
);
1111 wxLogSysError(rc
, _T("thr_setconcurrency() failed"));
1115 #else // !HAVE_THR_SETCONCURRENCY
1116 // ok only for the default value
1118 #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
1121 // -----------------------------------------------------------------------------
1123 // -----------------------------------------------------------------------------
1125 wxThread::wxThread(wxThreadKind kind
)
1127 // add this thread to the global list of all threads
1129 wxMutexLocker
lock(*gs_mutexAllThreads
);
1131 gs_allThreads
.Add(this);
1134 m_internal
= new wxThreadInternal();
1136 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1139 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1140 #define WXUNUSED_STACKSIZE(identifier) identifier
1142 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1145 wxThreadError
wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize
))
1147 if ( m_internal
->GetState() != STATE_NEW
)
1149 // don't recreate thread
1150 return wxTHREAD_RUNNING
;
1153 // set up the thread attribute: right now, we only set thread priority
1154 pthread_attr_t attr
;
1155 pthread_attr_init(&attr
);
1157 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1159 pthread_attr_setstacksize(&attr
, stackSize
);
1162 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1164 if ( pthread_attr_getschedpolicy(&attr
, &policy
) != 0 )
1166 wxLogError(_("Cannot retrieve thread scheduling policy."));
1170 /* the pthread.h contains too many spaces. This is a work-around */
1171 # undef sched_get_priority_max
1172 #undef sched_get_priority_min
1173 #define sched_get_priority_max(_pol_) \
1174 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1175 #define sched_get_priority_min(_pol_) \
1176 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1179 int max_prio
= sched_get_priority_max(policy
),
1180 min_prio
= sched_get_priority_min(policy
),
1181 prio
= m_internal
->GetPriority();
1183 if ( min_prio
== -1 || max_prio
== -1 )
1185 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1188 else if ( max_prio
== min_prio
)
1190 if ( prio
!= WXTHREAD_DEFAULT_PRIORITY
)
1192 // notify the programmer that this doesn't work here
1193 wxLogWarning(_("Thread priority setting is ignored."));
1195 //else: we have default priority, so don't complain
1197 // anyhow, don't do anything because priority is just ignored
1201 struct sched_param sp
;
1202 if ( pthread_attr_getschedparam(&attr
, &sp
) != 0 )
1204 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1207 sp
.sched_priority
= min_prio
+ (prio
*(max_prio
- min_prio
))/100;
1209 if ( pthread_attr_setschedparam(&attr
, &sp
) != 0 )
1211 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1214 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1216 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1217 // this will make the threads created by this process really concurrent
1218 if ( pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
) != 0 )
1220 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1222 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1224 // VZ: assume that this one is always available (it's rather fundamental),
1225 // if this function is ever missing we should try to use
1226 // pthread_detach() instead (after thread creation)
1229 if ( pthread_attr_setdetachstate(&attr
, PTHREAD_CREATE_DETACHED
) != 0 )
1231 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1234 // never try to join detached threads
1235 m_internal
->Detach();
1237 //else: threads are created joinable by default, it's ok
1239 // create the new OS thread object
1240 int rc
= pthread_create
1242 m_internal
->GetIdPtr(),
1248 if ( pthread_attr_destroy(&attr
) != 0 )
1250 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1255 m_internal
->SetState(STATE_EXITED
);
1257 return wxTHREAD_NO_RESOURCE
;
1260 return wxTHREAD_NO_ERROR
;
1263 wxThreadError
wxThread::Run()
1265 wxCriticalSectionLocker
lock(m_critsect
);
1267 wxCHECK_MSG( m_internal
->GetId(), wxTHREAD_MISC_ERROR
,
1268 wxT("must call wxThread::Create() first") );
1270 return m_internal
->Run();
1273 // -----------------------------------------------------------------------------
1275 // -----------------------------------------------------------------------------
1277 void wxThread::SetPriority(unsigned int prio
)
1279 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
1280 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
1281 wxT("invalid thread priority") );
1283 wxCriticalSectionLocker
lock(m_critsect
);
1285 switch ( m_internal
->GetState() )
1288 // thread not yet started, priority will be set when it is
1289 m_internal
->SetPriority(prio
);
1294 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1295 #if defined(__LINUX__)
1296 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1297 // a priority other than 0. Instead, we use the BSD setpriority
1298 // which alllows us to set a 'nice' value between 20 to -20. Only
1299 // super user can set a value less than zero (more negative yields
1300 // higher priority). setpriority set the static priority of a
1301 // process, but this is OK since Linux is configured as a thread
1304 // FIXME this is not true for 2.6!!
1306 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1307 // to Unix priorities 20..-20
1308 if ( setpriority(PRIO_PROCESS
, 0, -(2*prio
)/5 + 20) == -1 )
1310 wxLogError(_("Failed to set thread priority %d."), prio
);
1314 struct sched_param sparam
;
1315 sparam
.sched_priority
= prio
;
1317 if ( pthread_setschedparam(m_internal
->GetId(),
1318 SCHED_OTHER
, &sparam
) != 0 )
1320 wxLogError(_("Failed to set thread priority %d."), prio
);
1324 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1329 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1333 unsigned int wxThread::GetPriority() const
1335 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1337 return m_internal
->GetPriority();
1340 wxThreadIdType
wxThread::GetId() const
1342 return (wxThreadIdType
) m_internal
->GetId();
1345 // -----------------------------------------------------------------------------
1347 // -----------------------------------------------------------------------------
1349 wxThreadError
wxThread::Pause()
1351 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1352 _T("a thread can't pause itself") );
1354 wxCriticalSectionLocker
lock(m_critsect
);
1356 if ( m_internal
->GetState() != STATE_RUNNING
)
1358 wxLogDebug(wxT("Can't pause thread which is not running."));
1360 return wxTHREAD_NOT_RUNNING
;
1363 // just set a flag, the thread will be really paused only during the next
1364 // call to TestDestroy()
1365 m_internal
->SetState(STATE_PAUSED
);
1367 return wxTHREAD_NO_ERROR
;
1370 wxThreadError
wxThread::Resume()
1372 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1373 _T("a thread can't resume itself") );
1375 wxCriticalSectionLocker
lock(m_critsect
);
1377 wxThreadState state
= m_internal
->GetState();
1382 wxLogTrace(TRACE_THREADS
, _T("Thread %ld suspended, resuming."),
1385 m_internal
->Resume();
1387 return wxTHREAD_NO_ERROR
;
1390 wxLogTrace(TRACE_THREADS
, _T("Thread %ld exited, won't resume."),
1392 return wxTHREAD_NO_ERROR
;
1395 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1397 return wxTHREAD_MISC_ERROR
;
1401 // -----------------------------------------------------------------------------
1403 // -----------------------------------------------------------------------------
1405 wxThread::ExitCode
wxThread::Wait()
1407 wxCHECK_MSG( This() != this, (ExitCode
)-1,
1408 _T("a thread can't wait for itself") );
1410 wxCHECK_MSG( !m_isDetached
, (ExitCode
)-1,
1411 _T("can't wait for detached thread") );
1415 return m_internal
->GetExitCode();
1418 wxThreadError
wxThread::Delete(ExitCode
*rc
)
1420 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1421 _T("a thread can't delete itself") );
1423 bool isDetached
= m_isDetached
;
1426 wxThreadState state
= m_internal
->GetState();
1428 // ask the thread to stop
1429 m_internal
->SetCancelFlag();
1436 // we need to wake up the thread so that PthreadStart() will
1437 // terminate - right now it's blocking on run semaphore in
1439 m_internal
->SignalRun();
1448 // resume the thread first
1449 m_internal
->Resume();
1456 // wait until the thread stops
1461 // return the exit code of the thread
1462 *rc
= m_internal
->GetExitCode();
1465 //else: can't wait for detached threads
1468 return wxTHREAD_NO_ERROR
;
1471 wxThreadError
wxThread::Kill()
1473 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR
,
1474 _T("a thread can't kill itself") );
1476 switch ( m_internal
->GetState() )
1480 return wxTHREAD_NOT_RUNNING
;
1483 // resume the thread first
1489 #ifdef HAVE_PTHREAD_CANCEL
1490 if ( pthread_cancel(m_internal
->GetId()) != 0 )
1491 #endif // HAVE_PTHREAD_CANCEL
1493 wxLogError(_("Failed to terminate a thread."));
1495 return wxTHREAD_MISC_ERROR
;
1498 #ifdef HAVE_PTHREAD_CANCEL
1501 // if we use cleanup function, this will be done from
1502 // wxPthreadCleanup()
1503 #ifndef wxHAVE_PTHREAD_CLEANUP
1504 ScheduleThreadForDeletion();
1506 // don't call OnExit() here, it can only be called in the
1507 // threads context and we're in the context of another thread
1510 #endif // wxHAVE_PTHREAD_CLEANUP
1514 m_internal
->SetExitCode(EXITCODE_CANCELLED
);
1517 return wxTHREAD_NO_ERROR
;
1518 #endif // HAVE_PTHREAD_CANCEL
1522 void wxThread::Exit(ExitCode status
)
1524 wxASSERT_MSG( This() == this,
1525 _T("wxThread::Exit() can only be called in the context of the same thread") );
1529 // from the moment we call OnExit(), the main program may terminate at
1530 // any moment, so mark this thread as being already in process of being
1531 // deleted or wxThreadModule::OnExit() will try to delete it again
1532 ScheduleThreadForDeletion();
1535 // don't enter m_critsect before calling OnExit() because the user code
1536 // might deadlock if, for example, it signals a condition in OnExit() (a
1537 // common case) while the main thread calls any of functions entering
1538 // m_critsect on us (almost all of them do)
1541 // delete C++ thread object if this is a detached thread - user is
1542 // responsible for doing this for joinable ones
1545 // FIXME I'm feeling bad about it - what if another thread function is
1546 // called (in another thread context) now? It will try to access
1547 // half destroyed object which will probably result in something
1548 // very bad - but we can't protect this by a crit section unless
1549 // we make it a global object, but this would mean that we can
1550 // only call one thread function at a time :-(
1552 pthread_setspecific(gs_keySelf
, 0);
1557 m_internal
->SetState(STATE_EXITED
);
1561 // terminate the thread (pthread_exit() never returns)
1562 pthread_exit(status
);
1564 wxFAIL_MSG(_T("pthread_exit() failed"));
1567 // also test whether we were paused
1568 bool wxThread::TestDestroy()
1570 wxASSERT_MSG( This() == this,
1571 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1575 if ( m_internal
->GetState() == STATE_PAUSED
)
1577 m_internal
->SetReallyPaused(true);
1579 // leave the crit section or the other threads will stop too if they
1580 // try to call any of (seemingly harmless) IsXXX() functions while we
1584 m_internal
->Pause();
1588 // thread wasn't requested to pause, nothing to do
1592 return m_internal
->WasCancelled();
1595 wxThread::~wxThread()
1600 // check that the thread either exited or couldn't be created
1601 if ( m_internal
->GetState() != STATE_EXITED
&&
1602 m_internal
->GetState() != STATE_NEW
)
1604 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1609 #endif // __WXDEBUG__
1613 // remove this thread from the global array
1615 wxMutexLocker
lock(*gs_mutexAllThreads
);
1617 gs_allThreads
.Remove(this);
1621 // -----------------------------------------------------------------------------
1623 // -----------------------------------------------------------------------------
1625 bool wxThread::IsRunning() const
1627 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1629 return m_internal
->GetState() == STATE_RUNNING
;
1632 bool wxThread::IsAlive() const
1634 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1636 switch ( m_internal
->GetState() )
1647 bool wxThread::IsPaused() const
1649 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
1651 return (m_internal
->GetState() == STATE_PAUSED
);
1654 //--------------------------------------------------------------------
1656 //--------------------------------------------------------------------
1658 class wxThreadModule
: public wxModule
1661 virtual bool OnInit();
1662 virtual void OnExit();
1665 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1668 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1670 bool wxThreadModule::OnInit()
1672 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
1675 wxLogSysError(rc
, _("Thread module initialization failed: failed to create thread key"));
1680 gs_tidMain
= pthread_self();
1682 gs_mutexAllThreads
= new wxMutex();
1684 gs_mutexGui
= new wxMutex();
1685 gs_mutexGui
->Lock();
1687 gs_mutexDeleteThread
= new wxMutex();
1688 gs_condAllDeleted
= new wxCondition(*gs_mutexDeleteThread
);
1693 void wxThreadModule::OnExit()
1695 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1697 // are there any threads left which are being deleted right now?
1698 size_t nThreadsBeingDeleted
;
1701 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1702 nThreadsBeingDeleted
= gs_nThreadsBeingDeleted
;
1704 if ( nThreadsBeingDeleted
> 0 )
1706 wxLogTrace(TRACE_THREADS
,
1707 _T("Waiting for %lu threads to disappear"),
1708 (unsigned long)nThreadsBeingDeleted
);
1710 // have to wait until all of them disappear
1711 gs_condAllDeleted
->Wait();
1718 wxMutexLocker
lock(*gs_mutexAllThreads
);
1720 // terminate any threads left
1721 count
= gs_allThreads
.GetCount();
1724 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1725 (unsigned long)count
);
1727 } // unlock mutex before deleting the threads as they lock it in their dtor
1729 for ( size_t n
= 0u; n
< count
; n
++ )
1731 // Delete calls the destructor which removes the current entry. We
1732 // should only delete the first one each time.
1733 gs_allThreads
[0]->Delete();
1736 delete gs_mutexAllThreads
;
1738 // destroy GUI mutex
1739 gs_mutexGui
->Unlock();
1742 // and free TLD slot
1743 (void)pthread_key_delete(gs_keySelf
);
1745 delete gs_condAllDeleted
;
1746 delete gs_mutexDeleteThread
;
1749 // ----------------------------------------------------------------------------
1751 // ----------------------------------------------------------------------------
1753 static void ScheduleThreadForDeletion()
1755 wxMutexLocker
lock( *gs_mutexDeleteThread
);
1757 gs_nThreadsBeingDeleted
++;
1759 wxLogTrace(TRACE_THREADS
, _T("%lu thread%s waiting to be deleted"),
1760 (unsigned long)gs_nThreadsBeingDeleted
,
1761 gs_nThreadsBeingDeleted
== 1 ? _T("") : _T("s"));
1764 static void DeleteThread(wxThread
*This
)
1766 // gs_mutexDeleteThread should be unlocked before signalling the condition
1767 // or wxThreadModule::OnExit() would deadlock
1768 wxMutexLocker
locker( *gs_mutexDeleteThread
);
1770 wxLogTrace(TRACE_THREADS
, _T("Thread %ld auto deletes."), This
->GetId());
1774 wxCHECK_RET( gs_nThreadsBeingDeleted
> 0,
1775 _T("no threads scheduled for deletion, yet we delete one?") );
1777 wxLogTrace(TRACE_THREADS
, _T("%lu scheduled for deletion threads left."),
1778 (unsigned long)gs_nThreadsBeingDeleted
- 1);
1780 if ( !--gs_nThreadsBeingDeleted
)
1782 // no more threads left, signal it
1783 gs_condAllDeleted
->Signal();
1787 void wxMutexGuiEnter()
1789 gs_mutexGui
->Lock();
1792 void wxMutexGuiLeave()
1794 gs_mutexGui
->Unlock();
1797 // ----------------------------------------------------------------------------
1798 // include common implementation code
1799 // ----------------------------------------------------------------------------
1801 #include "wx/thrimpl.cpp"
1803 #endif // wxUSE_THREADS