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 // ----------------------------------------------------------------------------
44 // ----------------------------------------------------------------------------
46 // the possible states of the thread ("=>" shows all possible transitions from
50 STATE_NEW
, // didn't start execution yet (=> RUNNING)
51 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
52 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
53 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
54 STATE_EXITED
// thread is terminating
57 // ----------------------------------------------------------------------------
58 // this module globals
59 // ----------------------------------------------------------------------------
61 static ThreadID gs_idMainThread
= kNoThreadID
;
62 static bool gs_waitingForThread
= FALSE
;
64 // ============================================================================
65 // MacOS implementation of thread classes
66 // ============================================================================
73 if ( UMASystemIsInitialized() )
74 ThreadBeginCritical() ;
78 if ( UMASystemIsInitialized() )
83 // ----------------------------------------------------------------------------
84 // wxMutex implementation
85 // ----------------------------------------------------------------------------
92 m_owner
= kNoThreadID
;
101 wxArrayLong m_waiters
;
106 m_internal
= new wxMutexInternal
;
115 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
121 wxMutexError
wxMutex::Lock()
123 wxMacStCritical critical
;
124 if ( UMASystemIsInitialized() )
127 ThreadID current
= kNoThreadID
;
128 err
= ::MacGetCurrentThread(¤t
);
129 // if we are not the owner, add this thread to the list of waiting threads, stop this thread
130 // and invoke the scheduler to continue executing the owner's thread
131 while ( m_internal
->m_owner
!= kNoThreadID
&& m_internal
->m_owner
!= current
)
133 m_internal
->m_waiters
.Add(current
);
134 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kStoppedThreadState
, m_internal
->m_owner
);
135 err
= ::ThreadBeginCritical();
137 m_internal
->m_owner
= current
;
141 return wxMUTEX_NO_ERROR
;
144 wxMutexError
wxMutex::TryLock()
146 wxMacStCritical critical
;
147 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(wxMutex
& mutex
) : m_mutex(mutex
)
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
;
252 wxCondition::wxCondition(wxMutex
& mutex
)
254 m_internal
= new wxConditionInternal(mutex
);
257 wxCondition::~wxCondition()
262 void wxCondition::Wait()
264 (void)m_internal
->Wait(0xFFFFFFFFL
);
267 bool wxCondition::Wait(unsigned long timeout_millis
)
269 return m_internal
->Wait(timeout_millis
);
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 ( size_t 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 ( size_t 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 unsigned long wxThread::GetCurrentId()
525 MacGetCurrentThread( ¤t
) ;
526 return (unsigned long)current
;
529 bool wxThread::SetConcurrency(size_t level
)
531 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
533 // ok only for the default one
537 // how many CPUs have we got?
538 if ( GetCPUCount() == 1 )
540 // don't bother with all this complicated stuff - on a single
541 // processor system it doesn't make much sense anyhow
551 wxThread::wxThread(wxThreadKind kind
)
553 m_internal
= new wxThreadInternal();
555 m_isDetached
= kind
== wxTHREAD_DETACHED
;
556 s_threads
.Add( (void*) this ) ;
559 wxThread::~wxThread()
561 s_threads
.Remove( (void*) this ) ;
565 // create/start thread
566 // -------------------
568 wxThreadError
wxThread::Create(unsigned int stackSize
)
570 wxCriticalSectionLocker
lock(m_critsect
);
572 if ( !m_internal
->Create(this, stackSize
) )
573 return wxTHREAD_NO_RESOURCE
;
575 return wxTHREAD_NO_ERROR
;
578 wxThreadError
wxThread::Run()
580 wxCriticalSectionLocker
lock(m_critsect
);
582 if ( m_internal
->GetState() != STATE_NEW
)
584 // actually, it may be almost any state at all, not only STATE_RUNNING
585 return wxTHREAD_RUNNING
;
588 // the thread has just been created and is still suspended - let it run
592 // suspend/resume thread
593 // ---------------------
595 wxThreadError
wxThread::Pause()
597 wxCriticalSectionLocker
lock(m_critsect
);
599 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
602 wxThreadError
wxThread::Resume()
604 wxCriticalSectionLocker
lock(m_critsect
);
606 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
612 wxThread::ExitCode
wxThread::Wait()
614 // although under MacOS we can wait for any thread, it's an error to
615 // wait for a detached one in wxWin API
616 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
617 _T("can't wait for detached thread") );
619 ExitCode rc
= (ExitCode
)-1;
628 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
632 // Delete() is always safe to call, so consider all possible states
634 // has the thread started to run?
635 bool shouldResume
= FALSE
;
638 wxCriticalSectionLocker
lock(m_critsect
);
640 if ( m_internal
->GetState() == STATE_NEW
)
642 // WinThreadStart() will see it and terminate immediately
643 m_internal
->SetState(STATE_EXITED
);
649 // is the thread paused?
650 if ( shouldResume
|| IsPaused() )
653 // does is still run?
658 // set flag for wxIsWaitingForThread()
659 gs_waitingForThread
= TRUE
;
666 // ask the thread to terminate
668 wxCriticalSectionLocker
lock(m_critsect
);
670 m_internal
->Cancel();
674 // simply wait for the thread to terminate
675 while( TestDestroy() )
677 ::YieldToAnyThread() ;
680 // simply wait for the thread to terminate
681 while( TestDestroy() )
683 ::YieldToAnyThread() ;
685 #endif // wxUSE_GUI/!wxUSE_GUI
689 gs_waitingForThread
= FALSE
;
697 // if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
699 wxLogLastError("GetExitCodeThread");
706 // if the thread exits normally, this is done in WinThreadStart, but in
707 // this case it would have been too early because
708 // MsgWaitForMultipleObject() would fail if the therad handle was
709 // closed while we were waiting on it, so we must do it here
713 // wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
714 // wxT("thread must be already terminated.") );
719 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
722 wxThreadError
wxThread::Kill()
725 return wxTHREAD_NOT_RUNNING
;
727 // if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
729 wxLogSysError(_("Couldn't terminate thread"));
731 return wxTHREAD_MISC_ERROR
;
741 return wxTHREAD_NO_ERROR
;
744 void wxThread::Exit(ExitCode status
)
753 m_internal
->SetResult( status
) ;
756 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
757 _endthreadex((unsigned)status);
759 ::ExitThread((DWORD)status);
762 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
768 // since all these calls are execute cooperatively we don't have to use the critical section
770 void wxThread::SetPriority(unsigned int prio
)
772 m_internal
->SetPriority(prio
);
775 unsigned int wxThread::GetPriority() const
777 return m_internal
->GetPriority();
780 unsigned long wxThread::GetId() const
782 return (unsigned long)m_internal
->GetId();
785 bool wxThread::IsRunning() const
787 return m_internal
->GetState() == STATE_RUNNING
;
790 bool wxThread::IsAlive() const
792 return (m_internal
->GetState() == STATE_RUNNING
) ||
793 (m_internal
->GetState() == STATE_PAUSED
);
796 bool wxThread::IsPaused() const
798 return m_internal
->GetState() == STATE_PAUSED
;
801 bool wxThread::TestDestroy()
803 return m_internal
->GetState() == STATE_CANCELED
;
806 // ----------------------------------------------------------------------------
807 // Automatic initialization for thread module
808 // ----------------------------------------------------------------------------
810 class wxThreadModule
: public wxModule
813 virtual bool OnInit();
814 virtual void OnExit();
817 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
820 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
822 bool wxThreadModule::OnInit()
825 bool hasThreadManager
;
826 hasThreadManager
= Gestalt( gestaltThreadMgrAttr
, &response
) == noErr
&& response
& 1;
829 // verify presence of shared library
830 hasThreadManager
= hasThreadManager
&& ((Ptr
)NewThread
!= (Ptr
)kUnresolvedCFragSymbolAddress
);
833 if ( !hasThreadManager
)
835 wxMessageBox( "Error" , "Thread Support is not available on this System" , wxOK
) ;
839 // no error return for GetCurrentThreadId()
840 MacGetCurrentThread( &gs_idMainThread
) ;
845 void wxThreadModule::OnExit()
849 // ----------------------------------------------------------------------------
850 // under MacOS we don't have currently preemptive threads, so any thread may access
851 // the GUI at any time
852 // ----------------------------------------------------------------------------
854 void WXDLLEXPORT
wxMutexGuiEnter()
858 void WXDLLEXPORT
wxMutexGuiLeave()
862 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
866 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
871 // wake up the main thread
872 void WXDLLEXPORT
wxWakeUpMainThread()
877 bool WXDLLEXPORT
wxIsWaitingForThread()
882 #endif // wxUSE_THREADS