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"
38 #include "wx/mac/uma.h"
41 // ----------------------------------------------------------------------------
43 // ----------------------------------------------------------------------------
45 // the possible states of the thread ("=>" shows all possible transitions from
49 STATE_NEW
, // didn't start execution yet (=> RUNNING)
50 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
51 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
52 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
53 STATE_EXITED
// thread is terminating
56 // ----------------------------------------------------------------------------
57 // this module globals
58 // ----------------------------------------------------------------------------
60 static ThreadID gs_idMainThread
= kNoThreadID
;
61 static bool gs_waitingForThread
= FALSE
;
63 // ============================================================================
64 // MacOS implementation of thread classes
65 // ============================================================================
72 if ( UMASystemIsInitialized() )
73 ThreadBeginCritical() ;
77 if ( UMASystemIsInitialized() )
82 // ----------------------------------------------------------------------------
83 // wxMutex implementation
84 // ----------------------------------------------------------------------------
91 m_owner
= kNoThreadID
;
100 wxArrayLong m_waiters
;
105 m_internal
= new wxMutexInternal
;
114 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
120 wxMutexError
wxMutex::Lock()
122 wxMacStCritical critical
;
123 if ( UMASystemIsInitialized() )
126 ThreadID current
= kNoThreadID
;
127 err
= ::MacGetCurrentThread(¤t
);
128 // if we are not the owner, add this thread to the list of waiting threads, stop this thread
129 // and invoke the scheduler to continue executing the owner's thread
130 while ( m_internal
->m_owner
!= kNoThreadID
&& m_internal
->m_owner
!= current
)
132 m_internal
->m_waiters
.Add(current
);
133 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kStoppedThreadState
, m_internal
->m_owner
);
134 err
= ::ThreadBeginCritical();
136 m_internal
->m_owner
= current
;
140 return wxMUTEX_NO_ERROR
;
143 wxMutexError
wxMutex::TryLock()
145 wxMacStCritical critical
;
146 if ( UMASystemIsInitialized() )
149 ThreadID current
= kNoThreadID
;
150 ::MacGetCurrentThread(¤t
);
151 // if we are not the owner, give an error back
152 if ( m_internal
->m_owner
!= kNoThreadID
&& m_internal
->m_owner
!= current
)
155 m_internal
->m_owner
= current
;
159 return wxMUTEX_NO_ERROR
;
162 wxMutexError
wxMutex::Unlock()
164 if ( UMASystemIsInitialized() )
167 err
= ::ThreadBeginCritical();
172 // this mutex is not owned by anybody anmore
173 m_internal
->m_owner
= kNoThreadID
;
175 // now pass on to the first waiting thread
176 ThreadID firstWaiting
= kNoThreadID
;
178 while (!m_internal
->m_waiters
.IsEmpty() && !found
)
180 firstWaiting
= m_internal
->m_waiters
[0];
181 err
= ::SetThreadState(firstWaiting
, kReadyThreadState
, kNoThreadID
);
182 // in case this was not successful (dead thread), we just loop on and reset the id
183 found
= (err
!= threadNotFoundErr
);
185 firstWaiting
= kNoThreadID
;
186 m_internal
->m_waiters
.RemoveAt(0) ;
188 // now we have a valid firstWaiting thread, which has been scheduled to run next, just end the
189 // critical section and invoke the scheduler
190 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kReadyThreadState
, firstWaiting
);
197 return wxMUTEX_NO_ERROR
;
200 // ----------------------------------------------------------------------------
201 // wxCondition implementation
202 // ----------------------------------------------------------------------------
204 class wxConditionInternal
207 wxConditionInternal()
209 m_excessSignals
= 0 ;
211 ~wxConditionInternal()
215 bool Wait(unsigned long msectimeout
)
217 wxMacStCritical critical
;
218 if ( m_excessSignals
> 0 )
223 else if ( msectimeout
== 0 )
233 // FIXME this should be MsgWaitForMultipleObjects() as well probably
234 DWORD rc = ::WaitForSingleObject(event, timeout);
238 return rc != WAIT_TIMEOUT;
244 wxMacStCritical critical
;
247 wxArrayLong m_waiters
;
248 wxInt32 m_excessSignals
;
251 wxCondition::wxCondition()
253 m_internal
= new wxConditionInternal
;
256 wxCondition::~wxCondition()
261 void wxCondition::Wait()
263 (void)m_internal
->Wait(0xFFFFFFFFL
);
266 bool wxCondition::Wait(unsigned long sec
,
269 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
272 void wxCondition::Signal()
274 // set the event to signaled: if a thread is already waiting on it, it will
275 // be woken up, otherwise the event will remain in the signaled state until
276 // someone waits on it. In any case, the system will return it to a non
277 // signalled state afterwards. If multiple threads are waiting, only one
279 m_internal
->Signal() ;
282 void wxCondition::Broadcast()
284 // this works because all these threads are already waiting and so each
285 // SetEvent() inside Signal() is really a PulseEvent() because the event
286 // state is immediately returned to non-signaled
287 for ( int i
= 0; i
< m_internal
->m_waiters
.Count(); i
++ )
293 // ----------------------------------------------------------------------------
294 // wxCriticalSection implementation
295 // ----------------------------------------------------------------------------
297 // it's implemented as a mutex on mac os, so it is defined in the headers
299 // ----------------------------------------------------------------------------
300 // wxThread implementation
301 // ----------------------------------------------------------------------------
303 // wxThreadInternal class
304 // ----------------------
306 class wxThreadInternal
311 m_tid
= kNoThreadID
;
313 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
324 // create a new (suspended) thread (for the given thread object)
325 bool Create(wxThread
*thread
, unsigned int stackSize
);
327 // suspend/resume/terminate
330 void Cancel() { m_state
= STATE_CANCELED
; }
333 void SetState(wxThreadState state
) { m_state
= state
; }
334 wxThreadState
GetState() const { return m_state
; }
337 void SetPriority(unsigned int priority
);
338 unsigned int GetPriority() const { return m_priority
; }
340 void SetResult( void *res
) { m_result
= res
; }
341 void *GetResult() { return m_result
; }
343 // thread handle and id
344 ThreadID
GetId() const { return m_tid
; }
347 static pascal void* MacThreadStart(wxThread
* arg
);
350 wxThreadState m_state
; // state, see wxThreadState enum
351 unsigned int m_priority
; // thread priority in "wx" units
352 ThreadID m_tid
; // thread id
354 static ThreadEntryUPP s_threadEntry
;
357 static wxArrayPtrVoid s_threads
;
359 ThreadEntryUPP
wxThreadInternal::s_threadEntry
= NULL
;
360 pascal void* wxThreadInternal::MacThreadStart(wxThread
*thread
)
362 // first of all, check whether we hadn't been cancelled already
363 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
368 void* rc
= thread
->Entry();
370 // enter m_critsect before changing the thread state
371 thread
->m_critsect
.Enter();
372 bool wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
373 thread
->m_internal
->SetState(STATE_EXITED
);
374 thread
->m_critsect
.Leave();
378 // if the thread was cancelled (from Delete()), then it the handle is still
380 if ( thread
->IsDetached() && !wasCancelled
)
385 //else: the joinable threads handle will be closed when Wait() is done
389 void wxThreadInternal::SetPriority(unsigned int priority
)
391 // Priorities don't exist on Mac
394 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
396 if ( s_threadEntry
== NULL
)
398 s_threadEntry
= NewThreadEntryUPP( (ThreadEntryProcPtr
) MacThreadStart
) ;
400 OSErr err
= NewThread( kCooperativeThread
,
410 wxLogSysError(_("Can't create thread"));
414 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
416 SetPriority(m_priority
);
422 bool wxThreadInternal::Suspend()
426 ::ThreadBeginCritical();
428 if ( m_state
!= STATE_RUNNING
)
430 ::ThreadEndCritical() ;
431 wxLogSysError(_("Can not suspend thread %x"), m_tid
);
435 m_state
= STATE_PAUSED
;
437 err
= ::SetThreadStateEndCritical(m_tid
, kStoppedThreadState
, kNoThreadID
);
442 bool wxThreadInternal::Resume()
446 err
= MacGetCurrentThread( ¤t
) ;
448 wxASSERT( err
== noErr
) ;
449 wxASSERT( current
!= m_tid
) ;
451 ::ThreadBeginCritical();
452 if ( m_state
!= STATE_PAUSED
&& m_state
!= STATE_NEW
)
454 ::ThreadEndCritical() ;
455 wxLogSysError(_("Can not resume thread %x"), m_tid
);
459 err
= ::SetThreadStateEndCritical(m_tid
, kReadyThreadState
, kNoThreadID
);
460 wxASSERT( err
== noErr
) ;
462 m_state
= STATE_RUNNING
;
463 ::ThreadEndCritical() ;
464 ::YieldToAnyThread() ;
470 wxThread
*wxThread::This()
472 wxMacStCritical critical
;
477 err
= MacGetCurrentThread( ¤t
) ;
479 for ( int i
= 0 ; i
< s_threads
.Count() ; ++i
)
481 if ( ( (wxThread
*) s_threads
[i
] )->GetId() == current
)
482 return (wxThread
*) s_threads
[i
] ;
485 wxLogSysError(_("Couldn't get the current thread pointer"));
489 bool wxThread::IsMain()
494 err
= MacGetCurrentThread( ¤t
) ;
495 return current
== gs_idMainThread
;
502 void wxThread::Yield()
504 ::YieldToAnyThread() ;
507 void wxThread::Sleep(unsigned long milliseconds
)
509 clock_t start
= clock() ;
513 } while( clock() - start
< milliseconds
/ CLOCKS_PER_SEC
) ;
516 int wxThread::GetCPUCount()
518 // we will use whatever MP API will be used for the new MP Macs
522 bool wxThread::SetConcurrency(size_t level
)
524 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
526 // ok only for the default one
530 // how many CPUs have we got?
531 if ( GetCPUCount() == 1 )
533 // don't bother with all this complicated stuff - on a single
534 // processor system it doesn't make much sense anyhow
544 wxThread::wxThread(wxThreadKind kind
)
546 m_internal
= new wxThreadInternal();
548 m_isDetached
= kind
== wxTHREAD_DETACHED
;
549 s_threads
.Add( (void*) this ) ;
552 wxThread::~wxThread()
554 s_threads
.Remove( (void*) this ) ;
558 // create/start thread
559 // -------------------
561 wxThreadError
wxThread::Create(unsigned int stackSize
)
563 wxCriticalSectionLocker
lock(m_critsect
);
565 if ( !m_internal
->Create(this, stackSize
) )
566 return wxTHREAD_NO_RESOURCE
;
568 return wxTHREAD_NO_ERROR
;
571 wxThreadError
wxThread::Run()
573 wxCriticalSectionLocker
lock(m_critsect
);
575 if ( m_internal
->GetState() != STATE_NEW
)
577 // actually, it may be almost any state at all, not only STATE_RUNNING
578 return wxTHREAD_RUNNING
;
581 // the thread has just been created and is still suspended - let it run
585 // suspend/resume thread
586 // ---------------------
588 wxThreadError
wxThread::Pause()
590 wxCriticalSectionLocker
lock(m_critsect
);
592 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
595 wxThreadError
wxThread::Resume()
597 wxCriticalSectionLocker
lock(m_critsect
);
599 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
605 wxThread::ExitCode
wxThread::Wait()
607 // although under MacOS we can wait for any thread, it's an error to
608 // wait for a detached one in wxWin API
609 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
610 _T("can't wait for detached thread") );
612 ExitCode rc
= (ExitCode
)-1;
621 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
625 // Delete() is always safe to call, so consider all possible states
627 // has the thread started to run?
628 bool shouldResume
= FALSE
;
631 wxCriticalSectionLocker
lock(m_critsect
);
633 if ( m_internal
->GetState() == STATE_NEW
)
635 // WinThreadStart() will see it and terminate immediately
636 m_internal
->SetState(STATE_EXITED
);
642 // is the thread paused?
643 if ( shouldResume
|| IsPaused() )
646 // does is still run?
651 // set flag for wxIsWaitingForThread()
652 gs_waitingForThread
= TRUE
;
659 // ask the thread to terminate
661 wxCriticalSectionLocker
lock(m_critsect
);
663 m_internal
->Cancel();
667 // simply wait for the thread to terminate
668 while( TestDestroy() )
670 ::YieldToAnyThread() ;
673 // simply wait for the thread to terminate
674 while( TestDestroy() )
676 ::YieldToAnyThread() ;
678 #endif // wxUSE_GUI/!wxUSE_GUI
682 gs_waitingForThread
= FALSE
;
690 // if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
692 wxLogLastError("GetExitCodeThread");
699 // if the thread exits normally, this is done in WinThreadStart, but in
700 // this case it would have been too early because
701 // MsgWaitForMultipleObject() would fail if the therad handle was
702 // closed while we were waiting on it, so we must do it here
706 // wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
707 // wxT("thread must be already terminated.") );
712 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
715 wxThreadError
wxThread::Kill()
718 return wxTHREAD_NOT_RUNNING
;
720 // if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
722 wxLogSysError(_("Couldn't terminate thread"));
724 return wxTHREAD_MISC_ERROR
;
734 return wxTHREAD_NO_ERROR
;
737 void wxThread::Exit(ExitCode status
)
746 m_internal
->SetResult( status
) ;
749 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
750 _endthreadex((unsigned)status);
752 ::ExitThread((DWORD)status);
755 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
761 // since all these calls are execute cooperatively we don't have to use the critical section
763 void wxThread::SetPriority(unsigned int prio
)
765 m_internal
->SetPriority(prio
);
768 unsigned int wxThread::GetPriority() const
770 return m_internal
->GetPriority();
773 unsigned long wxThread::GetId() const
775 return (unsigned long)m_internal
->GetId();
778 bool wxThread::IsRunning() const
780 return m_internal
->GetState() == STATE_RUNNING
;
783 bool wxThread::IsAlive() const
785 return (m_internal
->GetState() == STATE_RUNNING
) ||
786 (m_internal
->GetState() == STATE_PAUSED
);
789 bool wxThread::IsPaused() const
791 return m_internal
->GetState() == STATE_PAUSED
;
794 bool wxThread::TestDestroy()
796 return m_internal
->GetState() == STATE_CANCELED
;
799 // ----------------------------------------------------------------------------
800 // Automatic initialization for thread module
801 // ----------------------------------------------------------------------------
803 class wxThreadModule
: public wxModule
806 virtual bool OnInit();
807 virtual void OnExit();
810 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
813 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
815 bool wxThreadModule::OnInit()
818 bool hasThreadManager
;
819 hasThreadManager
= Gestalt( gestaltThreadMgrAttr
, &response
) == noErr
&& response
& 1;
822 // verify presence of shared library
823 hasThreadManager
= hasThreadManager
&& ((Ptr
)NewThread
!= (Ptr
)kUnresolvedCFragSymbolAddress
);
826 if ( !hasThreadManager
)
828 wxMessageBox( "Error" , "Thread Support is not available on this System" , wxOK
) ;
832 // no error return for GetCurrentThreadId()
833 MacGetCurrentThread( &gs_idMainThread
) ;
838 void wxThreadModule::OnExit()
842 // ----------------------------------------------------------------------------
843 // under MacOS we don't have currently preemptive threads, so any thread may access
844 // the GUI at any time
845 // ----------------------------------------------------------------------------
847 void WXDLLEXPORT
wxMutexGuiEnter()
851 void WXDLLEXPORT
wxMutexGuiLeave()
855 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
859 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
864 // wake up the main thread
865 void WXDLLEXPORT
wxWakeUpMainThread()
870 bool WXDLLEXPORT
wxIsWaitingForThread()
875 #endif // wxUSE_THREADS