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 #include "wx/thread.h"
30 #error This file needs wxUSE_THREADS
33 #include "wx/module.h"
37 #include "wx/dynarray.h"
49 // ----------------------------------------------------------------------------
51 // ----------------------------------------------------------------------------
55 STATE_NEW
, // didn't start execution yet (=> RUNNING)
62 WX_DEFINE_ARRAY(wxThread
*, wxArrayThread
);
64 // -----------------------------------------------------------------------------
66 // -----------------------------------------------------------------------------
68 // we keep the list of all threads created by the application to be able to
69 // terminate them on exit if there are some left - otherwise the process would
71 static wxArrayThread gs_allThreads
;
73 // the id of the main thread
74 static pthread_t gs_tidMain
;
76 // the key for the pointer to the associated wxThread object
77 static pthread_key_t gs_keySelf
;
79 // this mutex must be acquired before any call to a GUI function
80 static wxMutex
*gs_mutexGui
;
82 // ============================================================================
84 // ============================================================================
86 //--------------------------------------------------------------------
87 // wxMutex (Posix implementation)
88 //--------------------------------------------------------------------
93 pthread_mutex_t p_mutex
;
98 p_internal
= new wxMutexInternal
;
99 pthread_mutex_init( &(p_internal
->p_mutex
), (const pthread_mutexattr_t
*) NULL
);
106 wxLogDebug("Freeing a locked mutex (%d locks)", m_locked
);
108 pthread_mutex_destroy( &(p_internal
->p_mutex
) );
112 wxMutexError
wxMutex::Lock()
114 int err
= pthread_mutex_lock( &(p_internal
->p_mutex
) );
117 wxLogDebug("Locking this mutex would lead to deadlock!");
119 return wxMUTEX_DEAD_LOCK
;
124 return wxMUTEX_NO_ERROR
;
127 wxMutexError
wxMutex::TryLock()
134 int err
= pthread_mutex_trylock( &(p_internal
->p_mutex
) );
137 case EBUSY
: return wxMUTEX_BUSY
;
142 return wxMUTEX_NO_ERROR
;
145 wxMutexError
wxMutex::Unlock()
153 wxLogDebug("Unlocking not locked mutex.");
155 return wxMUTEX_UNLOCKED
;
158 pthread_mutex_unlock( &(p_internal
->p_mutex
) );
160 return wxMUTEX_NO_ERROR
;
163 //--------------------------------------------------------------------
164 // wxCondition (Posix implementation)
165 //--------------------------------------------------------------------
167 class wxConditionInternal
170 pthread_cond_t p_condition
;
173 wxCondition::wxCondition()
175 p_internal
= new wxConditionInternal
;
176 pthread_cond_init( &(p_internal
->p_condition
), (const pthread_condattr_t
*) NULL
);
179 wxCondition::~wxCondition()
181 pthread_cond_destroy( &(p_internal
->p_condition
) );
186 void wxCondition::Wait(wxMutex
& mutex
)
188 pthread_cond_wait( &(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
) );
191 bool wxCondition::Wait(wxMutex
& mutex
, unsigned long sec
, unsigned long nsec
)
193 struct timespec tspec
;
195 tspec
.tv_sec
= time(0L)+sec
;
196 tspec
.tv_nsec
= nsec
;
197 return (pthread_cond_timedwait(&(p_internal
->p_condition
), &(mutex
.p_internal
->p_mutex
), &tspec
) != ETIMEDOUT
);
200 void wxCondition::Signal()
202 pthread_cond_signal( &(p_internal
->p_condition
) );
205 void wxCondition::Broadcast()
207 pthread_cond_broadcast( &(p_internal
->p_condition
) );
210 //--------------------------------------------------------------------
211 // wxThread (Posix implementation)
212 //--------------------------------------------------------------------
214 class wxThreadInternal
220 // thread entry function
221 static void *PthreadStart(void *ptr
);
226 // ask the thread to terminate
228 // wake up threads waiting for our termination
230 // go to sleep until Resume() is called
237 int GetPriority() const { return m_prio
; }
238 void SetPriority(int prio
) { m_prio
= prio
; }
240 thread_state
GetState() const { return m_state
; }
241 void SetState(thread_state state
) { m_state
= state
; }
243 pthread_t
GetId() const { return thread_id
; }
245 bool WasCancelled() const { return m_cancelled
; }
247 //private: -- should be!
251 thread_state m_state
; // see thread_state enum
252 int m_prio
; // in wxWindows units: from 0 to 100
254 // set when the thread should terminate
257 // this (mutex, cond) pair is used to synchronize the main thread and this
258 // thread in several situations:
259 // 1. The thread function blocks until condition is signaled by Run() when
260 // it's initially created - this allows create thread in "suspended"
262 // 2. The Delete() function blocks until the condition is signaled when the
267 // another (mutex, cond) pair for Pause()/Resume() usage
269 // VZ: it's possible that we might reuse the mutex and condition from above
270 // for this too, but as I'm not at all sure that it won't create subtle
271 // problems with race conditions between, say, Pause() and Delete() I
272 // prefer this may be a bit less efficient but much safer solution
273 wxMutex m_mutexSuspend
;
274 wxCondition m_condSuspend
;
277 void *wxThreadInternal::PthreadStart(void *ptr
)
279 wxThread
*thread
= (wxThread
*)ptr
;
280 wxThreadInternal
*pthread
= thread
->p_internal
;
282 if ( pthread_setspecific(gs_keySelf
, thread
) != 0 )
284 wxLogError(_("Can not start thread: error writing TLS."));
289 // wait for the condition to be signaled from Run()
290 // mutex state: currently locked by the thread which created us
291 pthread
->m_cond
.Wait(pthread
->m_mutex
);
293 // mutex state: locked again on exit of Wait()
295 // call the main entry
296 void* status
= thread
->Entry();
298 // terminate the thread
299 thread
->Exit(status
);
301 wxFAIL_MSG("wxThread::Exit() can't return.");
306 wxThreadInternal::wxThreadInternal()
311 // this mutex is locked during almost all thread lifetime - it will only be
312 // unlocked in the very end
315 // this mutex is used in Pause()/Resume() and is also locked all the time
316 // unless the thread is paused
317 m_mutexSuspend
.Lock();
320 wxThreadInternal::~wxThreadInternal()
322 m_mutexSuspend
.Unlock();
324 // note that m_mutex will be unlocked by the thread which waits for our
328 wxThreadError
wxThreadInternal::Run()
330 wxCHECK_MSG( GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
331 "thread may only be started once after successful Create()" );
333 // the mutex was locked on Create(), so we will be able to lock it again
334 // only when the thread really starts executing and enters the wait -
335 // otherwise we might signal the condition before anybody is waiting for it
336 wxMutexLocker
lock(m_mutex
);
339 m_state
= STATE_RUNNING
;
341 return wxTHREAD_NO_ERROR
;
343 // now the mutex is unlocked back - but just to allow Wait() function to
344 // terminate by relocking it, so the net result is that the worker thread
345 // starts executing and the mutex is still locked
348 void wxThreadInternal::Cancel()
350 // if the thread we're waiting for is waiting for the GUI mutex, we will
351 // deadlock so make sure we release it temporarily
352 if ( wxThread::IsMain() )
355 // nobody ever writes this variable so it's safe to not use any
356 // synchronization here
359 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
360 // it and to signal us its termination
361 m_cond
.Wait(m_mutex
);
363 // mutex is still in the locked state - relocked on exit from Wait(), so
364 // unlock it - we don't need it any more, the thread has already terminated
367 // reacquire GUI mutex
368 if ( wxThread::IsMain() )
372 void wxThreadInternal::SignalExit()
374 // as mutex is currently locked, this will block until some other thread
375 // (normally the same which created this one) unlocks it by entering Wait()
378 // wake up all the threads waiting for our termination
381 // after this call mutex will be finally unlocked
385 void wxThreadInternal::Pause()
387 wxCHECK_RET( m_state
== STATE_PAUSED
,
388 "thread must first be paused with wxThread::Pause()." );
390 // wait until the condition is signaled from Resume()
391 m_condSuspend
.Wait(m_mutexSuspend
);
394 void wxThreadInternal::Resume()
396 wxCHECK_RET( m_state
== STATE_PAUSED
,
397 "can't resume thread which is not suspended." );
399 // we will be able to lock this mutex only when Pause() starts waiting
400 wxMutexLocker
lock(m_mutexSuspend
);
401 m_condSuspend
.Signal();
403 SetState(STATE_RUNNING
);
406 // -----------------------------------------------------------------------------
408 // -----------------------------------------------------------------------------
410 wxThread
*wxThread::This()
412 return (wxThread
*)pthread_getspecific(gs_keySelf
);
415 bool wxThread::IsMain()
417 return (bool)pthread_equal(pthread_self(), gs_tidMain
);
420 void wxThread::Yield()
425 void wxThread::Sleep(unsigned long milliseconds
)
427 wxUsleep(milliseconds
);
430 // -----------------------------------------------------------------------------
432 // -----------------------------------------------------------------------------
436 // add this thread to the global list of all threads
437 gs_allThreads
.Add(this);
439 p_internal
= new wxThreadInternal();
442 wxThreadError
wxThread::Create()
444 if (p_internal
->GetState() != STATE_NEW
)
445 return wxTHREAD_RUNNING
;
447 // set up the thread attribute: right now, we only set thread priority
449 pthread_attr_init(&attr
);
452 if ( pthread_attr_getschedpolicy(&attr
, &prio
) != 0 )
454 wxLogError(_("Can not retrieve thread scheduling policy."));
457 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
458 int min_prio
= sched_get_priority_min(prio
),
459 max_prio
= sched_get_priority_max(prio
);
461 if ( min_prio
== -1 || max_prio
== -1 )
463 wxLogError(_("Can not get priority range for scheduling policy %d."),
468 struct sched_param sp
;
469 pthread_attr_getschedparam(&attr
, &sp
);
470 sp
.sched_priority
= min_prio
+
471 (p_internal
->GetPriority()*(max_prio
-min_prio
))/100;
472 pthread_attr_setschedparam(&attr
, &sp
);
474 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
476 // create the new OS thread object
477 int rc
= pthread_create(&p_internal
->thread_id
, &attr
,
478 wxThreadInternal::PthreadStart
, (void *)this);
479 pthread_attr_destroy(&attr
);
483 p_internal
->SetState(STATE_EXITED
);
484 return wxTHREAD_NO_RESOURCE
;
487 return wxTHREAD_NO_ERROR
;
490 wxThreadError
wxThread::Run()
492 return p_internal
->Run();
495 // -----------------------------------------------------------------------------
497 // -----------------------------------------------------------------------------
499 void wxThread::SetPriority(unsigned int prio
)
501 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY
<= (int)prio
) &&
502 ((int)prio
<= (int)WXTHREAD_MAX_PRIORITY
),
503 "invalid thread priority" );
505 wxCriticalSectionLocker
lock(m_critsect
);
507 switch ( p_internal
->GetState() )
510 // thread not yet started, priority will be set when it is
511 p_internal
->SetPriority(prio
);
516 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
518 struct sched_param sparam
;
519 sparam
.sched_priority
= prio
;
521 if ( pthread_setschedparam(p_internal
->GetId(),
522 SCHED_OTHER
, &sparam
) != 0 )
524 wxLogError(_("Failed to set thread priority %d."), prio
);
527 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
532 wxFAIL_MSG("impossible to set thread priority in this state");
536 unsigned int wxThread::GetPriority() const
538 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
540 return p_internal
->GetPriority();
543 unsigned long wxThread::GetID() const
545 return (unsigned long)p_internal
->thread_id
;
548 // -----------------------------------------------------------------------------
550 // -----------------------------------------------------------------------------
552 wxThreadError
wxThread::Pause()
554 wxCriticalSectionLocker
lock(m_critsect
);
556 if ( p_internal
->GetState() != STATE_RUNNING
)
558 wxLogDebug("Can't pause thread which is not running.");
560 return wxTHREAD_NOT_RUNNING
;
563 p_internal
->SetState(STATE_PAUSED
);
565 return wxTHREAD_NO_ERROR
;
568 wxThreadError
wxThread::Resume()
570 wxCriticalSectionLocker
lock(m_critsect
);
572 if ( p_internal
->GetState() == STATE_PAUSED
)
574 p_internal
->Resume();
576 return wxTHREAD_NO_ERROR
;
580 wxLogDebug("Attempt to resume a thread which is not paused.");
582 return wxTHREAD_MISC_ERROR
;
586 // -----------------------------------------------------------------------------
588 // -----------------------------------------------------------------------------
590 wxThread::ExitCode
wxThread::Delete()
593 thread_state state
= p_internal
->GetState();
604 // resume the thread first
610 // set the flag telling to the thread to stop and wait
611 p_internal
->Cancel();
617 wxThreadError
wxThread::Kill()
619 switch ( p_internal
->GetState() )
623 return wxTHREAD_NOT_RUNNING
;
626 #ifdef HAVE_PTHREAD_CANCEL
627 if ( pthread_cancel(p_internal
->GetId()) != 0 )
630 wxLogError(_("Failed to terminate a thread."));
632 return wxTHREAD_MISC_ERROR
;
635 return wxTHREAD_NO_ERROR
;
639 void wxThread::Exit(void *status
)
641 // first call user-level clean up code
644 // next wake up the threads waiting for us (OTOH, this function won't return
645 // until someone waited for us!)
646 p_internal
->SignalExit();
648 p_internal
->SetState(STATE_EXITED
);
650 // delete both C++ thread object and terminate the OS thread object
652 pthread_exit(status
);
655 // also test whether we were paused
656 bool wxThread::TestDestroy()
658 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
660 if ( p_internal
->GetState() == STATE_PAUSED
)
662 // leave the crit section or the other threads will stop too if they try
663 // to call any of (seemingly harmless) IsXXX() functions while we sleep
668 // enter it back before it's finally left in lock object dtor
672 return p_internal
->WasCancelled();
675 wxThread::~wxThread()
677 // remove this thread from the global array
678 gs_allThreads
.Remove(this);
681 // -----------------------------------------------------------------------------
683 // -----------------------------------------------------------------------------
685 bool wxThread::IsRunning() const
687 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
689 return p_internal
->GetState() == STATE_RUNNING
;
692 bool wxThread::IsAlive() const
694 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
696 switch ( p_internal
->GetState() )
707 //--------------------------------------------------------------------
709 //--------------------------------------------------------------------
711 class wxThreadModule
: public wxModule
714 virtual bool OnInit();
715 virtual void OnExit();
718 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
721 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
723 bool wxThreadModule::OnInit()
725 if ( pthread_key_create(&gs_keySelf
, NULL
/* dtor function */) != 0 )
727 wxLogError(_("Thread module initialization failed: "
728 "failed to create pthread key."));
733 gs_mutexGui
= new wxMutex();
737 gs_tidMain
= pthread_self();
743 void wxThreadModule::OnExit()
745 wxASSERT_MSG( wxThread::IsMain(), "only main thread can be here" );
747 // terminate any threads left
748 size_t count
= gs_allThreads
.GetCount();
750 wxLogDebug("Some threads were not terminated by the application.");
752 for ( size_t n
= 0u; n
< count
; n
++ )
754 gs_allThreads
[n
]->Delete();
758 gs_mutexGui
->Unlock();
765 (void)pthread_key_delete(gs_keySelf
);
768 // ----------------------------------------------------------------------------
770 // ----------------------------------------------------------------------------
772 void wxMutexGuiEnter()
777 void wxMutexGuiLeave()
779 gs_mutexGui
->Unlock();