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"
54 // ----------------------------------------------------------------------------
56 // ----------------------------------------------------------------------------
58 // the possible states of the thread and transitions from them
61 STATE_NEW
, // didn't start execution yet (=> RUNNING)
62 STATE_RUNNING
, // running (=> PAUSED or EXITED)
63 STATE_PAUSED
, // suspended (=> RUNNING or EXITED)
64 STATE_EXITED
// thread doesn't exist any more
67 // ----------------------------------------------------------------------------
69 // ----------------------------------------------------------------------------
71 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
73 // -----------------------------------------------------------------------------
75 // -----------------------------------------------------------------------------
77 // we keep the list of all threads created by the application to be able to
78 // terminate them on exit if there are some left - otherwise the process would
80 static wxArrayThread gs_allThreads
;
82 // the id of the main thread
83 static pthread_t gs_tidMain
;
85 // the key for the pointer to the associated wxThread object
86 static pthread_key_t gs_keySelf
;
89 // this mutex must be acquired before any call to a GUI function
90 static wxMutex
*gs_mutexGui
;
93 // ============================================================================
95 // ============================================================================
97 //--------------------------------------------------------------------
98 // wxMutex (Posix implementation)
99 //--------------------------------------------------------------------
101 class wxMutexInternal
104 pthread_mutex_t p_mutex
;
109 p_internal
= new wxMutexInternal
;
110 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) NULL
);
117 wxLogDebug(_T("Freeing a locked mutex (%d locks)"), m_locked
);
119 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
123 wxMutexError
wxMutex::Lock()
125 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
128 wxLogDebug(_T("Locking this mutex would lead to deadlock!"));
130 return wxMUTEX_DEAD_LOCK
;
135 return wxMUTEX_NO_ERROR
;
138 wxMutexError
wxMutex::TryLock()
145 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
148 case EBUSY
: return wxMUTEX_BUSY
;
153 return wxMUTEX_NO_ERROR
;
156 wxMutexError
wxMutex::Unlock()
164 wxLogDebug(_T("Unlocking not locked mutex."));
166 return wxMUTEX_UNLOCKED
;
169 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
171 return wxMUTEX_NO_ERROR
;
174 //--------------------------------------------------------------------
175 // wxCondition (Posix implementation)
176 //--------------------------------------------------------------------
178 class wxConditionInternal
181 pthread_cond_t p_condition
;
184 wxCondition::wxCondition()
186 p_internal
= new wxConditionInternal
;
187 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
190 wxCondition::~wxCondition()
192 pthread_cond_destroy( &(p_internal
->p_condition
) );
197 void wxCondition::Wait(wxMutex
& mutex
)
199 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
202 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
204 struct timespec tspec
;
206 tspec
.tv_sec
= time(0L)+sec
;
207 tspec
.tv_nsec
= nsec
;
208 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
211 void wxCondition::Signal()
213 pthread_cond_signal( &(p_internal
->p_condition
) );
216 void wxCondition::Broadcast()
218 pthread_cond_broadcast( &(p_internal
->p_condition
) );
221 //--------------------------------------------------------------------
222 // wxThread (Posix implementation)
223 //--------------------------------------------------------------------
225 class wxThreadInternal
231 // thread entry function
232 static void *PthreadStart(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
278 // another (mutex, cond) pair for Pause()/Resume() usage
280 // VZ: it's possible that we might reuse the mutex and condition from above
281 // for this too, but as I'm not at all sure that it won't create subtle
282 // problems with race conditions between, say, Pause() and Delete() I
283 // prefer this may be a bit less efficient but much safer solution
284 wxMutex m_mutexSuspend
;
285 wxCondition m_condSuspend
;
288 void *wxThreadInternal::PthreadStart(void *ptr
)
290 wxThread
*thread
= (wxThread
*)ptr
;
291 wxThreadInternal
*pthread
= thread
->p_internal
;
293 int rc
= pthread_setspecific(gs_keySelf
, thread
);
296 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
301 // wait for the condition to be signaled from Run()
302 // mutex state: currently locked by the thread which created us
303 pthread
->m_cond
.Wait(pthread
->m_mutex
);
305 // mutex state: locked again on exit of Wait()
307 // call the main entry
308 void* status
= thread
->Entry();
310 // terminate the thread
311 thread
->Exit(status
);
313 wxFAIL_MSG(_T("wxThread::Exit() can't return."));
318 wxThreadInternal::wxThreadInternal()
323 // this mutex is locked during almost all thread lifetime - it will only be
324 // unlocked in the very end
327 // this mutex is used in Pause()/Resume() and is also locked all the time
328 // unless the thread is paused
329 m_mutexSuspend
.Lock();
332 wxThreadInternal::~wxThreadInternal()
334 // GL: moved to SignalExit
335 // m_mutexSuspend.Unlock();
337 // note that m_mutex will be unlocked by the thread which waits for our
341 wxThreadError
wxThreadInternal::Run()
343 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
344 _T("thread may only be started once after successful Create()") );
346 // the mutex was locked on Create(), so we will be able to lock it again
347 // only when the thread really starts executing and enters the wait -
348 // otherwise we might signal the condition before anybody is waiting for it
349 wxMutexLocker
lock(m_mutex
);
352 m_state
= STATE_RUNNING
;
354 return wxTHREAD_NO_ERROR
;
356 // now the mutex is unlocked back - but just to allow Wait() function to
357 // terminate by relocking it, so the net result is that the worker thread
358 // starts executing and the mutex is still locked
361 void wxThreadInternal::Wait()
363 wxCHECK_RET( WasCancelled(), _T("thread should have been cancelled first") );
365 // if the thread we're waiting for is waiting for the GUI mutex, we will
366 // deadlock so make sure we release it temporarily
367 if ( wxThread::IsMain() )
370 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
371 // it and to signal us its termination
372 m_cond
.Wait(m_mutex
);
374 // mutex is still in the locked state - relocked on exit from Wait(), so
375 // unlock it - we don't need it any more, the thread has already terminated
378 // reacquire GUI mutex
379 if ( wxThread::IsMain() )
383 void wxThreadInternal::SignalExit()
385 // GL: Unlock mutexSuspend here.
386 m_mutexSuspend
.Unlock();
388 // as mutex is currently locked, this will block until some other thread
389 // (normally the same which created this one) unlocks it by entering Wait()
392 // wake up all the threads waiting for our termination
395 // after this call mutex will be finally unlocked
399 void wxThreadInternal::Pause()
401 // the state is set from the thread which pauses us first, this function
402 // is called later so the state should have been already set
403 wxCHECK_RET( m_state
== STATE_PAUSED
,
404 _T("thread must first be paused with wxThread::Pause().") );
406 // don't pause the thread which is being terminated - this would lead to
407 // deadlock if the thread is paused after Delete() had called Resume() but
408 // before it had time to call Wait()
409 if ( WasCancelled() )
412 // wait until the condition is signaled from Resume()
413 m_condSuspend
.Wait(m_mutexSuspend
);
416 void wxThreadInternal::Resume()
418 wxCHECK_RET( m_state
== STATE_PAUSED
,
419 _T("can't resume thread which is not suspended.") );
421 // we will be able to lock this mutex only when Pause() starts waiting
422 wxMutexLocker
lock(m_mutexSuspend
);
423 m_condSuspend
.Signal();
425 SetState(STATE_RUNNING
);
428 // -----------------------------------------------------------------------------
430 // -----------------------------------------------------------------------------
432 wxThread
*wxThread::This()
434 return (wxThread
*)pthread_getspecific(gs_keySelf
);
437 bool wxThread::IsMain()
439 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
442 void wxThread::Yield()
447 void wxThread::Sleep(unsigned long milliseconds
)
449 wxUsleep(milliseconds
);
452 // -----------------------------------------------------------------------------
454 // -----------------------------------------------------------------------------
458 // add this thread to the global list of all threads
459 gs_allThreads
.Add(this);
461 p_internal
= new wxThreadInternal();
464 wxThreadError
wxThread::Create()
466 if (p_internal
->GetState() != STATE_NEW
)
467 return wxTHREAD_RUNNING
;
469 // set up the thread attribute: right now, we only set thread priority
471 pthread_attr_init(&attr
);
473 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
475 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
477 wxLogError(_("Cannot retrieve thread scheduling policy."));
480 int min_prio
= sched_get_priority_min(prio
),
481 max_prio
= sched_get_priority_max(prio
);
483 if ( min_prio
== -1 || max_prio
== -1 )
485 wxLogError(_("Cannot get priority range for scheduling policy %d."),
490 struct sched_param sp
;
491 pthread_attr_getschedparam(&attr
, &sp
);
492 sp
.sched_priority
= min_prio
+
493 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
494 pthread_attr_setschedparam(&attr
, &sp
);
496 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
498 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
499 // this will make the threads created by this process really concurrent
500 pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
);
501 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
503 // create the new OS thread object
504 int rc
= pthread_create(p_internal
->GetIdPtr(), &attr
,
505 wxThreadInternal::PthreadStart
, (void *)this);
506 pthread_attr_destroy(&attr
);
510 p_internal
->SetState(STATE_EXITED
);
511 return wxTHREAD_NO_RESOURCE
;
514 return wxTHREAD_NO_ERROR
;
517 wxThreadError
wxThread::Run()
519 return p_internal
->Run();
522 // -----------------------------------------------------------------------------
524 // -----------------------------------------------------------------------------
526 void wxThread::SetPriority(unsigned int prio
)
528 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
529 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
530 _T("invalid thread priority") );
532 wxCriticalSectionLocker
lock(m_critsect
);
534 switch ( p_internal
->GetState() )
537 // thread not yet started, priority will be set when it is
538 p_internal
->SetPriority(prio
);
543 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
545 struct sched_param sparam
;
546 sparam
.sched_priority
= prio
;
548 if ( pthread_setschedparam(p_internal
->GetId(),
549 SCHED_OTHER
, &sparam
) != 0 )
551 wxLogError(_("Failed to set thread priority %d."), prio
);
554 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
559 wxFAIL_MSG(_T("impossible to set thread priority in this state"));
563 unsigned int wxThread::GetPriority() const
565 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
567 return p_internal
->GetPriority();
570 unsigned long wxThread::GetID() const
572 return (unsigned long)p_internal
->GetId();
575 // -----------------------------------------------------------------------------
577 // -----------------------------------------------------------------------------
579 wxThreadError
wxThread::Pause()
581 wxCriticalSectionLocker
lock(m_critsect
);
583 if ( p_internal
->GetState() != STATE_RUNNING
)
585 wxLogDebug(_T("Can't pause thread which is not running."));
587 return wxTHREAD_NOT_RUNNING
;
590 p_internal
->SetState(STATE_PAUSED
);
592 return wxTHREAD_NO_ERROR
;
595 wxThreadError
wxThread::Resume()
597 wxCriticalSectionLocker
lock(m_critsect
);
599 if ( p_internal
->GetState() == STATE_PAUSED
)
602 p_internal
->Resume();
605 return wxTHREAD_NO_ERROR
;
609 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
611 return wxTHREAD_MISC_ERROR
;
615 // -----------------------------------------------------------------------------
617 // -----------------------------------------------------------------------------
619 wxThread::ExitCode
wxThread::Delete()
622 wxThreadState state
= p_internal
->GetState();
625 // ask the thread to stop
626 p_internal
->SetCancelFlag();
636 // resume the thread first
642 // wait until the thread stops
649 wxThreadError
wxThread::Kill()
651 switch ( p_internal
->GetState() )
655 return wxTHREAD_NOT_RUNNING
;
658 #ifdef HAVE_PTHREAD_CANCEL
659 if ( pthread_cancel(p_internal
->GetId()) != 0 )
662 wxLogError(_("Failed to terminate a thread."));
664 return wxTHREAD_MISC_ERROR
;
667 return wxTHREAD_NO_ERROR
;
671 void wxThread::Exit(void *status
)
673 // first call user-level clean up code
676 // next wake up the threads waiting for us (OTOH, this function won't return
677 // until someone waited for us!)
678 p_internal
->SetState(STATE_EXITED
);
680 p_internal
->SignalExit();
682 // delete both C++ thread object and terminate the OS thread object
683 // GL: This is very ugly and buggy ...
685 pthread_exit(status
);
688 // also test whether we were paused
689 bool wxThread::TestDestroy()
691 wxCriticalSectionLocker
lock(m_critsect
);
693 if ( p_internal
->GetState() == STATE_PAUSED
)
695 // leave the crit section or the other threads will stop too if they try
696 // to call any of (seemingly harmless) IsXXX() functions while we sleep
701 // enter it back before it's finally left in lock object dtor
705 return p_internal
->WasCancelled();
708 wxThread::~wxThread()
710 // remove this thread from the global array
711 gs_allThreads
.Remove(this);
714 // -----------------------------------------------------------------------------
716 // -----------------------------------------------------------------------------
718 bool wxThread::IsRunning() const
720 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
722 return p_internal
->GetState() == STATE_RUNNING
;
725 bool wxThread::IsAlive() const
727 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
729 switch ( p_internal
->GetState() )
740 bool wxThread::IsPaused() const
742 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
744 return (p_internal
->GetState() == STATE_PAUSED
);
747 //--------------------------------------------------------------------
749 //--------------------------------------------------------------------
751 class wxThreadModule
: public wxModule
754 virtual bool OnInit();
755 virtual void OnExit();
758 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
761 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
763 bool wxThreadModule::OnInit()
765 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
768 wxLogSysError(rc
, _("Thread module initialization failed: "
769 "failed to create thread key"));
775 gs_mutexGui
= new wxMutex();
778 gs_tidMain
= pthread_self();
787 void wxThreadModule::OnExit()
789 wxASSERT_MSG( wxThread::IsMain(), _T("only main thread can be here") );
791 // terminate any threads left
792 size_t count
= gs_allThreads
.GetCount();
794 wxLogDebug(_T("Some threads were not terminated by the application."));
796 for ( size_t n
= 0u; n
< count
; n
++ )
798 gs_allThreads
[n
]->Delete();
803 gs_mutexGui
->Unlock();
809 (void)pthread_key_delete(gs_keySelf
);
812 // ----------------------------------------------------------------------------
814 // ----------------------------------------------------------------------------
816 void wxMutexGuiEnter()
825 void wxMutexGuiLeave()
830 gs_mutexGui
->Unlock();