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
;
105 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) NULL
);
112 wxLogDebug(T("Freeing a locked mutex (%d locks)"), m_locked
);
114 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
118 wxMutexError
wxMutex::Lock()
120 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
123 wxLogDebug(T("Locking this mutex would lead to deadlock!"));
125 return wxMUTEX_DEAD_LOCK
;
130 return wxMUTEX_NO_ERROR
;
133 wxMutexError
wxMutex::TryLock()
140 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
143 case EBUSY
: return wxMUTEX_BUSY
;
148 return wxMUTEX_NO_ERROR
;
151 wxMutexError
wxMutex::Unlock()
159 wxLogDebug(T("Unlocking not locked mutex."));
161 return wxMUTEX_UNLOCKED
;
164 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
166 return wxMUTEX_NO_ERROR
;
169 //--------------------------------------------------------------------
170 // wxCondition (Posix implementation)
171 //--------------------------------------------------------------------
173 class wxConditionInternal
176 pthread_cond_t p_condition
;
179 wxCondition::wxCondition()
181 p_internal
= new wxConditionInternal
;
182 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
185 wxCondition::~wxCondition()
187 pthread_cond_destroy( &(p_internal
->p_condition
) );
192 void wxCondition::Wait(wxMutex
& mutex
)
194 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
197 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
199 struct timespec tspec
;
201 tspec
.tv_sec
= time(0L)+sec
;
202 tspec
.tv_nsec
= nsec
;
203 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
206 void wxCondition::Signal()
208 pthread_cond_signal( &(p_internal
->p_condition
) );
211 void wxCondition::Broadcast()
213 pthread_cond_broadcast( &(p_internal
->p_condition
) );
216 //--------------------------------------------------------------------
217 // wxThread (Posix implementation)
218 //--------------------------------------------------------------------
220 class wxThreadInternal
226 // thread entry function
227 static void *PthreadStart(void *ptr
);
229 #if HAVE_THREAD_CLEANUP_FUNCTIONS
230 // thread exit function
231 static void PthreadCleanup(void *ptr
);
237 // ask the thread to terminate
239 // wake up threads waiting for our termination
241 // go to sleep until Resume() is called
248 int GetPriority() const { return m_prio
; }
249 void SetPriority(int prio
) { m_prio
= prio
; }
251 wxThreadState
GetState() const { return m_state
; }
252 void SetState(wxThreadState state
) { m_state
= state
; }
254 pthread_t
GetId() const { return m_threadId
; }
255 pthread_t
*GetIdPtr() { return &m_threadId
; }
257 void SetCancelFlag() { m_cancelled
= TRUE
; }
258 bool WasCancelled() const { return m_cancelled
; }
261 pthread_t m_threadId
; // id of the thread
262 wxThreadState m_state
; // see wxThreadState enum
263 int m_prio
; // in wxWindows units: from 0 to 100
265 // set when the thread should terminate
268 // this (mutex, cond) pair is used to synchronize the main thread and this
269 // thread in several situations:
270 // 1. The thread function blocks until condition is signaled by Run() when
271 // it's initially created - this allows thread creation in "suspended"
273 // 2. The Delete() function blocks until the condition is signaled when the
275 // GL: On Linux, this may fail because we can have a deadlock in either
276 // SignalExit() or Wait(): so we add m_end_mutex for the finalization.
277 wxMutex m_mutex
, m_end_mutex
;
280 // another (mutex, cond) pair for Pause()/Resume() usage
282 // VZ: it's possible that we might reuse the mutex and condition from above
283 // for this too, but as I'm not at all sure that it won't create subtle
284 // problems with race conditions between, say, Pause() and Delete() I
285 // prefer this may be a bit less efficient but much safer solution
286 wxMutex m_mutexSuspend
;
287 wxCondition m_condSuspend
;
290 void *wxThreadInternal::PthreadStart(void *ptr
)
292 wxThread
*thread
= (wxThread
*)ptr
;
293 wxThreadInternal
*pthread
= thread
->p_internal
;
296 int rc
= pthread_setspecific(gs_keySelf
, thread
);
299 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
303 #if HAVE_THREAD_CLEANUP_FUNCTIONS
304 // Install the cleanup handler.
305 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
308 // wait for the condition to be signaled from Run()
309 // mutex state: currently locked by the thread which created us
310 pthread
->m_cond
.Wait(pthread
->m_mutex
);
311 // mutex state: locked again on exit of Wait()
313 // call the main entry
314 status
= thread
->Entry();
316 #if HAVE_THREAD_CLEANUP_FUNCTIONS
317 pthread_cleanup_pop(FALSE
);
320 // terminate the thread
321 thread
->Exit(status
);
323 wxFAIL_MSG(T("wxThread::Exit() can't return."));
328 #if HAVE_THREAD_CLEANUP_FUNCTIONS
329 // Only called when the thread is explicitely killed.
331 void wxThreadInternal::PthreadCleanup(void *ptr
)
333 wxThread
*thread
= (wxThread
*) ptr
;
335 // The thread is already considered as finished.
336 if (thread
->p_internal
->GetState() == STATE_EXITED
)
339 // first call user-level clean up code
342 // next wake up the threads waiting for us (OTOH, this function won't retur
343 // until someone waited for us!)
344 thread
->p_internal
->SetState(STATE_EXITED
);
346 thread
->p_internal
->SignalExit();
350 wxThreadInternal::wxThreadInternal()
354 m_prio
= WXTHREAD_DEFAULT_PRIORITY
;
357 // this mutex is locked during almost all thread lifetime - it will only be
358 // unlocked in the very end
361 // this mutex is used by wxThreadInternal::Wait() and by
362 // wxThreadInternal::SignalExit(). We don't use m_mutex because of a
363 // possible deadlock in either Wait() or SignalExit().
366 // this mutex is used in Pause()/Resume() and is also locked all the time
367 // unless the thread is paused
368 m_mutexSuspend
.Lock();
371 wxThreadInternal::~wxThreadInternal()
373 // GL: moved to SignalExit
374 // m_mutexSuspend.Unlock();
376 // note that m_mutex will be unlocked by the thread which waits for our
379 // In the case, we didn't start the thread, all these mutex are locked:
380 // we must unlock them.
381 if (m_mutex
.IsLocked())
384 if (m_end_mutex
.IsLocked())
385 m_end_mutex
.Unlock();
387 if (m_mutexSuspend
.IsLocked())
388 m_mutexSuspend
.Unlock();
391 wxThreadError
wxThreadInternal::Run()
393 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
394 T("thread may only be started once after successful Create()") );
396 // the mutex was locked on Create(), so we will be able to lock it again
397 // only when the thread really starts executing and enters the wait -
398 // otherwise we might signal the condition before anybody is waiting for it
399 wxMutexLocker
lock(m_mutex
);
402 m_state
= STATE_RUNNING
;
404 return wxTHREAD_NO_ERROR
;
406 // now the mutex is unlocked back - but just to allow Wait() function to
407 // terminate by relocking it, so the net result is that the worker thread
408 // starts executing and the mutex is still locked
411 void wxThreadInternal::Wait()
413 wxCHECK_RET( WasCancelled(), T("thread should have been cancelled first") );
415 // if the thread we're waiting for is waiting for the GUI mutex, we will
416 // deadlock so make sure we release it temporarily
417 if ( wxThread::IsMain() )
420 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
421 // it and to signal us its termination
422 m_cond
.Wait(m_end_mutex
);
424 // mutex is still in the locked state - relocked on exit from Wait(), so
425 // unlock it - we don't need it any more, the thread has already terminated
426 m_end_mutex
.Unlock();
428 // After that, we wait for the real end of the other thread.
429 pthread_join(GetId(), NULL
);
431 // reacquire GUI mutex
432 if ( wxThread::IsMain() )
436 void wxThreadInternal::SignalExit()
438 // GL: Unlock mutexSuspend here.
439 m_mutexSuspend
.Unlock();
441 // as mutex is currently locked, this will block until some other thread
442 // (normally the same which created this one) unlocks it by entering Wait()
445 // wake up all the threads waiting for our termination
448 // after this call mutex will be finally unlocked
449 m_end_mutex
.Unlock();
452 void wxThreadInternal::Pause()
454 // the state is set from the thread which pauses us first, this function
455 // is called later so the state should have been already set
456 wxCHECK_RET( m_state
== STATE_PAUSED
,
457 T("thread must first be paused with wxThread::Pause().") );
459 // don't pause the thread which is being terminated - this would lead to
460 // deadlock if the thread is paused after Delete() had called Resume() but
461 // before it had time to call Wait()
462 if ( WasCancelled() )
465 // wait until the condition is signaled from Resume()
466 m_condSuspend
.Wait(m_mutexSuspend
);
469 void wxThreadInternal::Resume()
471 wxCHECK_RET( m_state
== STATE_PAUSED
,
472 T("can't resume thread which is not suspended.") );
474 // we will be able to lock this mutex only when Pause() starts waiting
475 wxMutexLocker
lock(m_mutexSuspend
);
476 m_condSuspend
.Signal();
478 SetState(STATE_RUNNING
);
481 // -----------------------------------------------------------------------------
483 // -----------------------------------------------------------------------------
485 wxThread
*wxThread::This()
487 return (wxThread
*)pthread_getspecific(gs_keySelf
);
490 bool wxThread::IsMain()
492 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
495 void wxThread::Yield()
500 void wxThread::Sleep(unsigned long milliseconds
)
502 wxUsleep(milliseconds
);
505 // -----------------------------------------------------------------------------
507 // -----------------------------------------------------------------------------
511 // add this thread to the global list of all threads
512 gs_allThreads
.Add(this);
514 p_internal
= new wxThreadInternal();
517 wxThreadError
wxThread::Create()
519 if (p_internal
->GetState() != STATE_NEW
)
520 return wxTHREAD_RUNNING
;
522 // set up the thread attribute: right now, we only set thread priority
524 pthread_attr_init(&attr
);
526 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
528 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
530 wxLogError(_("Cannot retrieve thread scheduling policy."));
533 int min_prio
= sched_get_priority_min(prio
),
534 max_prio
= sched_get_priority_max(prio
);
536 if ( min_prio
== -1 || max_prio
== -1 )
538 wxLogError(_("Cannot get priority range for scheduling policy %d."),
541 else if ( max_prio
== min_prio
)
543 if ( p_internal
->GetPriority() != WXTHREAD_DEFAULT_PRIORITY
)
545 // notify the programmer that this doesn't work here
546 wxLogWarning(_("Thread priority setting is ignored."));
548 //else: we have default priority, so don't complain
550 // anyhow, don't do anything because priority is just ignored
554 struct sched_param sp
;
555 pthread_attr_getschedparam(&attr
, &sp
);
556 sp
.sched_priority
= min_prio
+
557 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
558 pthread_attr_setschedparam(&attr
, &sp
);
560 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
562 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
563 // this will make the threads created by this process really concurrent
564 pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
);
565 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
567 // create the new OS thread object
568 int rc
= pthread_create(p_internal
->GetIdPtr(), &attr
,
569 wxThreadInternal::PthreadStart
, (void *)this);
570 pthread_attr_destroy(&attr
);
574 p_internal
->SetState(STATE_EXITED
);
575 return wxTHREAD_NO_RESOURCE
;
578 return wxTHREAD_NO_ERROR
;
581 wxThreadError
wxThread::Run()
583 wxCHECK_MSG( p_internal
->GetId(), wxTHREAD_MISC_ERROR
,
584 T("must call wxThread::Create() first") );
586 return p_internal
->Run();
589 // -----------------------------------------------------------------------------
591 // -----------------------------------------------------------------------------
593 void wxThread::SetPriority(unsigned int prio
)
595 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
596 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
597 T("invalid thread priority") );
599 wxCriticalSectionLocker
lock(m_critsect
);
601 switch ( p_internal
->GetState() )
604 // thread not yet started, priority will be set when it is
605 p_internal
->SetPriority(prio
);
610 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
612 struct sched_param sparam
;
613 sparam
.sched_priority
= prio
;
615 if ( pthread_setschedparam(p_internal
->GetId(),
616 SCHED_OTHER
, &sparam
) != 0 )
618 wxLogError(_("Failed to set thread priority %d."), prio
);
621 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
626 wxFAIL_MSG(T("impossible to set thread priority in this state"));
630 unsigned int wxThread::GetPriority() const
632 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
634 return p_internal
->GetPriority();
637 unsigned long wxThread::GetID() const
639 return (unsigned long)p_internal
->GetId();
642 // -----------------------------------------------------------------------------
644 // -----------------------------------------------------------------------------
646 wxThreadError
wxThread::Pause()
648 wxCriticalSectionLocker
lock(m_critsect
);
650 if ( p_internal
->GetState() != STATE_RUNNING
)
652 wxLogDebug(T("Can't pause thread which is not running."));
654 return wxTHREAD_NOT_RUNNING
;
657 p_internal
->SetState(STATE_PAUSED
);
659 return wxTHREAD_NO_ERROR
;
662 wxThreadError
wxThread::Resume()
664 wxCriticalSectionLocker
lock(m_critsect
);
666 if ( p_internal
->GetState() == STATE_PAUSED
)
669 p_internal
->Resume();
672 return wxTHREAD_NO_ERROR
;
676 wxLogDebug(T("Attempt to resume a thread which is not paused."));
678 return wxTHREAD_MISC_ERROR
;
682 // -----------------------------------------------------------------------------
684 // -----------------------------------------------------------------------------
686 wxThread::ExitCode
wxThread::Delete()
692 wxThreadState state
= p_internal
->GetState();
694 // ask the thread to stop
695 p_internal
->SetCancelFlag();
707 // resume the thread first
713 // wait until the thread stops
716 //GL: As we must auto-destroy, the destruction must happen here.
722 wxThreadError
wxThread::Kill()
724 switch ( p_internal
->GetState() )
728 return wxTHREAD_NOT_RUNNING
;
731 #ifdef HAVE_PTHREAD_CANCEL
732 if ( pthread_cancel(p_internal
->GetId()) != 0 )
735 wxLogError(_("Failed to terminate a thread."));
737 return wxTHREAD_MISC_ERROR
;
739 //GL: As we must auto-destroy, the destruction must happen here (2).
742 return wxTHREAD_NO_ERROR
;
746 void wxThread::Exit(void *status
)
748 // first call user-level clean up code
751 // next wake up the threads waiting for us (OTOH, this function won't return
752 // until someone waited for us!)
753 p_internal
->SignalExit();
755 p_internal
->SetState(STATE_EXITED
);
757 // delete both C++ thread object and terminate the OS thread object
758 // GL: This is very ugly and buggy ...
760 pthread_exit(status
);
763 // also test whether we were paused
764 bool wxThread::TestDestroy()
766 wxCriticalSectionLocker
lock(m_critsect
);
768 if ( p_internal
->GetState() == STATE_PAUSED
)
770 // leave the crit section or the other threads will stop too if they try
771 // to call any of (seemingly harmless) IsXXX() functions while we sleep
776 // enter it back before it's finally left in lock object dtor
780 return p_internal
->WasCancelled();
783 wxThread::~wxThread()
786 if ( p_internal
->GetState() != STATE_EXITED
&&
787 p_internal
->GetState() != STATE_NEW
)
789 wxLogDebug(T("The thread is being destroyed although it is still "
790 "running! The application may crash."));
797 // remove this thread from the global array
798 gs_allThreads
.Remove(this);
801 // -----------------------------------------------------------------------------
803 // -----------------------------------------------------------------------------
805 bool wxThread::IsRunning() const
807 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
809 return p_internal
->GetState() == STATE_RUNNING
;
812 bool wxThread::IsAlive() const
814 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
816 switch ( p_internal
->GetState() )
827 bool wxThread::IsPaused() const
829 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
831 return (p_internal
->GetState() == STATE_PAUSED
);
834 //--------------------------------------------------------------------
836 //--------------------------------------------------------------------
838 class wxThreadModule
: public wxModule
841 virtual bool OnInit();
842 virtual void OnExit();
845 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
848 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
850 bool wxThreadModule::OnInit()
852 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
855 wxLogSysError(rc
, _("Thread module initialization failed: "
856 "failed to create thread key"));
861 gs_mutexGui
= new wxMutex();
863 gs_tidMain
= pthread_self();
870 void wxThreadModule::OnExit()
872 wxASSERT_MSG( wxThread::IsMain(), T("only main thread can be here") );
874 // terminate any threads left
875 size_t count
= gs_allThreads
.GetCount();
877 wxLogDebug(T("Some threads were not terminated by the application."));
879 for ( size_t n
= 0u; n
< count
; n
++ )
881 // Delete calls the destructor which removes the current entry. We
882 // should only delete the first one each time.
883 gs_allThreads
[0]->Delete();
887 gs_mutexGui
->Unlock();
892 (void)pthread_key_delete(gs_keySelf
);
895 // ----------------------------------------------------------------------------
897 // ----------------------------------------------------------------------------
899 void wxMutexGuiEnter()
904 void wxMutexGuiLeave()
906 gs_mutexGui
->Unlock();