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"
40 #include "wx/mac/macnotfy.h"
43 #define INFINITE 0xFFFFFFFF
46 // ----------------------------------------------------------------------------
48 // ----------------------------------------------------------------------------
50 // the possible states of the thread ("=>" shows all possible transitions from
54 STATE_NEW
, // didn't start execution yet (=> RUNNING)
55 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
56 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
57 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
58 STATE_EXITED
// thread is terminating
61 // ----------------------------------------------------------------------------
62 // this module globals
63 // ----------------------------------------------------------------------------
65 static ThreadID gs_idMainThread
= kNoThreadID
;
66 static bool gs_waitingForThread
= FALSE
;
68 // ============================================================================
69 // MacOS implementation of thread classes
70 // ============================================================================
77 if ( UMASystemIsInitialized() )
78 ThreadBeginCritical() ;
82 if ( UMASystemIsInitialized() )
87 // ----------------------------------------------------------------------------
88 // wxMutex implementation
89 // ----------------------------------------------------------------------------
94 wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
96 m_owner
= kNoThreadID
;
104 wxLogDebug(_T("Warning: freeing a locked mutex (%ld locks)."), m_locked
);
108 bool IsOk() const { return true; }
110 wxMutexError
Lock() ;
111 wxMutexError
TryLock() ;
112 wxMutexError
Unlock();
115 wxArrayLong m_waiters
;
119 wxMutexError
wxMutexInternal::Lock()
121 wxMacStCritical critical
;
122 if ( UMASystemIsInitialized() )
125 ThreadID current
= kNoThreadID
;
126 err
= ::MacGetCurrentThread(¤t
);
127 // if we are not the owner, add this thread to the list of waiting threads, stop this thread
128 // and invoke the scheduler to continue executing the owner's thread
129 while ( m_owner
!= kNoThreadID
&& m_owner
!= current
)
131 m_waiters
.Add(current
);
132 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kStoppedThreadState
, m_owner
);
133 err
= ::ThreadBeginCritical();
139 return wxMUTEX_NO_ERROR
;
142 wxMutexError
wxMutexInternal::TryLock()
144 wxMacStCritical critical
;
145 if ( UMASystemIsInitialized() )
147 ThreadID current
= kNoThreadID
;
148 ::MacGetCurrentThread(¤t
);
149 // if we are not the owner, give an error back
150 if ( m_owner
!= kNoThreadID
&& m_owner
!= current
)
157 return wxMUTEX_NO_ERROR
;
160 wxMutexError
wxMutexInternal::Unlock()
162 if ( UMASystemIsInitialized() )
165 err
= ::ThreadBeginCritical();
170 // this mutex is not owned by anybody anmore
171 m_owner
= kNoThreadID
;
173 // now pass on to the first waiting thread
174 ThreadID firstWaiting
= kNoThreadID
;
176 while (!m_waiters
.IsEmpty() && !found
)
178 firstWaiting
= m_waiters
[0];
179 err
= ::SetThreadState(firstWaiting
, kReadyThreadState
, kNoThreadID
);
180 // in case this was not successful (dead thread), we just loop on and reset the id
181 found
= (err
!= threadNotFoundErr
);
183 firstWaiting
= kNoThreadID
;
184 m_waiters
.RemoveAt(0) ;
186 // now we have a valid firstWaiting thread, which has been scheduled to run next, just end the
187 // critical section and invoke the scheduler
188 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kReadyThreadState
, firstWaiting
);
195 return wxMUTEX_NO_ERROR
;
198 // --------------------------------------------------------------------------
200 // --------------------------------------------------------------------------
202 // TODO not yet implemented
204 class wxSemaphoreInternal
207 wxSemaphoreInternal(int initialcount
, int maxcount
);
208 ~wxSemaphoreInternal();
210 bool IsOk() const { return true ; }
212 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
213 wxSemaError
TryWait() { return WaitTimeout(0); }
214 wxSemaError
WaitTimeout(unsigned long milliseconds
);
221 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
225 // make it practically infinite
230 wxSemaphoreInternal::~wxSemaphoreInternal()
234 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
236 return wxSEMA_MISC_ERROR
;
239 wxSemaError
wxSemaphoreInternal::Post()
241 return wxSEMA_MISC_ERROR
;
244 // ----------------------------------------------------------------------------
245 // wxCondition implementation
246 // ----------------------------------------------------------------------------
248 // TODO this is not yet completed
250 class wxConditionInternal
253 wxConditionInternal(wxMutex
& mutex
) : m_mutex(mutex
)
255 m_excessSignals
= 0 ;
257 ~wxConditionInternal()
261 bool IsOk() const { return m_mutex
.IsOk() ; }
265 return WaitTimeout(0xFFFFFFFF );
268 wxCondError
WaitTimeout(unsigned long msectimeout
)
270 wxMacStCritical critical
;
271 if ( m_excessSignals
> 0 )
274 return wxCOND_NO_ERROR
;
276 else if ( msectimeout
== 0 )
278 return wxCOND_MISC_ERROR
;
286 // FIXME this should be MsgWaitForMultipleObjects() as well probably
287 DWORD rc = ::WaitForSingleObject(event, timeout);
291 return rc != WAIT_TIMEOUT;
293 return wxCOND_NO_ERROR
;
297 wxMacStCritical critical
;
298 return wxCOND_NO_ERROR
;
301 wxCondError
Broadcast()
303 wxMacStCritical critical
;
304 return wxCOND_NO_ERROR
;
307 wxArrayLong m_waiters
;
308 wxInt32 m_excessSignals
;
312 // ----------------------------------------------------------------------------
313 // wxCriticalSection implementation
314 // ----------------------------------------------------------------------------
316 // it's implemented as a mutex on mac os, so it is defined in the headers
318 // ----------------------------------------------------------------------------
319 // wxThread implementation
320 // ----------------------------------------------------------------------------
322 // wxThreadInternal class
323 // ----------------------
325 class wxThreadInternal
330 m_tid
= kNoThreadID
;
332 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
343 // create a new (suspended) thread (for the given thread object)
344 bool Create(wxThread
*thread
, unsigned int stackSize
);
346 // suspend/resume/terminate
349 void Cancel() { m_state
= STATE_CANCELED
; }
352 void SetState(wxThreadState state
) { m_state
= state
; }
353 wxThreadState
GetState() const { return m_state
; }
356 void SetPriority(unsigned int priority
);
357 unsigned int GetPriority() const { return m_priority
; }
359 void SetResult( void *res
) { m_result
= res
; }
360 void *GetResult() { return m_result
; }
362 // thread handle and id
363 ThreadID
GetId() const { return m_tid
; }
366 static pascal void* MacThreadStart(wxThread
* arg
);
369 wxThreadState m_state
; // state, see wxThreadState enum
370 unsigned int m_priority
; // thread priority in "wx" units
371 ThreadID m_tid
; // thread id
373 static ThreadEntryUPP s_threadEntry
;
376 static wxArrayPtrVoid s_threads
;
378 ThreadEntryUPP
wxThreadInternal::s_threadEntry
= NULL
;
379 pascal void* wxThreadInternal::MacThreadStart(wxThread
*thread
)
381 // first of all, check whether we hadn't been cancelled already
382 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
387 void* rc
= thread
->Entry();
389 // enter m_critsect before changing the thread state
390 thread
->m_critsect
.Enter();
391 bool wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
392 thread
->m_internal
->SetState(STATE_EXITED
);
393 thread
->m_critsect
.Leave();
397 // if the thread was cancelled (from Delete()), then it the handle is still
399 if ( thread
->IsDetached() && !wasCancelled
)
404 //else: the joinable threads handle will be closed when Wait() is done
408 void wxThreadInternal::SetPriority(unsigned int priority
)
410 // Priorities don't exist on Mac
413 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
415 if ( s_threadEntry
== NULL
)
417 s_threadEntry
= NewThreadEntryUPP( (ThreadEntryProcPtr
) MacThreadStart
) ;
419 OSErr err
= NewThread( kCooperativeThread
,
429 wxLogSysError(_("Can't create thread"));
433 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
435 SetPriority(m_priority
);
443 bool wxThreadInternal::Suspend()
447 ::ThreadBeginCritical();
449 if ( m_state
!= STATE_RUNNING
)
451 ::ThreadEndCritical() ;
452 wxLogSysError(_("Can not suspend thread %x"), m_tid
);
456 m_state
= STATE_PAUSED
;
458 err
= ::SetThreadStateEndCritical(m_tid
, kStoppedThreadState
, kNoThreadID
);
463 bool wxThreadInternal::Resume()
467 err
= MacGetCurrentThread( ¤t
) ;
469 wxASSERT( err
== noErr
) ;
470 wxASSERT( current
!= m_tid
) ;
472 ::ThreadBeginCritical();
473 if ( m_state
!= STATE_PAUSED
&& m_state
!= STATE_NEW
)
475 ::ThreadEndCritical() ;
476 wxLogSysError(_("Can not resume thread %x"), m_tid
);
480 err
= ::SetThreadStateEndCritical(m_tid
, kReadyThreadState
, kNoThreadID
);
481 wxASSERT( err
== noErr
) ;
483 m_state
= STATE_RUNNING
;
484 ::ThreadEndCritical() ;
485 ::YieldToAnyThread() ;
491 wxThread
*wxThread::This()
493 wxMacStCritical critical
;
498 err
= MacGetCurrentThread( ¤t
) ;
500 for ( size_t i
= 0 ; i
< s_threads
.Count() ; ++i
)
502 if ( ( (wxThread
*) s_threads
[i
] )->GetId() == current
)
503 return (wxThread
*) s_threads
[i
] ;
506 wxLogSysError(_("Couldn't get the current thread pointer"));
510 bool wxThread::IsMain()
515 err
= MacGetCurrentThread( ¤t
) ;
516 return current
== gs_idMainThread
;
523 void wxThread::Yield()
525 ::YieldToAnyThread() ;
528 void wxThread::Sleep(unsigned long milliseconds
)
530 clock_t start
= clock();
534 } while( clock() - start
< milliseconds
/ 1000.0 * CLOCKS_PER_SEC
) ;
537 int wxThread::GetCPUCount()
539 // we will use whatever MP API will be used for the new MP Macs
543 unsigned long wxThread::GetCurrentId()
546 MacGetCurrentThread( ¤t
) ;
547 return (unsigned long)current
;
550 bool wxThread::SetConcurrency(size_t level
)
552 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
554 // ok only for the default one
558 // how many CPUs have we got?
559 if ( GetCPUCount() == 1 )
561 // don't bother with all this complicated stuff - on a single
562 // processor system it doesn't make much sense anyhow
572 wxThread::wxThread(wxThreadKind kind
)
574 m_internal
= new wxThreadInternal();
576 m_isDetached
= kind
== wxTHREAD_DETACHED
;
577 s_threads
.Add( (void*) this ) ;
580 wxThread::~wxThread()
582 s_threads
.Remove( (void*) this ) ;
583 if (m_internal
!= NULL
) {
589 // create/start thread
590 // -------------------
592 wxThreadError
wxThread::Create(unsigned int stackSize
)
594 wxCriticalSectionLocker
lock(m_critsect
);
596 if ( !m_internal
->Create(this, stackSize
) )
597 return wxTHREAD_NO_RESOURCE
;
599 return wxTHREAD_NO_ERROR
;
602 wxThreadError
wxThread::Run()
604 wxCriticalSectionLocker
lock(m_critsect
);
606 if ( m_internal
->GetState() != STATE_NEW
)
608 // actually, it may be almost any state at all, not only STATE_RUNNING
609 return wxTHREAD_RUNNING
;
612 // the thread has just been created and is still suspended - let it run
616 // suspend/resume thread
617 // ---------------------
619 wxThreadError
wxThread::Pause()
621 wxCriticalSectionLocker
lock(m_critsect
);
623 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
626 wxThreadError
wxThread::Resume()
628 wxCriticalSectionLocker
lock(m_critsect
);
630 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
636 wxThread::ExitCode
wxThread::Wait()
638 // although under MacOS we can wait for any thread, it's an error to
639 // wait for a detached one in wxWin API
640 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
641 _T("can't wait for detached thread") );
643 ExitCode rc
= (ExitCode
)-1;
652 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
656 // Delete() is always safe to call, so consider all possible states
658 // has the thread started to run?
659 bool shouldResume
= FALSE
;
662 wxCriticalSectionLocker
lock(m_critsect
);
664 if ( m_internal
->GetState() == STATE_NEW
)
666 // WinThreadStart() will see it and terminate immediately
667 m_internal
->SetState(STATE_EXITED
);
673 // is the thread paused?
674 if ( shouldResume
|| IsPaused() )
677 // does is still run?
682 // set flag for wxIsWaitingForThread()
683 gs_waitingForThread
= TRUE
;
690 // ask the thread to terminate
692 wxCriticalSectionLocker
lock(m_critsect
);
694 m_internal
->Cancel();
698 // simply wait for the thread to terminate
699 while( TestDestroy() )
701 ::YieldToAnyThread() ;
704 // simply wait for the thread to terminate
705 while( TestDestroy() )
707 ::YieldToAnyThread() ;
709 #endif // wxUSE_GUI/!wxUSE_GUI
713 gs_waitingForThread
= FALSE
;
723 // if the thread exits normally, this is done in WinThreadStart, but in
724 // this case it would have been too early because
725 // MsgWaitForMultipleObject() would fail if the therad handle was
726 // closed while we were waiting on it, so we must do it here
733 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
736 wxThreadError
wxThread::Kill()
739 return wxTHREAD_NOT_RUNNING
;
741 // if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
743 wxLogSysError(_("Couldn't terminate thread"));
745 return wxTHREAD_MISC_ERROR
;
755 return wxTHREAD_NO_ERROR
;
758 void wxThread::Exit(ExitCode status
)
767 m_internal
->SetResult( status
) ;
770 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
771 _endthreadex((unsigned)status);
773 ::ExitThread((DWORD)status);
776 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
782 // since all these calls are execute cooperatively we don't have to use the critical section
784 void wxThread::SetPriority(unsigned int prio
)
786 m_internal
->SetPriority(prio
);
789 unsigned int wxThread::GetPriority() const
791 return m_internal
->GetPriority();
794 unsigned long wxThread::GetId() const
796 return (unsigned long)m_internal
->GetId();
799 bool wxThread::IsRunning() const
801 return m_internal
->GetState() == STATE_RUNNING
;
804 bool wxThread::IsAlive() const
806 return (m_internal
->GetState() == STATE_RUNNING
) ||
807 (m_internal
->GetState() == STATE_PAUSED
);
810 bool wxThread::IsPaused() const
812 return m_internal
->GetState() == STATE_PAUSED
;
815 bool wxThread::TestDestroy()
817 return m_internal
->GetState() == STATE_CANCELED
;
820 // ----------------------------------------------------------------------------
821 // Automatic initialization for thread module
822 // ----------------------------------------------------------------------------
824 class wxThreadModule
: public wxModule
827 virtual bool OnInit();
828 virtual void OnExit();
831 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
834 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
836 bool wxThreadModule::OnInit()
839 bool hasThreadManager
;
840 hasThreadManager
= Gestalt( gestaltThreadMgrAttr
, &response
) == noErr
&& response
& 1;
843 // verify presence of shared library
844 hasThreadManager
= hasThreadManager
&& ((Ptr
)NewThread
!= (Ptr
)kUnresolvedCFragSymbolAddress
);
847 if ( !hasThreadManager
)
849 wxLogSysError( wxT("Thread Support is not available on this System") );
853 // no error return for GetCurrentThreadId()
854 MacGetCurrentThread( &gs_idMainThread
) ;
859 void wxThreadModule::OnExit()
863 // ----------------------------------------------------------------------------
864 // under MacOS we don't have currently preemptive threads, so any thread may access
865 // the GUI at any time
866 // ----------------------------------------------------------------------------
868 void WXDLLEXPORT
wxMutexGuiEnter()
872 void WXDLLEXPORT
wxMutexGuiLeave()
876 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
880 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
885 // wake up the main thread
886 void WXDLLEXPORT
wxWakeUpMainThread()
891 bool WXDLLEXPORT
wxIsWaitingForThread()
896 #include "wx/thrimpl.cpp"
898 #endif // wxUSE_THREADS