1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread (Posix) Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
8 // Copyright: (c) Wolfram Gloger (1996, 1997)
9 // Guilhem Lavaux (1998)
10 // Vadim Zeitlin (1999)
11 // Robert Roebling (1999)
12 // Licence: wxWindows licence
13 /////////////////////////////////////////////////////////////////////////////
15 // ============================================================================
17 // ============================================================================
19 // ----------------------------------------------------------------------------
21 // ----------------------------------------------------------------------------
24 #pragma implementation "thread.h"
27 // With simple makefiles, we must ignore the file body if not using
33 #include "wx/thread.h"
34 #include "wx/module.h"
38 #include "wx/dynarray.h"
50 // ----------------------------------------------------------------------------
52 // ----------------------------------------------------------------------------
54 // the possible states of the thread and transitions from them
57 STATE_NEW
, // didn't start execution yet (=> RUNNING)
58 STATE_RUNNING
, // running (=> PAUSED or EXITED)
59 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
60 STATE_EXITED
// thread doesn't exist any more
63 // ----------------------------------------------------------------------------
65 // ----------------------------------------------------------------------------
67 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
69 // -----------------------------------------------------------------------------
71 // -----------------------------------------------------------------------------
73 // we keep the list of all threads created by the application to be able to
74 // terminate them on exit if there are some left - otherwise the process would
76 static wxArrayThread gs_allThreads
;
78 // the id of the main thread
79 static pthread_t gs_tidMain
;
81 // the key for the pointer to the associated wxThread object
82 static pthread_key_t gs_keySelf
;
84 // this mutex must be acquired before any call to a GUI function
85 static wxMutex
*gs_mutexGui
;
87 // ============================================================================
89 // ============================================================================
91 //--------------------------------------------------------------------
92 // wxMutex (Posix implementation)
93 //--------------------------------------------------------------------
98 pthread_mutex_t p_mutex
;
103 pthread_mutexattr_t attr_type
;
105 pthread_mutexattr_settype( &attr_type
, PTHREAD_MUTEX_FAST_NP
);
107 p_internal
= new wxMutexInternal
;
108 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) &attr_type
);
115 wxLogDebug(_T("Freeing a locked mutex (%d locks)"), m_locked
);
117 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
121 wxMutexError
wxMutex::Lock()
123 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
126 wxLogDebug(_T("Locking this mutex would lead to deadlock!"));
128 return wxMUTEX_DEAD_LOCK
;
133 return wxMUTEX_NO_ERROR
;
136 wxMutexError
wxMutex::TryLock()
143 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
146 case EBUSY
: return wxMUTEX_BUSY
;
151 return wxMUTEX_NO_ERROR
;
154 wxMutexError
wxMutex::Unlock()
162 wxLogDebug(_T("Unlocking not locked mutex."));
164 return wxMUTEX_UNLOCKED
;
167 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
169 return wxMUTEX_NO_ERROR
;
172 //--------------------------------------------------------------------
173 // wxCondition (Posix implementation)
174 //--------------------------------------------------------------------
176 class wxConditionInternal
179 pthread_cond_t p_condition
;
182 wxCondition::wxCondition()
184 p_internal
= new wxConditionInternal
;
185 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
188 wxCondition::~wxCondition()
190 pthread_cond_destroy( &(p_internal
->p_condition
) );
195 void wxCondition::Wait(wxMutex
& mutex
)
197 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
200 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
202 struct timespec tspec
;
204 tspec
.tv_sec
= time(0L)+sec
;
205 tspec
.tv_nsec
= nsec
;
206 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
209 void wxCondition::Signal()
211 pthread_cond_signal( &(p_internal
->p_condition
) );
214 void wxCondition::Broadcast()
216 pthread_cond_broadcast( &(p_internal
->p_condition
) );
219 //--------------------------------------------------------------------
220 // wxThread (Posix implementation)
221 //--------------------------------------------------------------------
223 class wxThreadInternal
229 // thread entry function
230 static void *PthreadStart(void *ptr
);
232 #if HAVE_THREAD_CLEANUP_FUNCTIONS
233 // thread exit function
234 static void PthreadCleanup(void *ptr
);
240 // ask the thread to terminate
242 // wake up threads waiting for our termination
244 // go to sleep until Resume() is called
251 int GetPriority() const { return m_prio
; }
252 void SetPriority(int prio
) { m_prio
= prio
; }
254 wxThreadState
GetState() const { return m_state
; }
255 void SetState(wxThreadState state
) { m_state
= state
; }
257 pthread_t
GetId() const { return m_threadId
; }
258 pthread_t
*GetIdPtr() { return &m_threadId
; }
260 void SetCancelFlag() { m_cancelled
= TRUE
; }
261 bool WasCancelled() const { return m_cancelled
; }
264 pthread_t m_threadId
; // id of the thread
265 wxThreadState m_state
; // see wxThreadState enum
266 int m_prio
; // in wxWindows units: from 0 to 100
268 // set when the thread should terminate
271 // this (mutex, cond) pair is used to synchronize the main thread and this
272 // thread in several situations:
273 // 1. The thread function blocks until condition is signaled by Run() when
274 // it's initially created - this allows thread creation in "suspended"
276 // 2. The Delete() function blocks until the condition is signaled when the
278 // GL: On Linux, this may fail because we can have a deadlock in either
279 // SignalExit() or Wait(): so we add m_end_mutex for the finalization.
280 wxMutex m_mutex
, m_end_mutex
;
283 // another (mutex, cond) pair for Pause()/Resume() usage
285 // VZ: it's possible that we might reuse the mutex and condition from above
286 // for this too, but as I'm not at all sure that it won't create subtle
287 // problems with race conditions between, say, Pause() and Delete() I
288 // prefer this may be a bit less efficient but much safer solution
289 wxMutex m_mutexSuspend
;
290 wxCondition m_condSuspend
;
293 void *wxThreadInternal::PthreadStart(void *ptr
)
295 wxThread
*thread
= (wxThread
*)ptr
;
296 wxThreadInternal
*pthread
= thread
->p_internal
;
299 int rc
= pthread_setspecific(gs_keySelf
, thread
);
302 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
306 #if HAVE_THREAD_CLEANUP_FUNCTIONS
307 // Install the cleanup handler.
308 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
311 // wait for the condition to be signaled from Run()
312 // mutex state: currently locked by the thread which created us
313 pthread
->m_cond
.Wait(pthread
->m_mutex
);
314 // mutex state: locked again on exit of Wait()
316 // call the main entry
317 status
= thread
->Entry();
319 #if HAVE_THREAD_CLEANUP_FUNCTIONS
320 pthread_cleanup_pop(FALSE
);
323 // terminate the thread
324 thread
->Exit(status
);
326 wxFAIL_MSG(_T("wxThread::Exit() can't return."));
331 #if HAVE_THREAD_CLEANUP_FUNCTIONS
332 // Only called when the thread is explicitely killed.
334 void wxThreadInternal::PthreadCleanup(void *ptr
)
336 wxThread
*thread
= (wxThread
*) ptr
;
338 // The thread is already considered as finished.
339 if (thread
->p_internal
->GetState() == STATE_EXITED
)
342 // first call user-level clean up code
345 // next wake up the threads waiting for us (OTOH, this function won't retur
346 // until someone waited for us!)
347 thread
->p_internal
->SetState(STATE_EXITED
);
349 thread
->p_internal
->SignalExit();
353 wxThreadInternal::wxThreadInternal()
358 // this mutex is locked during almost all thread lifetime - it will only be
359 // unlocked in the very end
362 // this mutex is used by wxThreadInternal::Wait() and by
363 // wxThreadInternal::SignalExit(). We don't use m_mutex because of a
364 // possible deadlock in either Wait() or SignalExit().
367 // this mutex is used in Pause()/Resume() and is also locked all the time
368 // unless the thread is paused
369 m_mutexSuspend
.Lock();
372 wxThreadInternal::~wxThreadInternal()
374 // GL: moved to SignalExit
375 // m_mutexSuspend.Unlock();
377 // note that m_mutex will be unlocked by the thread which waits for our
380 // In the case, we didn't start the thread, all these mutex are locked:
381 // we must unlock them.
382 if (m_mutex
.IsLocked())
385 if (m_end_mutex
.IsLocked())
386 m_end_mutex
.Unlock();
388 if (m_mutexSuspend
.IsLocked())
389 m_mutexSuspend
.Unlock();
392 wxThreadError
wxThreadInternal::Run()
394 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
395 _T("thread may only be started once after successful Create()") );
397 // the mutex was locked on Create(), so we will be able to lock it again
398 // only when the thread really starts executing and enters the wait -
399 // otherwise we might signal the condition before anybody is waiting for it
400 wxMutexLocker
lock(m_mutex
);
403 m_state
= STATE_RUNNING
;
405 return wxTHREAD_NO_ERROR
;
407 // now the mutex is unlocked back - but just to allow Wait() function to
408 // terminate by relocking it, so the net result is that the worker thread
409 // starts executing and the mutex is still locked
412 void wxThreadInternal::Wait()
414 wxCHECK_RET( WasCancelled(), _T("thread should have been cancelled first") );
416 // if the thread we're waiting for is waiting for the GUI mutex, we will
417 // deadlock so make sure we release it temporarily
418 if ( wxThread::IsMain() )
421 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
422 // it and to signal us its termination
423 m_cond
.Wait(m_end_mutex
);
425 // mutex is still in the locked state - relocked on exit from Wait(), so
426 // unlock it - we don't need it any more, the thread has already terminated
427 m_end_mutex
.Unlock();
429 // After that, we wait for the real end of the other thread.
430 pthread_join(GetId(), NULL
);
432 // reacquire GUI mutex
433 if ( wxThread::IsMain() )
437 void wxThreadInternal::SignalExit()
439 // GL: Unlock mutexSuspend here.
440 m_mutexSuspend
.Unlock();
442 // as mutex is currently locked, this will block until some other thread
443 // (normally the same which created this one) unlocks it by entering Wait()
446 // wake up all the threads waiting for our termination
449 // after this call mutex will be finally unlocked
450 m_end_mutex
.Unlock();
453 void wxThreadInternal::Pause()
455 // the state is set from the thread which pauses us first, this function
456 // is called later so the state should have been already set
457 wxCHECK_RET( m_state
== STATE_PAUSED
,
458 _T("thread must first be paused with wxThread::Pause().") );
460 // don't pause the thread which is being terminated - this would lead to
461 // deadlock if the thread is paused after Delete() had called Resume() but
462 // before it had time to call Wait()
463 if ( WasCancelled() )
466 // wait until the condition is signaled from Resume()
467 m_condSuspend
.Wait(m_mutexSuspend
);
470 void wxThreadInternal::Resume()
472 wxCHECK_RET( m_state
== STATE_PAUSED
,
473 _T("can't resume thread which is not suspended.") );
475 // we will be able to lock this mutex only when Pause() starts waiting
476 wxMutexLocker
lock(m_mutexSuspend
);
477 m_condSuspend
.Signal();
479 SetState(STATE_RUNNING
);
482 // -----------------------------------------------------------------------------
484 // -----------------------------------------------------------------------------
486 wxThread
*wxThread::This()
488 return (wxThread
*)pthread_getspecific(gs_keySelf
);
491 bool wxThread::IsMain()
493 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
496 void wxThread::Yield()
501 void wxThread::Sleep(unsigned long milliseconds
)
503 wxUsleep(milliseconds
);
506 // -----------------------------------------------------------------------------
508 // -----------------------------------------------------------------------------
512 // add this thread to the global list of all threads
513 gs_allThreads
.Add(this);
515 p_internal
= new wxThreadInternal();
518 wxThreadError
wxThread::Create()
520 if (p_internal
->GetState() != STATE_NEW
)
521 return wxTHREAD_RUNNING
;
523 // set up the thread attribute: right now, we only set thread priority
525 pthread_attr_init(&attr
);
527 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
529 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
531 wxLogError(_("Cannot retrieve thread scheduling policy."));
534 int min_prio
= sched_get_priority_min(prio
),
535 max_prio
= sched_get_priority_max(prio
);
537 if ( min_prio
== -1 || max_prio
== -1 )
539 wxLogError(_("Cannot get priority range for scheduling policy %d."),
544 struct sched_param sp
;
545 pthread_attr_getschedparam(&attr
, &sp
);
546 sp
.sched_priority
= min_prio
+
547 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
548 pthread_attr_setschedparam(&attr
, &sp
);
550 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
552 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
553 // this will make the threads created by this process really concurrent
554 pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
);
555 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
557 // create the new OS thread object
558 int rc
= pthread_create(p_internal
->GetIdPtr(), &attr
,
559 wxThreadInternal::PthreadStart
, (void *)this);
560 pthread_attr_destroy(&attr
);
564 p_internal
->SetState(STATE_EXITED
);
565 return wxTHREAD_NO_RESOURCE
;
568 return wxTHREAD_NO_ERROR
;
571 wxThreadError
wxThread::Run()
573 return p_internal
->Run();
576 // -----------------------------------------------------------------------------
578 // -----------------------------------------------------------------------------
580 void wxThread::SetPriority(unsigned int prio
)
582 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
583 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
584 _T("invalid thread priority") );
586 wxCriticalSectionLocker
lock(m_critsect
);
588 switch ( p_internal
->GetState() )
591 // thread not yet started, priority will be set when it is
592 p_internal
->SetPriority(prio
);
597 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
599 struct sched_param sparam
;
600 sparam
.sched_priority
= prio
;
602 if ( pthread_setschedparam(p_internal
->GetId(),
603 SCHED_OTHER
, &sparam
) != 0 )
605 wxLogError(_("Failed to set thread priority %d."), prio
);
608 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
613 wxFAIL_MSG(_T("impossible to set thread priority in this state"));
617 unsigned int wxThread::GetPriority() const
619 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
621 return p_internal
->GetPriority();
624 unsigned long wxThread::GetID() const
626 return (unsigned long)p_internal
->GetId();
629 // -----------------------------------------------------------------------------
631 // -----------------------------------------------------------------------------
633 wxThreadError
wxThread::Pause()
635 wxCriticalSectionLocker
lock(m_critsect
);
637 if ( p_internal
->GetState() != STATE_RUNNING
)
639 wxLogDebug(_T("Can't pause thread which is not running."));
641 return wxTHREAD_NOT_RUNNING
;
644 p_internal
->SetState(STATE_PAUSED
);
646 return wxTHREAD_NO_ERROR
;
649 wxThreadError
wxThread::Resume()
651 wxCriticalSectionLocker
lock(m_critsect
);
653 if ( p_internal
->GetState() == STATE_PAUSED
)
656 p_internal
->Resume();
659 return wxTHREAD_NO_ERROR
;
663 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
665 return wxTHREAD_MISC_ERROR
;
669 // -----------------------------------------------------------------------------
671 // -----------------------------------------------------------------------------
673 wxThread::ExitCode
wxThread::Delete()
679 wxThreadState state
= p_internal
->GetState();
681 // ask the thread to stop
682 p_internal
->SetCancelFlag();
694 // resume the thread first
700 // wait until the thread stops
703 //GL: As we must auto-destroy, the destruction must happen here.
709 wxThreadError
wxThread::Kill()
711 switch ( p_internal
->GetState() )
715 return wxTHREAD_NOT_RUNNING
;
718 #ifdef HAVE_PTHREAD_CANCEL
719 if ( pthread_cancel(p_internal
->GetId()) != 0 )
722 wxLogError(_("Failed to terminate a thread."));
724 return wxTHREAD_MISC_ERROR
;
726 //GL: As we must auto-destroy, the destruction must happen here (2).
729 return wxTHREAD_NO_ERROR
;
733 void wxThread::Exit(void *status
)
735 // first call user-level clean up code
738 // next wake up the threads waiting for us (OTOH, this function won't return
739 // until someone waited for us!)
740 p_internal
->SignalExit();
742 p_internal
->SetState(STATE_EXITED
);
744 // delete both C++ thread object and terminate the OS thread object
745 // GL: This is very ugly and buggy ...
747 pthread_exit(status
);
750 // also test whether we were paused
751 bool wxThread::TestDestroy()
753 wxCriticalSectionLocker
lock(m_critsect
);
755 if ( p_internal
->GetState() == STATE_PAUSED
)
757 // leave the crit section or the other threads will stop too if they try
758 // to call any of (seemingly harmless) IsXXX() functions while we sleep
763 // enter it back before it's finally left in lock object dtor
767 return p_internal
->WasCancelled();
770 wxThread::~wxThread()
773 if (p_internal
->GetState() != STATE_EXITED
&&
774 p_internal
->GetState() != STATE_NEW
)
775 wxLogDebug(_T("The thread is being destroyed althought it is still running ! The application may crash."));
780 // remove this thread from the global array
781 gs_allThreads
.Remove(this);
784 // -----------------------------------------------------------------------------
786 // -----------------------------------------------------------------------------
788 bool wxThread::IsRunning() const
790 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
792 return p_internal
->GetState() == STATE_RUNNING
;
795 bool wxThread::IsAlive() const
797 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
799 switch ( p_internal
->GetState() )
810 bool wxThread::IsPaused() const
812 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
814 return (p_internal
->GetState() == STATE_PAUSED
);
817 //--------------------------------------------------------------------
819 //--------------------------------------------------------------------
821 class wxThreadModule
: public wxModule
824 virtual bool OnInit();
825 virtual void OnExit();
828 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
831 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
833 bool wxThreadModule::OnInit()
835 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
838 wxLogSysError(rc
, _("Thread module initialization failed: "
839 "failed to create thread key"));
844 gs_mutexGui
= new wxMutex();
846 gs_tidMain
= pthread_self();
853 void wxThreadModule::OnExit()
855 wxASSERT_MSG( wxThread::IsMain(), _T("only main thread can be here") );
857 // terminate any threads left
858 size_t count
= gs_allThreads
.GetCount();
860 wxLogDebug(_T("Some threads were not terminated by the application."));
862 for ( size_t n
= 0u; n
< count
; n
++ )
864 gs_allThreads
[n
]->Delete();
868 gs_mutexGui
->Unlock();
873 (void)pthread_key_delete(gs_keySelf
);
876 // ----------------------------------------------------------------------------
878 // ----------------------------------------------------------------------------
880 void wxMutexGuiEnter()
885 void wxMutexGuiLeave()
887 gs_mutexGui
->Unlock();