1 ///////////////////////////////////////////////////////////////////////////// 
   3 // Purpose:     wxThread Implementation 
   4 // Author:      Original from Wolfram Gloger/Guilhem Lavaux/Vadim Zeitlin 
   5 // Modified by: Stefan Csomor 
   8 // Copyright:   (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998), 
   9 //                  Vadim Zeitlin (1999) , Stefan Csomor (2000) 
  10 // Licence:     wxWindows licence 
  11 ///////////////////////////////////////////////////////////////////////////// 
  14     #pragma implementation "thread.h" 
  17 // ---------------------------------------------------------------------------- 
  19 // ---------------------------------------------------------------------------- 
  21 // For compilers that support precompilation, includes "wx.h". 
  22 #include "wx/wxprec.h" 
  24 #if defined(__BORLANDC__) 
  34 #include "wx/module.h" 
  35 #include "wx/thread.h" 
  39 #include "wx/mac/uma.h" 
  42 #define INFINITE 0xFFFFFFFF 
  44 // ---------------------------------------------------------------------------- 
  46 // ---------------------------------------------------------------------------- 
  48 // the possible states of the thread ("=>" shows all possible transitions from 
  52     STATE_NEW
,          // didn't start execution yet (=> RUNNING) 
  53     STATE_RUNNING
,      // thread is running (=> PAUSED, CANCELED) 
  54     STATE_PAUSED
,       // thread is temporarily suspended (=> RUNNING) 
  55     STATE_CANCELED
,     // thread should terminate a.s.a.p. (=> EXITED) 
  56     STATE_EXITED        
// thread is terminating 
  59 // ---------------------------------------------------------------------------- 
  60 // this module globals 
  61 // ---------------------------------------------------------------------------- 
  63 static ThreadID gs_idMainThread 
= kNoThreadID 
; 
  64 static bool gs_waitingForThread 
= FALSE 
; 
  66 // ============================================================================ 
  67 // MacOS implementation of thread classes 
  68 // ============================================================================ 
  75         if ( UMASystemIsInitialized() ) 
  76             ThreadBeginCritical() ; 
  80         if ( UMASystemIsInitialized() ) 
  85 // ---------------------------------------------------------------------------- 
  86 // wxMutex implementation 
  87 // ---------------------------------------------------------------------------- 
  92     wxMutexInternal(wxMutexType 
WXUNUSED(mutexType
)) 
  94         m_owner 
= kNoThreadID 
; 
 102             wxLogDebug(_T("Warning: freeing a locked mutex (%ld locks)."), m_locked
); 
 106     bool IsOk() const { return true; } 
 108     wxMutexError 
Lock() ; 
 109     wxMutexError 
TryLock() ; 
 110     wxMutexError 
Unlock(); 
 113     wxArrayLong m_waiters 
; 
 117 wxMutexError 
wxMutexInternal::Lock() 
 119     wxMacStCritical critical 
; 
 120     if ( UMASystemIsInitialized() ) 
 123         ThreadID current 
= kNoThreadID
; 
 124         err 
= ::MacGetCurrentThread(¤t
); 
 125         // if we are not the owner, add this thread to the list of waiting threads, stop this thread 
 126         // and invoke the scheduler to continue executing the owner's thread 
 127         while ( m_owner 
!= kNoThreadID 
&& m_owner 
!= current
) 
 129             m_waiters
.Add(current
); 
 130             err 
= ::SetThreadStateEndCritical(kCurrentThreadID
, kStoppedThreadState
, m_owner
); 
 131             err 
= ::ThreadBeginCritical(); 
 137     return wxMUTEX_NO_ERROR
; 
 140 wxMutexError 
wxMutexInternal::TryLock() 
 142     wxMacStCritical critical 
; 
 143     if ( UMASystemIsInitialized() ) 
 145         ThreadID current 
= kNoThreadID
; 
 146         ::MacGetCurrentThread(¤t
); 
 147         // if we are not the owner, give an error back 
 148         if ( m_owner 
!= kNoThreadID 
&& m_owner 
!= current 
) 
 155    return wxMUTEX_NO_ERROR
; 
 158 wxMutexError 
wxMutexInternal::Unlock() 
 160     if ( UMASystemIsInitialized() ) 
 163         err 
= ::ThreadBeginCritical(); 
 168         // this mutex is not owned by anybody anmore 
 169         m_owner 
= kNoThreadID
; 
 171         // now pass on to the first waiting thread 
 172         ThreadID firstWaiting 
= kNoThreadID
; 
 174         while (!m_waiters
.IsEmpty() && !found
) 
 176             firstWaiting 
= m_waiters
[0]; 
 177             err 
= ::SetThreadState(firstWaiting
, kReadyThreadState
, kNoThreadID
); 
 178             // in case this was not successful (dead thread), we just loop on and reset the id 
 179             found 
= (err 
!= threadNotFoundErr
); 
 181                 firstWaiting 
= kNoThreadID 
; 
 182             m_waiters
.RemoveAt(0) ; 
 184         // now we have a valid firstWaiting thread, which has been scheduled to run next, just end the 
 185         // critical section and invoke the scheduler 
 186         err 
= ::SetThreadStateEndCritical(kCurrentThreadID
, kReadyThreadState
, firstWaiting
); 
 193     return wxMUTEX_NO_ERROR
; 
 196 // -------------------------------------------------------------------------- 
 198 // -------------------------------------------------------------------------- 
 200 // TODO not yet implemented 
 202 class wxSemaphoreInternal
 
 205     wxSemaphoreInternal(int initialcount
, int maxcount
); 
 206     ~wxSemaphoreInternal(); 
 208     bool IsOk() const { return true ; } 
 210     wxSemaError 
Wait() { return WaitTimeout(INFINITE
); } 
 211     wxSemaError 
TryWait() { return WaitTimeout(0); } 
 212     wxSemaError 
WaitTimeout(unsigned long milliseconds
); 
 219 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
) 
 223         // make it practically infinite 
 228 wxSemaphoreInternal::~wxSemaphoreInternal() 
 232 wxSemaError 
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
) 
 234     return wxSEMA_MISC_ERROR
; 
 237 wxSemaError 
wxSemaphoreInternal::Post() 
 239     return wxSEMA_MISC_ERROR
; 
 242 // ---------------------------------------------------------------------------- 
 243 // wxCondition implementation 
 244 // ---------------------------------------------------------------------------- 
 246 // TODO this is not yet completed 
 248 class wxConditionInternal
 
 251     wxConditionInternal(wxMutex
& mutex
) : m_mutex(mutex
) 
 253         m_excessSignals 
= 0 ; 
 255     ~wxConditionInternal() 
 259     bool IsOk() const { return m_mutex
.IsOk() ; } 
 263         return WaitTimeout(0xFFFFFFFF ); 
 266     wxCondError 
WaitTimeout(unsigned long msectimeout
) 
 268         wxMacStCritical critical 
; 
 269         if ( m_excessSignals 
> 0 ) 
 272             return wxCOND_NO_ERROR 
; 
 274         else if ( msectimeout 
== 0 ) 
 276             return wxCOND_MISC_ERROR 
; 
 284         // FIXME this should be MsgWaitForMultipleObjects() as well probably 
 285         DWORD rc = ::WaitForSingleObject(event, timeout); 
 289         return rc != WAIT_TIMEOUT; 
 291         return wxCOND_NO_ERROR 
; 
 295         wxMacStCritical critical 
; 
 296         return wxCOND_NO_ERROR
; 
 299     wxCondError 
Broadcast() 
 301         wxMacStCritical critical 
; 
 302         return wxCOND_NO_ERROR
; 
 305     wxArrayLong m_waiters 
; 
 306     wxInt32     m_excessSignals 
; 
 310 // ---------------------------------------------------------------------------- 
 311 // wxCriticalSection implementation 
 312 // ---------------------------------------------------------------------------- 
 314 // it's implemented as a mutex on mac os, so it is defined in the headers 
 316 // ---------------------------------------------------------------------------- 
 317 // wxThread implementation 
 318 // ---------------------------------------------------------------------------- 
 320 // wxThreadInternal class 
 321 // ---------------------- 
 323 class wxThreadInternal
 
 328         m_tid 
= kNoThreadID 
; 
 330         m_priority 
= WXTHREAD_DEFAULT_PRIORITY
; 
 341     // create a new (suspended) thread (for the given thread object) 
 342     bool Create(wxThread 
*thread
, unsigned int stackSize
); 
 344     // suspend/resume/terminate 
 347     void Cancel() { m_state 
= STATE_CANCELED
; } 
 350     void SetState(wxThreadState state
) { m_state 
= state
; } 
 351     wxThreadState 
GetState() const { return m_state
; } 
 354     void SetPriority(unsigned int priority
); 
 355     unsigned int GetPriority() const { return m_priority
; } 
 357     void SetResult( void *res 
) { m_result 
= res 
; } 
 358     void *GetResult() { return m_result 
; } 
 360     // thread handle and id 
 361     ThreadID  
GetId() const { return m_tid
; } 
 364     static pascal void*    MacThreadStart(wxThread
* arg
); 
 367     wxThreadState           m_state
;      // state, see wxThreadState enum 
 368     unsigned int            m_priority
;   // thread priority in "wx" units 
 369     ThreadID                m_tid
;        // thread id 
 371     static ThreadEntryUPP   s_threadEntry 
; 
 374 static wxArrayPtrVoid s_threads 
; 
 376 ThreadEntryUPP 
wxThreadInternal::s_threadEntry 
= NULL 
; 
 377 pascal void* wxThreadInternal::MacThreadStart(wxThread 
*thread
) 
 379     // first of all, check whether we hadn't been cancelled already 
 380     if ( thread
->m_internal
->GetState() == STATE_EXITED 
) 
 385     void* rc 
= thread
->Entry(); 
 387     // enter m_critsect before changing the thread state 
 388     thread
->m_critsect
.Enter(); 
 389     bool wasCancelled 
= thread
->m_internal
->GetState() == STATE_CANCELED
; 
 390     thread
->m_internal
->SetState(STATE_EXITED
); 
 391     thread
->m_critsect
.Leave(); 
 395     // if the thread was cancelled (from Delete()), then it the handle is still 
 397     if ( thread
->IsDetached() && !wasCancelled 
) 
 402     //else: the joinable threads handle will be closed when Wait() is done 
 406 void wxThreadInternal::SetPriority(unsigned int priority
) 
 408     // Priorities don't exist on Mac 
 411 bool wxThreadInternal::Create(wxThread 
*thread
, unsigned int stackSize
) 
 413     if ( s_threadEntry 
== NULL 
) 
 415         s_threadEntry 
= NewThreadEntryUPP( (ThreadEntryProcPtr
) MacThreadStart 
) ; 
 417     OSErr err 
= NewThread( kCooperativeThread
, 
 427         wxLogSysError(_("Can't create thread")); 
 431     if ( m_priority 
!= WXTHREAD_DEFAULT_PRIORITY 
) 
 433         SetPriority(m_priority
); 
 441 bool wxThreadInternal::Suspend() 
 445     ::ThreadBeginCritical(); 
 447     if ( m_state 
!= STATE_RUNNING 
) 
 449         ::ThreadEndCritical() ; 
 450         wxLogSysError(_("Can not suspend thread %x"), m_tid
); 
 454     m_state 
= STATE_PAUSED
; 
 456     err 
= ::SetThreadStateEndCritical(m_tid
, kStoppedThreadState
, kNoThreadID
); 
 461 bool wxThreadInternal::Resume() 
 465     err 
= MacGetCurrentThread( ¤t 
) ; 
 467     wxASSERT( err 
== noErr 
) ; 
 468     wxASSERT( current 
!= m_tid 
) ; 
 470     ::ThreadBeginCritical(); 
 471     if ( m_state 
!= STATE_PAUSED 
&& m_state 
!= STATE_NEW 
) 
 473         ::ThreadEndCritical() ; 
 474         wxLogSysError(_("Can not resume thread %x"), m_tid
); 
 478     err 
= ::SetThreadStateEndCritical(m_tid
, kReadyThreadState
, kNoThreadID
); 
 479     wxASSERT( err 
== noErr 
) ; 
 481     m_state 
= STATE_RUNNING
; 
 482     ::ThreadEndCritical() ; 
 483     ::YieldToAnyThread() ; 
 489 wxThread 
*wxThread::This() 
 491     wxMacStCritical critical 
; 
 496     err 
= MacGetCurrentThread( ¤t 
) ; 
 498     for ( size_t i 
= 0 ; i 
< s_threads
.Count() ; ++i 
) 
 500         if ( ( (wxThread
*) s_threads
[i
] )->GetId() == current 
) 
 501             return (wxThread
*) s_threads
[i
] ; 
 504     wxLogSysError(_("Couldn't get the current thread pointer")); 
 508 bool wxThread::IsMain() 
 513     err 
= MacGetCurrentThread( ¤t 
) ; 
 514     return current 
== gs_idMainThread
; 
 521 void wxThread::Yield() 
 523     ::YieldToAnyThread() ; 
 526 void wxThread::Sleep(unsigned long milliseconds
) 
 528     clock_t start 
= clock(); 
 532     } while( clock() - start 
< milliseconds 
/  1000.0 * CLOCKS_PER_SEC 
) ; 
 535 int wxThread::GetCPUCount() 
 537     // we will use whatever MP API will be used for the new MP Macs 
 541 unsigned long wxThread::GetCurrentId() 
 544     MacGetCurrentThread( ¤t 
) ; 
 545     return (unsigned long)current
; 
 548 bool wxThread::SetConcurrency(size_t level
) 
 550     wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") ); 
 552     // ok only for the default one 
 556     // how many CPUs have we got? 
 557     if ( GetCPUCount() == 1 ) 
 559         // don't bother with all this complicated stuff - on a single 
 560         // processor system it doesn't make much sense anyhow 
 570 wxThread::wxThread(wxThreadKind kind
) 
 572     m_internal 
= new wxThreadInternal(); 
 574     m_isDetached 
= kind 
== wxTHREAD_DETACHED
; 
 575     s_threads
.Add( (void*) this ) ; 
 578 wxThread::~wxThread() 
 580     s_threads
.Remove( (void*) this ) ; 
 581     if (m_internal 
!= NULL
) { 
 587 // create/start thread 
 588 // ------------------- 
 590 wxThreadError 
wxThread::Create(unsigned int stackSize
) 
 592     wxCriticalSectionLocker 
lock(m_critsect
); 
 594     if ( !m_internal
->Create(this, stackSize
) ) 
 595         return wxTHREAD_NO_RESOURCE
; 
 597     return wxTHREAD_NO_ERROR
; 
 600 wxThreadError 
wxThread::Run() 
 602     wxCriticalSectionLocker 
lock(m_critsect
); 
 604     if ( m_internal
->GetState() != STATE_NEW 
) 
 606         // actually, it may be almost any state at all, not only STATE_RUNNING 
 607         return wxTHREAD_RUNNING
; 
 610     // the thread has just been created and is still suspended - let it run 
 614 // suspend/resume thread 
 615 // --------------------- 
 617 wxThreadError 
wxThread::Pause() 
 619     wxCriticalSectionLocker 
lock(m_critsect
); 
 621     return m_internal
->Suspend() ? wxTHREAD_NO_ERROR 
: wxTHREAD_MISC_ERROR
; 
 624 wxThreadError 
wxThread::Resume() 
 626     wxCriticalSectionLocker 
lock(m_critsect
); 
 628     return m_internal
->Resume() ? wxTHREAD_NO_ERROR 
: wxTHREAD_MISC_ERROR
; 
 634 wxThread::ExitCode 
wxThread::Wait() 
 636     // although under MacOS we can wait for any thread, it's an error to 
 637     // wait for a detached one in wxWin API 
 638     wxCHECK_MSG( !IsDetached(), (ExitCode
)-1, 
 639                  _T("can't wait for detached thread") ); 
 641     ExitCode rc 
= (ExitCode
)-1; 
 650 wxThreadError 
wxThread::Delete(ExitCode 
*pRc
) 
 654     // Delete() is always safe to call, so consider all possible states 
 656     // has the thread started to run? 
 657     bool shouldResume 
= FALSE
; 
 660         wxCriticalSectionLocker 
lock(m_critsect
); 
 662         if ( m_internal
->GetState() == STATE_NEW 
) 
 664             // WinThreadStart() will see it and terminate immediately 
 665             m_internal
->SetState(STATE_EXITED
); 
 671     // is the thread paused? 
 672     if ( shouldResume 
|| IsPaused() ) 
 675     // does is still run? 
 680             // set flag for wxIsWaitingForThread() 
 681             gs_waitingForThread 
= TRUE
; 
 688         // ask the thread to terminate 
 690             wxCriticalSectionLocker 
lock(m_critsect
); 
 692             m_internal
->Cancel(); 
 696         // simply wait for the thread to terminate 
 697         while( TestDestroy() ) 
 699             ::YieldToAnyThread() ; 
 702         // simply wait for the thread to terminate 
 703         while( TestDestroy() ) 
 705             ::YieldToAnyThread() ; 
 707 #endif // wxUSE_GUI/!wxUSE_GUI 
 711             gs_waitingForThread 
= FALSE
; 
 719  //   if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) ) 
 721         wxLogLastError("GetExitCodeThread"); 
 728         // if the thread exits normally, this is done in WinThreadStart, but in 
 729         // this case it would have been too early because 
 730         // MsgWaitForMultipleObject() would fail if the therad handle was 
 731         // closed while we were waiting on it, so we must do it here 
 735  //   wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE, 
 736  //                 wxT("thread must be already terminated.") ); 
 741     return rc 
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR 
: wxTHREAD_NO_ERROR
; 
 744 wxThreadError 
wxThread::Kill() 
 747         return wxTHREAD_NOT_RUNNING
; 
 749 //    if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) ) 
 751         wxLogSysError(_("Couldn't terminate thread")); 
 753         return wxTHREAD_MISC_ERROR
; 
 763     return wxTHREAD_NO_ERROR
; 
 766 void wxThread::Exit(ExitCode status
) 
 775     m_internal
->SetResult( status 
) ; 
 778 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) 
 779     _endthreadex((unsigned)status); 
 781     ::ExitThread((DWORD)status); 
 784     wxFAIL_MSG(wxT("Couldn't return from ExitThread()!")); 
 790 // since all these calls are execute cooperatively we don't have to use the critical section 
 792 void wxThread::SetPriority(unsigned int prio
) 
 794     m_internal
->SetPriority(prio
); 
 797 unsigned int wxThread::GetPriority() const 
 799     return m_internal
->GetPriority(); 
 802 unsigned long wxThread::GetId() const 
 804     return (unsigned long)m_internal
->GetId(); 
 807 bool wxThread::IsRunning() const 
 809     return m_internal
->GetState() == STATE_RUNNING
; 
 812 bool wxThread::IsAlive() const 
 814     return (m_internal
->GetState() == STATE_RUNNING
) || 
 815            (m_internal
->GetState() == STATE_PAUSED
); 
 818 bool wxThread::IsPaused() const 
 820     return m_internal
->GetState() == STATE_PAUSED
; 
 823 bool wxThread::TestDestroy() 
 825     return m_internal
->GetState() == STATE_CANCELED
; 
 828 // ---------------------------------------------------------------------------- 
 829 // Automatic initialization for thread module 
 830 // ---------------------------------------------------------------------------- 
 832 class wxThreadModule 
: public wxModule
 
 835     virtual bool OnInit(); 
 836     virtual void OnExit(); 
 839     DECLARE_DYNAMIC_CLASS(wxThreadModule
) 
 842 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
) 
 844 bool wxThreadModule::OnInit() 
 847     bool hasThreadManager 
; 
 848     hasThreadManager 
= Gestalt( gestaltThreadMgrAttr
, &response
) == noErr 
&& response 
& 1; 
 851     // verify presence of shared library 
 852     hasThreadManager 
= hasThreadManager 
&& ((Ptr
)NewThread 
!= (Ptr
)kUnresolvedCFragSymbolAddress
); 
 855     if ( !hasThreadManager 
) 
 857         wxMessageBox( wxT("Error") , wxT("Thread Support is not available on this System") , wxOK 
) ; 
 861     // no error return for GetCurrentThreadId() 
 862     MacGetCurrentThread( &gs_idMainThread 
) ; 
 867 void wxThreadModule::OnExit() 
 871 // ---------------------------------------------------------------------------- 
 872 // under MacOS we don't have currently preemptive threads, so any thread may access 
 873 // the GUI at any time 
 874 // ---------------------------------------------------------------------------- 
 876 void WXDLLEXPORT 
wxMutexGuiEnter() 
 880 void WXDLLEXPORT 
wxMutexGuiLeave() 
 884 void WXDLLEXPORT 
wxMutexGuiLeaveOrEnter() 
 888 bool WXDLLEXPORT 
wxGuiOwnedByMainThread() 
 893 // wake up the main thread 
 894 void WXDLLEXPORT 
wxWakeUpMainThread() 
 899 bool WXDLLEXPORT 
wxIsWaitingForThread() 
 904 #include "wx/thrimpl.cpp" 
 906 #endif // wxUSE_THREADS