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 p_internal
= new wxMutexInternal
;
104 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) NULL
);
111 wxLogDebug(_T("Freeing a locked mutex (%d locks)"), m_locked
);
113 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
117 wxMutexError
wxMutex::Lock()
119 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
122 wxLogDebug(_T("Locking this mutex would lead to deadlock!"));
124 return wxMUTEX_DEAD_LOCK
;
129 return wxMUTEX_NO_ERROR
;
132 wxMutexError
wxMutex::TryLock()
139 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
142 case EBUSY
: return wxMUTEX_BUSY
;
147 return wxMUTEX_NO_ERROR
;
150 wxMutexError
wxMutex::Unlock()
158 wxLogDebug(_T("Unlocking not locked mutex."));
160 return wxMUTEX_UNLOCKED
;
163 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
165 return wxMUTEX_NO_ERROR
;
168 //--------------------------------------------------------------------
169 // wxCondition (Posix implementation)
170 //--------------------------------------------------------------------
172 class wxConditionInternal
175 pthread_cond_t p_condition
;
178 wxCondition::wxCondition()
180 p_internal
= new wxConditionInternal
;
181 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
184 wxCondition::~wxCondition()
186 pthread_cond_destroy( &(p_internal
->p_condition
) );
191 void wxCondition::Wait(wxMutex
& mutex
)
193 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
196 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
198 struct timespec tspec
;
200 tspec
.tv_sec
= time(0L)+sec
;
201 tspec
.tv_nsec
= nsec
;
202 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
205 void wxCondition::Signal()
207 pthread_cond_signal( &(p_internal
->p_condition
) );
210 void wxCondition::Broadcast()
212 pthread_cond_broadcast( &(p_internal
->p_condition
) );
215 //--------------------------------------------------------------------
216 // wxThread (Posix implementation)
217 //--------------------------------------------------------------------
219 class wxThreadInternal
225 // thread entry function
226 static void *PthreadStart(void *ptr
);
228 #if HAVE_THREAD_CLEANUP_FUNCTIONS
229 // thread exit function
230 static void PthreadCleanup(void *ptr
);
236 // ask the thread to terminate
238 // wake up threads waiting for our termination
240 // go to sleep until Resume() is called
247 int GetPriority() const { return m_prio
; }
248 void SetPriority(int prio
) { m_prio
= prio
; }
250 wxThreadState
GetState() const { return m_state
; }
251 void SetState(wxThreadState state
) { m_state
= state
; }
253 pthread_t
GetId() const { return m_threadId
; }
254 pthread_t
*GetIdPtr() { return &m_threadId
; }
256 void SetCancelFlag() { m_cancelled
= TRUE
; }
257 bool WasCancelled() const { return m_cancelled
; }
260 pthread_t m_threadId
; // id of the thread
261 wxThreadState m_state
; // see wxThreadState enum
262 int m_prio
; // in wxWindows units: from 0 to 100
264 // set when the thread should terminate
267 // this (mutex, cond) pair is used to synchronize the main thread and this
268 // thread in several situations:
269 // 1. The thread function blocks until condition is signaled by Run() when
270 // it's initially created - this allows thread creation in "suspended"
272 // 2. The Delete() function blocks until the condition is signaled when the
274 // GL: On Linux, this may fail because we can have a deadlock in either
275 // SignalExit() or Wait(): so we add m_end_mutex for the finalization.
276 wxMutex m_mutex
, m_end_mutex
;
279 // another (mutex, cond) pair for Pause()/Resume() usage
281 // VZ: it's possible that we might reuse the mutex and condition from above
282 // for this too, but as I'm not at all sure that it won't create subtle
283 // problems with race conditions between, say, Pause() and Delete() I
284 // prefer this may be a bit less efficient but much safer solution
285 wxMutex m_mutexSuspend
;
286 wxCondition m_condSuspend
;
289 void *wxThreadInternal::PthreadStart(void *ptr
)
291 wxThread
*thread
= (wxThread
*)ptr
;
292 wxThreadInternal
*pthread
= thread
->p_internal
;
295 int rc
= pthread_setspecific(gs_keySelf
, thread
);
298 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
302 #if HAVE_THREAD_CLEANUP_FUNCTIONS
303 // Install the cleanup handler.
304 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
307 // wait for the condition to be signaled from Run()
308 // mutex state: currently locked by the thread which created us
309 pthread
->m_cond
.Wait(pthread
->m_mutex
);
310 // mutex state: locked again on exit of Wait()
312 // call the main entry
313 status
= thread
->Entry();
315 #if HAVE_THREAD_CLEANUP_FUNCTIONS
316 pthread_cleanup_pop(FALSE
);
319 // terminate the thread
320 thread
->Exit(status
);
322 wxFAIL_MSG(_T("wxThread::Exit() can't return."));
327 #if HAVE_THREAD_CLEANUP_FUNCTIONS
328 // Only called when the thread is explicitely killed.
330 void wxThreadInternal::PthreadCleanup(void *ptr
)
332 wxThread
*thread
= (wxThread
*) ptr
;
334 // The thread is already considered as finished.
335 if (thread
->p_internal
->GetState() == STATE_EXITED
)
338 // first call user-level clean up code
341 // next wake up the threads waiting for us (OTOH, this function won't retur
342 // until someone waited for us!)
343 thread
->p_internal
->SetState(STATE_EXITED
);
345 thread
->p_internal
->SignalExit();
349 wxThreadInternal::wxThreadInternal()
354 // this mutex is locked during almost all thread lifetime - it will only be
355 // unlocked in the very end
358 // this mutex is used by wxThreadInternal::Wait() and by
359 // wxThreadInternal::SignalExit(). We don't use m_mutex because of a
360 // possible deadlock in either Wait() or SignalExit().
363 // this mutex is used in Pause()/Resume() and is also locked all the time
364 // unless the thread is paused
365 m_mutexSuspend
.Lock();
368 wxThreadInternal::~wxThreadInternal()
370 // GL: moved to SignalExit
371 // m_mutexSuspend.Unlock();
373 // note that m_mutex will be unlocked by the thread which waits for our
376 // In the case, we didn't start the thread, all these mutex are locked:
377 // we must unlock them.
378 if (m_mutex
.IsLocked())
381 if (m_end_mutex
.IsLocked())
382 m_end_mutex
.Unlock();
384 if (m_mutexSuspend
.IsLocked())
385 m_mutexSuspend
.Unlock();
388 wxThreadError
wxThreadInternal::Run()
390 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
391 _T("thread may only be started once after successful Create()") );
393 // the mutex was locked on Create(), so we will be able to lock it again
394 // only when the thread really starts executing and enters the wait -
395 // otherwise we might signal the condition before anybody is waiting for it
396 wxMutexLocker
lock(m_mutex
);
399 m_state
= STATE_RUNNING
;
401 return wxTHREAD_NO_ERROR
;
403 // now the mutex is unlocked back - but just to allow Wait() function to
404 // terminate by relocking it, so the net result is that the worker thread
405 // starts executing and the mutex is still locked
408 void wxThreadInternal::Wait()
410 wxCHECK_RET( WasCancelled(), _T("thread should have been cancelled first") );
412 // if the thread we're waiting for is waiting for the GUI mutex, we will
413 // deadlock so make sure we release it temporarily
414 if ( wxThread::IsMain() )
417 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
418 // it and to signal us its termination
419 m_cond
.Wait(m_end_mutex
);
421 // mutex is still in the locked state - relocked on exit from Wait(), so
422 // unlock it - we don't need it any more, the thread has already terminated
423 m_end_mutex
.Unlock();
425 // After that, we wait for the real end of the other thread.
426 pthread_join(GetId(), NULL
);
428 // reacquire GUI mutex
429 if ( wxThread::IsMain() )
433 void wxThreadInternal::SignalExit()
435 // GL: Unlock mutexSuspend here.
436 m_mutexSuspend
.Unlock();
438 // as mutex is currently locked, this will block until some other thread
439 // (normally the same which created this one) unlocks it by entering Wait()
442 // wake up all the threads waiting for our termination
445 // after this call mutex will be finally unlocked
446 m_end_mutex
.Unlock();
449 void wxThreadInternal::Pause()
451 // the state is set from the thread which pauses us first, this function
452 // is called later so the state should have been already set
453 wxCHECK_RET( m_state
== STATE_PAUSED
,
454 _T("thread must first be paused with wxThread::Pause().") );
456 // don't pause the thread which is being terminated - this would lead to
457 // deadlock if the thread is paused after Delete() had called Resume() but
458 // before it had time to call Wait()
459 if ( WasCancelled() )
462 // wait until the condition is signaled from Resume()
463 m_condSuspend
.Wait(m_mutexSuspend
);
466 void wxThreadInternal::Resume()
468 wxCHECK_RET( m_state
== STATE_PAUSED
,
469 _T("can't resume thread which is not suspended.") );
471 // we will be able to lock this mutex only when Pause() starts waiting
472 wxMutexLocker
lock(m_mutexSuspend
);
473 m_condSuspend
.Signal();
475 SetState(STATE_RUNNING
);
478 // -----------------------------------------------------------------------------
480 // -----------------------------------------------------------------------------
482 wxThread
*wxThread::This()
484 return (wxThread
*)pthread_getspecific(gs_keySelf
);
487 bool wxThread::IsMain()
489 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
492 void wxThread::Yield()
497 void wxThread::Sleep(unsigned long milliseconds
)
499 wxUsleep(milliseconds
);
502 // -----------------------------------------------------------------------------
504 // -----------------------------------------------------------------------------
508 // add this thread to the global list of all threads
509 gs_allThreads
.Add(this);
511 p_internal
= new wxThreadInternal();
514 wxThreadError
wxThread::Create()
516 if (p_internal
->GetState() != STATE_NEW
)
517 return wxTHREAD_RUNNING
;
519 // set up the thread attribute: right now, we only set thread priority
521 pthread_attr_init(&attr
);
523 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
525 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
527 wxLogError(_("Cannot retrieve thread scheduling policy."));
530 int min_prio
= sched_get_priority_min(prio
),
531 max_prio
= sched_get_priority_max(prio
);
533 if ( min_prio
== -1 || max_prio
== -1 )
535 wxLogError(_("Cannot get priority range for scheduling policy %d."),
540 struct sched_param sp
;
541 pthread_attr_getschedparam(&attr
, &sp
);
542 sp
.sched_priority
= min_prio
+
543 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
544 pthread_attr_setschedparam(&attr
, &sp
);
546 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
548 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
549 // this will make the threads created by this process really concurrent
550 pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
);
551 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
553 // create the new OS thread object
554 int rc
= pthread_create(p_internal
->GetIdPtr(), &attr
,
555 wxThreadInternal::PthreadStart
, (void *)this);
556 pthread_attr_destroy(&attr
);
560 p_internal
->SetState(STATE_EXITED
);
561 return wxTHREAD_NO_RESOURCE
;
564 return wxTHREAD_NO_ERROR
;
567 wxThreadError
wxThread::Run()
569 return p_internal
->Run();
572 // -----------------------------------------------------------------------------
574 // -----------------------------------------------------------------------------
576 void wxThread::SetPriority(unsigned int prio
)
578 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
579 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
580 _T("invalid thread priority") );
582 wxCriticalSectionLocker
lock(m_critsect
);
584 switch ( p_internal
->GetState() )
587 // thread not yet started, priority will be set when it is
588 p_internal
->SetPriority(prio
);
593 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
595 struct sched_param sparam
;
596 sparam
.sched_priority
= prio
;
598 if ( pthread_setschedparam(p_internal
->GetId(),
599 SCHED_OTHER
, &sparam
) != 0 )
601 wxLogError(_("Failed to set thread priority %d."), prio
);
604 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
609 wxFAIL_MSG(_T("impossible to set thread priority in this state"));
613 unsigned int wxThread::GetPriority() const
615 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
617 return p_internal
->GetPriority();
620 unsigned long wxThread::GetID() const
622 return (unsigned long)p_internal
->GetId();
625 // -----------------------------------------------------------------------------
627 // -----------------------------------------------------------------------------
629 wxThreadError
wxThread::Pause()
631 wxCriticalSectionLocker
lock(m_critsect
);
633 if ( p_internal
->GetState() != STATE_RUNNING
)
635 wxLogDebug(_T("Can't pause thread which is not running."));
637 return wxTHREAD_NOT_RUNNING
;
640 p_internal
->SetState(STATE_PAUSED
);
642 return wxTHREAD_NO_ERROR
;
645 wxThreadError
wxThread::Resume()
647 wxCriticalSectionLocker
lock(m_critsect
);
649 if ( p_internal
->GetState() == STATE_PAUSED
)
652 p_internal
->Resume();
655 return wxTHREAD_NO_ERROR
;
659 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
661 return wxTHREAD_MISC_ERROR
;
665 // -----------------------------------------------------------------------------
667 // -----------------------------------------------------------------------------
669 wxThread::ExitCode
wxThread::Delete()
675 wxThreadState state
= p_internal
->GetState();
677 // ask the thread to stop
678 p_internal
->SetCancelFlag();
690 // resume the thread first
696 // wait until the thread stops
703 wxThreadError
wxThread::Kill()
705 switch ( p_internal
->GetState() )
709 return wxTHREAD_NOT_RUNNING
;
712 #ifdef HAVE_PTHREAD_CANCEL
713 if ( pthread_cancel(p_internal
->GetId()) != 0 )
716 wxLogError(_("Failed to terminate a thread."));
718 return wxTHREAD_MISC_ERROR
;
721 return wxTHREAD_NO_ERROR
;
725 void wxThread::Exit(void *status
)
727 // first call user-level clean up code
730 // next wake up the threads waiting for us (OTOH, this function won't return
731 // until someone waited for us!)
732 p_internal
->SignalExit();
734 p_internal
->SetState(STATE_EXITED
);
736 // delete both C++ thread object and terminate the OS thread object
737 // GL: This is very ugly and buggy ...
739 pthread_exit(status
);
742 // also test whether we were paused
743 bool wxThread::TestDestroy()
745 wxCriticalSectionLocker
lock(m_critsect
);
747 if ( p_internal
->GetState() == STATE_PAUSED
)
749 // leave the crit section or the other threads will stop too if they try
750 // to call any of (seemingly harmless) IsXXX() functions while we sleep
755 // enter it back before it's finally left in lock object dtor
759 return p_internal
->WasCancelled();
762 wxThread::~wxThread()
765 if (p_internal
->GetState() != STATE_EXITED
&&
766 p_internal
->GetState() != STATE_NEW
)
767 wxLogDebug(_T("The thread is being destroyed althought it is still running ! The application may crash."));
772 // remove this thread from the global array
773 gs_allThreads
.Remove(this);
776 // -----------------------------------------------------------------------------
778 // -----------------------------------------------------------------------------
780 bool wxThread::IsRunning() const
782 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
784 return p_internal
->GetState() == STATE_RUNNING
;
787 bool wxThread::IsAlive() const
789 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
791 switch ( p_internal
->GetState() )
802 bool wxThread::IsPaused() const
804 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
806 return (p_internal
->GetState() == STATE_PAUSED
);
809 //--------------------------------------------------------------------
811 //--------------------------------------------------------------------
813 class wxThreadModule
: public wxModule
816 virtual bool OnInit();
817 virtual void OnExit();
820 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
823 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
825 bool wxThreadModule::OnInit()
827 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
830 wxLogSysError(rc
, _("Thread module initialization failed: "
831 "failed to create thread key"));
836 gs_mutexGui
= new wxMutex();
838 gs_tidMain
= pthread_self();
845 void wxThreadModule::OnExit()
847 wxASSERT_MSG( wxThread::IsMain(), _T("only main thread can be here") );
849 // terminate any threads left
850 size_t count
= gs_allThreads
.GetCount();
852 wxLogDebug(_T("Some threads were not terminated by the application."));
854 for ( size_t n
= 0u; n
< count
; n
++ )
856 gs_allThreads
[n
]->Delete();
860 gs_mutexGui
->Unlock();
865 (void)pthread_key_delete(gs_keySelf
);
868 // ----------------------------------------------------------------------------
870 // ----------------------------------------------------------------------------
872 void wxMutexGuiEnter()
877 void wxMutexGuiLeave()
879 gs_mutexGui
->Unlock();