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
;
106 /* I don't know where this function is supposed to exist,
107 and NP actually means non-portable, RR. */
108 pthread_mutexattr_t attr_type
;
109 pthread_mutexattr_settype( &attr_type
, PTHREAD_MUTEX_FAST_NP
);
111 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) &attr_type
);
113 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) NULL
);
121 wxLogDebug(_T("Freeing a locked mutex (%d locks)"), m_locked
);
123 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
127 wxMutexError
wxMutex::Lock()
129 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
132 wxLogDebug(_T("Locking this mutex would lead to deadlock!"));
134 return wxMUTEX_DEAD_LOCK
;
139 return wxMUTEX_NO_ERROR
;
142 wxMutexError
wxMutex::TryLock()
149 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
152 case EBUSY
: return wxMUTEX_BUSY
;
157 return wxMUTEX_NO_ERROR
;
160 wxMutexError
wxMutex::Unlock()
168 wxLogDebug(_T("Unlocking not locked mutex."));
170 return wxMUTEX_UNLOCKED
;
173 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
175 return wxMUTEX_NO_ERROR
;
178 //--------------------------------------------------------------------
179 // wxCondition (Posix implementation)
180 //--------------------------------------------------------------------
182 class wxConditionInternal
185 pthread_cond_t p_condition
;
188 wxCondition::wxCondition()
190 p_internal
= new wxConditionInternal
;
191 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
194 wxCondition::~wxCondition()
196 pthread_cond_destroy( &(p_internal
->p_condition
) );
201 void wxCondition::Wait(wxMutex
& mutex
)
203 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
206 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
208 struct timespec tspec
;
210 tspec
.tv_sec
= time(0L)+sec
;
211 tspec
.tv_nsec
= nsec
;
212 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
215 void wxCondition::Signal()
217 pthread_cond_signal( &(p_internal
->p_condition
) );
220 void wxCondition::Broadcast()
222 pthread_cond_broadcast( &(p_internal
->p_condition
) );
225 //--------------------------------------------------------------------
226 // wxThread (Posix implementation)
227 //--------------------------------------------------------------------
229 class wxThreadInternal
235 // thread entry function
236 static void *PthreadStart(void *ptr
);
238 #if HAVE_THREAD_CLEANUP_FUNCTIONS
239 // thread exit function
240 static void PthreadCleanup(void *ptr
);
246 // ask the thread to terminate
248 // wake up threads waiting for our termination
250 // go to sleep until Resume() is called
257 int GetPriority() const { return m_prio
; }
258 void SetPriority(int prio
) { m_prio
= prio
; }
260 wxThreadState
GetState() const { return m_state
; }
261 void SetState(wxThreadState state
) { m_state
= state
; }
263 pthread_t
GetId() const { return m_threadId
; }
264 pthread_t
*GetIdPtr() { return &m_threadId
; }
266 void SetCancelFlag() { m_cancelled
= TRUE
; }
267 bool WasCancelled() const { return m_cancelled
; }
270 pthread_t m_threadId
; // id of the thread
271 wxThreadState m_state
; // see wxThreadState enum
272 int m_prio
; // in wxWindows units: from 0 to 100
274 // set when the thread should terminate
277 // this (mutex, cond) pair is used to synchronize the main thread and this
278 // thread in several situations:
279 // 1. The thread function blocks until condition is signaled by Run() when
280 // it's initially created - this allows thread creation in "suspended"
282 // 2. The Delete() function blocks until the condition is signaled when the
284 // GL: On Linux, this may fail because we can have a deadlock in either
285 // SignalExit() or Wait(): so we add m_end_mutex for the finalization.
286 wxMutex m_mutex
, m_end_mutex
;
289 // another (mutex, cond) pair for Pause()/Resume() usage
291 // VZ: it's possible that we might reuse the mutex and condition from above
292 // for this too, but as I'm not at all sure that it won't create subtle
293 // problems with race conditions between, say, Pause() and Delete() I
294 // prefer this may be a bit less efficient but much safer solution
295 wxMutex m_mutexSuspend
;
296 wxCondition m_condSuspend
;
299 void *wxThreadInternal::PthreadStart(void *ptr
)
301 wxThread
*thread
= (wxThread
*)ptr
;
302 wxThreadInternal
*pthread
= thread
->p_internal
;
305 int rc
= pthread_setspecific(gs_keySelf
, thread
);
308 wxLogSysError(rc
, _("Cannot start thread: error writing TLS"));
312 #if HAVE_THREAD_CLEANUP_FUNCTIONS
313 // Install the cleanup handler.
314 pthread_cleanup_push(wxThreadInternal::PthreadCleanup
, ptr
);
317 // wait for the condition to be signaled from Run()
318 // mutex state: currently locked by the thread which created us
319 pthread
->m_cond
.Wait(pthread
->m_mutex
);
320 // mutex state: locked again on exit of Wait()
322 // call the main entry
323 status
= thread
->Entry();
325 #if HAVE_THREAD_CLEANUP_FUNCTIONS
326 pthread_cleanup_pop(FALSE
);
329 // terminate the thread
330 thread
->Exit(status
);
332 wxFAIL_MSG(_T("wxThread::Exit() can't return."));
337 #if HAVE_THREAD_CLEANUP_FUNCTIONS
338 // Only called when the thread is explicitely killed.
340 void wxThreadInternal::PthreadCleanup(void *ptr
)
342 wxThread
*thread
= (wxThread
*) ptr
;
344 // The thread is already considered as finished.
345 if (thread
->p_internal
->GetState() == STATE_EXITED
)
348 // first call user-level clean up code
351 // next wake up the threads waiting for us (OTOH, this function won't retur
352 // until someone waited for us!)
353 thread
->p_internal
->SetState(STATE_EXITED
);
355 thread
->p_internal
->SignalExit();
359 wxThreadInternal::wxThreadInternal()
364 // this mutex is locked during almost all thread lifetime - it will only be
365 // unlocked in the very end
368 // this mutex is used by wxThreadInternal::Wait() and by
369 // wxThreadInternal::SignalExit(). We don't use m_mutex because of a
370 // possible deadlock in either Wait() or SignalExit().
373 // this mutex is used in Pause()/Resume() and is also locked all the time
374 // unless the thread is paused
375 m_mutexSuspend
.Lock();
378 wxThreadInternal::~wxThreadInternal()
380 // GL: moved to SignalExit
381 // m_mutexSuspend.Unlock();
383 // note that m_mutex will be unlocked by the thread which waits for our
386 // In the case, we didn't start the thread, all these mutex are locked:
387 // we must unlock them.
388 if (m_mutex
.IsLocked())
391 if (m_end_mutex
.IsLocked())
392 m_end_mutex
.Unlock();
394 if (m_mutexSuspend
.IsLocked())
395 m_mutexSuspend
.Unlock();
398 wxThreadError
wxThreadInternal::Run()
400 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
401 _T("thread may only be started once after successful Create()") );
403 // the mutex was locked on Create(), so we will be able to lock it again
404 // only when the thread really starts executing and enters the wait -
405 // otherwise we might signal the condition before anybody is waiting for it
406 wxMutexLocker
lock(m_mutex
);
409 m_state
= STATE_RUNNING
;
411 return wxTHREAD_NO_ERROR
;
413 // now the mutex is unlocked back - but just to allow Wait() function to
414 // terminate by relocking it, so the net result is that the worker thread
415 // starts executing and the mutex is still locked
418 void wxThreadInternal::Wait()
420 wxCHECK_RET( WasCancelled(), _T("thread should have been cancelled first") );
422 // if the thread we're waiting for is waiting for the GUI mutex, we will
423 // deadlock so make sure we release it temporarily
424 if ( wxThread::IsMain() )
427 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
428 // it and to signal us its termination
429 m_cond
.Wait(m_end_mutex
);
431 // mutex is still in the locked state - relocked on exit from Wait(), so
432 // unlock it - we don't need it any more, the thread has already terminated
433 m_end_mutex
.Unlock();
435 // After that, we wait for the real end of the other thread.
436 pthread_join(GetId(), NULL
);
438 // reacquire GUI mutex
439 if ( wxThread::IsMain() )
443 void wxThreadInternal::SignalExit()
445 // GL: Unlock mutexSuspend here.
446 m_mutexSuspend
.Unlock();
448 // as mutex is currently locked, this will block until some other thread
449 // (normally the same which created this one) unlocks it by entering Wait()
452 // wake up all the threads waiting for our termination
455 // after this call mutex will be finally unlocked
456 m_end_mutex
.Unlock();
459 void wxThreadInternal::Pause()
461 // the state is set from the thread which pauses us first, this function
462 // is called later so the state should have been already set
463 wxCHECK_RET( m_state
== STATE_PAUSED
,
464 _T("thread must first be paused with wxThread::Pause().") );
466 // don't pause the thread which is being terminated - this would lead to
467 // deadlock if the thread is paused after Delete() had called Resume() but
468 // before it had time to call Wait()
469 if ( WasCancelled() )
472 // wait until the condition is signaled from Resume()
473 m_condSuspend
.Wait(m_mutexSuspend
);
476 void wxThreadInternal::Resume()
478 wxCHECK_RET( m_state
== STATE_PAUSED
,
479 _T("can't resume thread which is not suspended.") );
481 // we will be able to lock this mutex only when Pause() starts waiting
482 wxMutexLocker
lock(m_mutexSuspend
);
483 m_condSuspend
.Signal();
485 SetState(STATE_RUNNING
);
488 // -----------------------------------------------------------------------------
490 // -----------------------------------------------------------------------------
492 wxThread
*wxThread::This()
494 return (wxThread
*)pthread_getspecific(gs_keySelf
);
497 bool wxThread::IsMain()
499 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
502 void wxThread::Yield()
507 void wxThread::Sleep(unsigned long milliseconds
)
509 wxUsleep(milliseconds
);
512 // -----------------------------------------------------------------------------
514 // -----------------------------------------------------------------------------
518 // add this thread to the global list of all threads
519 gs_allThreads
.Add(this);
521 p_internal
= new wxThreadInternal();
524 wxThreadError
wxThread::Create()
526 if (p_internal
->GetState() != STATE_NEW
)
527 return wxTHREAD_RUNNING
;
529 // set up the thread attribute: right now, we only set thread priority
531 pthread_attr_init(&attr
);
533 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
535 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
537 wxLogError(_("Cannot retrieve thread scheduling policy."));
540 int min_prio
= sched_get_priority_min(prio
),
541 max_prio
= sched_get_priority_max(prio
);
543 if ( min_prio
== -1 || max_prio
== -1 )
545 wxLogError(_("Cannot get priority range for scheduling policy %d."),
550 struct sched_param sp
;
551 pthread_attr_getschedparam(&attr
, &sp
);
552 sp
.sched_priority
= min_prio
+
553 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
554 pthread_attr_setschedparam(&attr
, &sp
);
556 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
558 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
559 // this will make the threads created by this process really concurrent
560 pthread_attr_setscope(&attr
, PTHREAD_SCOPE_SYSTEM
);
561 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
563 // create the new OS thread object
564 int rc
= pthread_create(p_internal
->GetIdPtr(), &attr
,
565 wxThreadInternal::PthreadStart
, (void *)this);
566 pthread_attr_destroy(&attr
);
570 p_internal
->SetState(STATE_EXITED
);
571 return wxTHREAD_NO_RESOURCE
;
574 return wxTHREAD_NO_ERROR
;
577 wxThreadError
wxThread::Run()
579 return p_internal
->Run();
582 // -----------------------------------------------------------------------------
584 // -----------------------------------------------------------------------------
586 void wxThread::SetPriority(unsigned int prio
)
588 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
589 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
590 _T("invalid thread priority") );
592 wxCriticalSectionLocker
lock(m_critsect
);
594 switch ( p_internal
->GetState() )
597 // thread not yet started, priority will be set when it is
598 p_internal
->SetPriority(prio
);
603 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
605 struct sched_param sparam
;
606 sparam
.sched_priority
= prio
;
608 if ( pthread_setschedparam(p_internal
->GetId(),
609 SCHED_OTHER
, &sparam
) != 0 )
611 wxLogError(_("Failed to set thread priority %d."), prio
);
614 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
619 wxFAIL_MSG(_T("impossible to set thread priority in this state"));
623 unsigned int wxThread::GetPriority() const
625 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
627 return p_internal
->GetPriority();
630 unsigned long wxThread::GetID() const
632 return (unsigned long)p_internal
->GetId();
635 // -----------------------------------------------------------------------------
637 // -----------------------------------------------------------------------------
639 wxThreadError
wxThread::Pause()
641 wxCriticalSectionLocker
lock(m_critsect
);
643 if ( p_internal
->GetState() != STATE_RUNNING
)
645 wxLogDebug(_T("Can't pause thread which is not running."));
647 return wxTHREAD_NOT_RUNNING
;
650 p_internal
->SetState(STATE_PAUSED
);
652 return wxTHREAD_NO_ERROR
;
655 wxThreadError
wxThread::Resume()
657 wxCriticalSectionLocker
lock(m_critsect
);
659 if ( p_internal
->GetState() == STATE_PAUSED
)
662 p_internal
->Resume();
665 return wxTHREAD_NO_ERROR
;
669 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
671 return wxTHREAD_MISC_ERROR
;
675 // -----------------------------------------------------------------------------
677 // -----------------------------------------------------------------------------
679 wxThread::ExitCode
wxThread::Delete()
685 wxThreadState state
= p_internal
->GetState();
687 // ask the thread to stop
688 p_internal
->SetCancelFlag();
700 // resume the thread first
706 // wait until the thread stops
709 //GL: As we must auto-destroy, the destruction must happen here.
715 wxThreadError
wxThread::Kill()
717 switch ( p_internal
->GetState() )
721 return wxTHREAD_NOT_RUNNING
;
724 #ifdef HAVE_PTHREAD_CANCEL
725 if ( pthread_cancel(p_internal
->GetId()) != 0 )
728 wxLogError(_("Failed to terminate a thread."));
730 return wxTHREAD_MISC_ERROR
;
732 //GL: As we must auto-destroy, the destruction must happen here (2).
735 return wxTHREAD_NO_ERROR
;
739 void wxThread::Exit(void *status
)
741 // first call user-level clean up code
744 // next wake up the threads waiting for us (OTOH, this function won't return
745 // until someone waited for us!)
746 p_internal
->SignalExit();
748 p_internal
->SetState(STATE_EXITED
);
750 // delete both C++ thread object and terminate the OS thread object
751 // GL: This is very ugly and buggy ...
753 pthread_exit(status
);
756 // also test whether we were paused
757 bool wxThread::TestDestroy()
759 wxCriticalSectionLocker
lock(m_critsect
);
761 if ( p_internal
->GetState() == STATE_PAUSED
)
763 // leave the crit section or the other threads will stop too if they try
764 // to call any of (seemingly harmless) IsXXX() functions while we sleep
769 // enter it back before it's finally left in lock object dtor
773 return p_internal
->WasCancelled();
776 wxThread::~wxThread()
779 if (p_internal
->GetState() != STATE_EXITED
&&
780 p_internal
->GetState() != STATE_NEW
)
781 wxLogDebug(_T("The thread is being destroyed althought it is still running ! The application may crash."));
786 // remove this thread from the global array
787 gs_allThreads
.Remove(this);
790 // -----------------------------------------------------------------------------
792 // -----------------------------------------------------------------------------
794 bool wxThread::IsRunning() const
796 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
798 return p_internal
->GetState() == STATE_RUNNING
;
801 bool wxThread::IsAlive() const
803 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
805 switch ( p_internal
->GetState() )
816 bool wxThread::IsPaused() const
818 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
820 return (p_internal
->GetState() == STATE_PAUSED
);
823 //--------------------------------------------------------------------
825 //--------------------------------------------------------------------
827 class wxThreadModule
: public wxModule
830 virtual bool OnInit();
831 virtual void OnExit();
834 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
837 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
839 bool wxThreadModule::OnInit()
841 int rc
= pthread_key_create(&gs_keySelf
, NULL
/* dtor function */);
844 wxLogSysError(rc
, _("Thread module initialization failed: "
845 "failed to create thread key"));
850 gs_mutexGui
= new wxMutex();
852 gs_tidMain
= pthread_self();
859 void wxThreadModule::OnExit()
861 wxASSERT_MSG( wxThread::IsMain(), _T("only main thread can be here") );
863 // terminate any threads left
864 size_t count
= gs_allThreads
.GetCount();
866 wxLogDebug(_T("Some threads were not terminated by the application."));
868 for ( size_t n
= 0u; n
< count
; n
++ )
870 gs_allThreads
[n
]->Delete();
874 gs_mutexGui
->Unlock();
879 (void)pthread_key_delete(gs_keySelf
);
882 // ----------------------------------------------------------------------------
884 // ----------------------------------------------------------------------------
886 void wxMutexGuiEnter()
891 void wxMutexGuiLeave()
893 gs_mutexGui
->Unlock();