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"
44 #define INFINITE 0xFFFFFFFF
47 // ----------------------------------------------------------------------------
49 // ----------------------------------------------------------------------------
51 // the possible states of the thread ("=>" shows all possible transitions from
55 STATE_NEW
, // didn't start execution yet (=> RUNNING)
56 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
57 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
58 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
59 STATE_EXITED
// thread is terminating
62 // ----------------------------------------------------------------------------
63 // this module globals
64 // ----------------------------------------------------------------------------
66 static ThreadID gs_idMainThread
= kNoThreadID
;
67 static bool gs_waitingForThread
= FALSE
;
68 size_t g_numberOfThreads
= 0;
70 // ============================================================================
71 // MacOS implementation of thread classes
72 // ============================================================================
79 if ( UMASystemIsInitialized() )
80 ThreadBeginCritical() ;
84 if ( UMASystemIsInitialized() )
89 // ----------------------------------------------------------------------------
90 // wxMutex implementation
91 // ----------------------------------------------------------------------------
96 wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
98 m_owner
= kNoThreadID
;
106 wxLogDebug(_T("Warning: freeing a locked mutex (%ld locks)."), m_locked
);
110 bool IsOk() const { return true; }
112 wxMutexError
Lock() ;
113 wxMutexError
TryLock() ;
114 wxMutexError
Unlock();
117 wxArrayLong m_waiters
;
121 wxMutexError
wxMutexInternal::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_owner
!= kNoThreadID
&& m_owner
!= current
)
133 m_waiters
.Add(current
);
134 err
= ::SetThreadStateEndCritical(kCurrentThreadID
, kStoppedThreadState
, m_owner
);
135 err
= ::ThreadBeginCritical();
141 return wxMUTEX_NO_ERROR
;
144 wxMutexError
wxMutexInternal::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_owner
!= kNoThreadID
&& m_owner
!= current
)
159 return wxMUTEX_NO_ERROR
;
162 wxMutexError
wxMutexInternal::Unlock()
164 if ( UMASystemIsInitialized() )
167 err
= ::ThreadBeginCritical();
172 // this mutex is not owned by anybody anmore
173 m_owner
= kNoThreadID
;
175 // now pass on to the first waiting thread
176 ThreadID firstWaiting
= kNoThreadID
;
178 while (!m_waiters
.IsEmpty() && !found
)
180 firstWaiting
= 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_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 // --------------------------------------------------------------------------
202 // --------------------------------------------------------------------------
204 // TODO not yet implemented
206 class wxSemaphoreInternal
209 wxSemaphoreInternal(int initialcount
, int maxcount
);
210 ~wxSemaphoreInternal();
212 bool IsOk() const { return true ; }
214 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
215 wxSemaError
TryWait() { return WaitTimeout(0); }
216 wxSemaError
WaitTimeout(unsigned long milliseconds
);
223 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
227 // make it practically infinite
232 wxSemaphoreInternal::~wxSemaphoreInternal()
236 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
238 return wxSEMA_MISC_ERROR
;
241 wxSemaError
wxSemaphoreInternal::Post()
243 return wxSEMA_MISC_ERROR
;
246 // ----------------------------------------------------------------------------
247 // wxCondition implementation
248 // ----------------------------------------------------------------------------
250 // TODO this is not yet completed
252 class wxConditionInternal
255 wxConditionInternal(wxMutex
& mutex
) : m_mutex(mutex
)
257 m_excessSignals
= 0 ;
259 ~wxConditionInternal()
263 bool IsOk() const { return m_mutex
.IsOk() ; }
267 return WaitTimeout(0xFFFFFFFF );
270 wxCondError
WaitTimeout(unsigned long msectimeout
)
272 wxMacStCritical critical
;
273 if ( m_excessSignals
> 0 )
276 return wxCOND_NO_ERROR
;
278 else if ( msectimeout
== 0 )
280 return wxCOND_MISC_ERROR
;
288 // FIXME this should be MsgWaitForMultipleObjects() as well probably
289 DWORD rc = ::WaitForSingleObject(event, timeout);
293 return rc != WAIT_TIMEOUT;
295 return wxCOND_NO_ERROR
;
299 wxMacStCritical critical
;
300 return wxCOND_NO_ERROR
;
303 wxCondError
Broadcast()
305 wxMacStCritical critical
;
306 return wxCOND_NO_ERROR
;
309 wxArrayLong m_waiters
;
310 wxInt32 m_excessSignals
;
314 // ----------------------------------------------------------------------------
315 // wxCriticalSection implementation
316 // ----------------------------------------------------------------------------
318 // it's implemented as a mutex on mac os, so it is defined in the headers
320 // ----------------------------------------------------------------------------
321 // wxThread implementation
322 // ----------------------------------------------------------------------------
324 // wxThreadInternal class
325 // ----------------------
327 class wxThreadInternal
332 m_tid
= kNoThreadID
;
334 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
345 // create a new (suspended) thread (for the given thread object)
346 bool Create(wxThread
*thread
, unsigned int stackSize
);
348 // suspend/resume/terminate
351 void Cancel() { m_state
= STATE_CANCELED
; }
354 void SetState(wxThreadState state
) { m_state
= state
; }
355 wxThreadState
GetState() const { return m_state
; }
358 void SetPriority(unsigned int priority
);
359 unsigned int GetPriority() const { return m_priority
; }
361 void SetResult( void *res
) { m_result
= res
; }
362 void *GetResult() { return m_result
; }
364 // thread handle and id
365 ThreadID
GetId() const { return m_tid
; }
368 static pascal void* MacThreadStart(wxThread
* arg
);
371 wxThreadState m_state
; // state, see wxThreadState enum
372 unsigned int m_priority
; // thread priority in "wx" units
373 ThreadID m_tid
; // thread id
375 static ThreadEntryUPP s_threadEntry
;
378 static wxArrayPtrVoid s_threads
;
380 ThreadEntryUPP
wxThreadInternal::s_threadEntry
= NULL
;
381 pascal void* wxThreadInternal::MacThreadStart(wxThread
*thread
)
383 // first of all, check whether we hadn't been cancelled already
384 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
389 void* rc
= thread
->Entry();
391 // enter m_critsect before changing the thread state
392 thread
->m_critsect
.Enter();
393 bool wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
394 thread
->m_internal
->SetState(STATE_EXITED
);
395 thread
->m_critsect
.Leave();
399 // if the thread was cancelled (from Delete()), then it the handle is still
401 if ( thread
->IsDetached() && !wasCancelled
)
406 //else: the joinable threads handle will be closed when Wait() is done
410 void wxThreadInternal::SetPriority(unsigned int priority
)
412 // Priorities don't exist on Mac
415 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
417 if ( s_threadEntry
== NULL
)
419 s_threadEntry
= NewThreadEntryUPP( (ThreadEntryProcPtr
) MacThreadStart
) ;
421 OSErr err
= NewThread( kCooperativeThread
,
431 wxLogSysError(_("Can't create thread"));
435 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
437 SetPriority(m_priority
);
445 bool wxThreadInternal::Suspend()
449 ::ThreadBeginCritical();
451 if ( m_state
!= STATE_RUNNING
)
453 ::ThreadEndCritical() ;
454 wxLogSysError(_("Can not suspend thread %x"), m_tid
);
458 m_state
= STATE_PAUSED
;
460 err
= ::SetThreadStateEndCritical(m_tid
, kStoppedThreadState
, kNoThreadID
);
465 bool wxThreadInternal::Resume()
469 err
= MacGetCurrentThread( ¤t
) ;
471 wxASSERT( err
== noErr
) ;
472 wxASSERT( current
!= m_tid
) ;
474 ::ThreadBeginCritical();
475 if ( m_state
!= STATE_PAUSED
&& m_state
!= STATE_NEW
)
477 ::ThreadEndCritical() ;
478 wxLogSysError(_("Can not resume thread %x"), m_tid
);
482 err
= ::SetThreadStateEndCritical(m_tid
, kReadyThreadState
, kNoThreadID
);
483 wxASSERT( err
== noErr
) ;
485 m_state
= STATE_RUNNING
;
486 ::ThreadEndCritical() ;
487 ::YieldToAnyThread() ;
493 wxThread
*wxThread::This()
495 wxMacStCritical critical
;
500 err
= MacGetCurrentThread( ¤t
) ;
502 for ( size_t i
= 0 ; i
< s_threads
.Count() ; ++i
)
504 if ( ( (wxThread
*) s_threads
[i
] )->GetId() == current
)
505 return (wxThread
*) s_threads
[i
] ;
508 wxLogSysError(_("Couldn't get the current thread pointer"));
512 bool wxThread::IsMain()
517 err
= MacGetCurrentThread( ¤t
) ;
518 return current
== gs_idMainThread
;
525 void wxThread::Yield()
527 #if TARGET_API_MAC_OSX
528 CFRunLoopRunInMode( kCFRunLoopDefaultMode
, 0 , true ) ;
530 ::YieldToAnyThread() ;
534 void wxThread::Sleep(unsigned long milliseconds
)
536 UnsignedWide start
, now
;
538 Microseconds(&start
);
540 double mssleep
= milliseconds
* 1000 ;
541 double msstart
, msnow
;
542 msstart
= (start
.hi
* 4294967296.0 + start
.lo
) ;
548 msnow
= (now
.hi
* 4294967296.0 + now
.lo
) ;
549 } while( msnow
- msstart
< mssleep
);
552 int wxThread::GetCPUCount()
554 // we will use whatever MP API will be used for the new MP Macs
558 unsigned long wxThread::GetCurrentId()
561 MacGetCurrentThread( ¤t
) ;
562 return (unsigned long)current
;
565 bool wxThread::SetConcurrency(size_t level
)
567 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
569 // ok only for the default one
573 // how many CPUs have we got?
574 if ( GetCPUCount() == 1 )
576 // don't bother with all this complicated stuff - on a single
577 // processor system it doesn't make much sense anyhow
587 wxThread::wxThread(wxThreadKind kind
)
590 m_internal
= new wxThreadInternal();
592 m_isDetached
= kind
== wxTHREAD_DETACHED
;
593 s_threads
.Add( (void*) this ) ;
596 wxThread::~wxThread()
598 if (g_numberOfThreads
>0)
605 wxFAIL_MSG(wxT("More threads deleted than created."));
609 s_threads
.Remove( (void*) this ) ;
610 if (m_internal
!= NULL
) {
616 // create/start thread
617 // -------------------
619 wxThreadError
wxThread::Create(unsigned int stackSize
)
621 wxCriticalSectionLocker
lock(m_critsect
);
623 if ( !m_internal
->Create(this, stackSize
) )
624 return wxTHREAD_NO_RESOURCE
;
626 return wxTHREAD_NO_ERROR
;
629 wxThreadError
wxThread::Run()
631 wxCriticalSectionLocker
lock(m_critsect
);
633 if ( m_internal
->GetState() != STATE_NEW
)
635 // actually, it may be almost any state at all, not only STATE_RUNNING
636 return wxTHREAD_RUNNING
;
639 // the thread has just been created and is still suspended - let it run
643 // suspend/resume thread
644 // ---------------------
646 wxThreadError
wxThread::Pause()
648 wxCriticalSectionLocker
lock(m_critsect
);
650 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
653 wxThreadError
wxThread::Resume()
655 wxCriticalSectionLocker
lock(m_critsect
);
657 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
663 wxThread::ExitCode
wxThread::Wait()
665 // although under MacOS we can wait for any thread, it's an error to
666 // wait for a detached one in wxWin API
667 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
668 _T("can't wait for detached thread") );
670 ExitCode rc
= (ExitCode
)-1;
679 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
683 // Delete() is always safe to call, so consider all possible states
685 // has the thread started to run?
686 bool shouldResume
= FALSE
;
689 wxCriticalSectionLocker
lock(m_critsect
);
691 if ( m_internal
->GetState() == STATE_NEW
)
693 // WinThreadStart() will see it and terminate immediately
694 m_internal
->SetState(STATE_EXITED
);
700 // is the thread paused?
701 if ( shouldResume
|| IsPaused() )
704 // does is still run?
709 // set flag for wxIsWaitingForThread()
710 gs_waitingForThread
= TRUE
;
717 // ask the thread to terminate
719 wxCriticalSectionLocker
lock(m_critsect
);
721 m_internal
->Cancel();
725 // simply wait for the thread to terminate
726 while( TestDestroy() )
728 ::YieldToAnyThread() ;
731 // simply wait for the thread to terminate
732 while( TestDestroy() )
734 ::YieldToAnyThread() ;
736 #endif // wxUSE_GUI/!wxUSE_GUI
740 gs_waitingForThread
= FALSE
;
750 // if the thread exits normally, this is done in WinThreadStart, but in
751 // this case it would have been too early because
752 // MsgWaitForMultipleObject() would fail if the therad handle was
753 // closed while we were waiting on it, so we must do it here
760 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
763 wxThreadError
wxThread::Kill()
766 return wxTHREAD_NOT_RUNNING
;
768 // if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
770 wxLogSysError(_("Couldn't terminate thread"));
772 return wxTHREAD_MISC_ERROR
;
782 return wxTHREAD_NO_ERROR
;
785 void wxThread::Exit(ExitCode status
)
794 m_internal
->SetResult( status
) ;
797 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
798 _endthreadex((unsigned)status);
800 ::ExitThread((DWORD)status);
803 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
809 // since all these calls are execute cooperatively we don't have to use the critical section
811 void wxThread::SetPriority(unsigned int prio
)
813 m_internal
->SetPriority(prio
);
816 unsigned int wxThread::GetPriority() const
818 return m_internal
->GetPriority();
821 unsigned long wxThread::GetId() const
823 return (unsigned long)m_internal
->GetId();
826 bool wxThread::IsRunning() const
828 return m_internal
->GetState() == STATE_RUNNING
;
831 bool wxThread::IsAlive() const
833 return (m_internal
->GetState() == STATE_RUNNING
) ||
834 (m_internal
->GetState() == STATE_PAUSED
);
837 bool wxThread::IsPaused() const
839 return m_internal
->GetState() == STATE_PAUSED
;
842 bool wxThread::TestDestroy()
844 return m_internal
->GetState() == STATE_CANCELED
;
847 // ----------------------------------------------------------------------------
848 // Automatic initialization for thread module
849 // ----------------------------------------------------------------------------
851 class wxThreadModule
: public wxModule
854 virtual bool OnInit();
855 virtual void OnExit();
858 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
861 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
863 bool wxThreadModule::OnInit()
866 bool hasThreadManager
;
867 hasThreadManager
= Gestalt( gestaltThreadMgrAttr
, &response
) == noErr
&& response
& 1;
870 // verify presence of shared library
871 hasThreadManager
= hasThreadManager
&& ((Ptr
)NewThread
!= (Ptr
)kUnresolvedCFragSymbolAddress
);
874 if ( !hasThreadManager
)
876 wxLogSysError( wxT("Thread Support is not available on this System") );
880 // no error return for GetCurrentThreadId()
881 MacGetCurrentThread( &gs_idMainThread
) ;
886 void wxThreadModule::OnExit()
890 // ----------------------------------------------------------------------------
891 // under MacOS we don't have currently preemptive threads, so any thread may access
892 // the GUI at any time
893 // ----------------------------------------------------------------------------
895 void WXDLLEXPORT
wxMutexGuiEnter()
899 void WXDLLEXPORT
wxMutexGuiLeave()
903 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
907 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
912 // wake up the main thread
913 void WXDLLEXPORT
wxWakeUpMainThread()
918 bool WXDLLEXPORT
wxIsWaitingForThread()
923 #include "wx/thrimpl.cpp"
925 #endif // wxUSE_THREADS