]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/mac/thread.cpp
regenerated for new build.h file
[wxWidgets.git] / src / mac / thread.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.cpp
3// Purpose: wxThread Implementation
4// Author: Original from Wolfram Gloger/Guilhem Lavaux/Vadim Zeitlin
5// Modified by: Stefan Csomor
6// Created: 04/22/98
7// RCS-ID: $Id$
8// Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
9// Vadim Zeitlin (1999) , Stefan Csomor (2000)
10// Licence: wxWindows licence
11/////////////////////////////////////////////////////////////////////////////
12
13#ifdef __GNUG__
14 #pragma implementation "thread.h"
15#endif
16
17// ----------------------------------------------------------------------------
18// headers
19// ----------------------------------------------------------------------------
20
21// For compilers that support precompilation, includes "wx.h".
22#include "wx/wxprec.h"
23
24#if defined(__BORLANDC__)
25 #pragma hdrstop
26#endif
27
28#ifndef WX_PRECOMP
29 #include "wx/wx.h"
30#endif
31
32#if wxUSE_THREADS
33
34#include "wx/module.h"
35#include "wx/thread.h"
36
37#ifdef __WXMAC__
38#include <Threads.h>
39#include "wx/mac/uma.h"
40#endif
41
42// ----------------------------------------------------------------------------
43// constants
44// ----------------------------------------------------------------------------
45
46// the possible states of the thread ("=>" shows all possible transitions from
47// this state)
48enum wxThreadState
49{
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
55};
56
57// ----------------------------------------------------------------------------
58// this module globals
59// ----------------------------------------------------------------------------
60
61static ThreadID gs_idMainThread = kNoThreadID ;
62static bool gs_waitingForThread = FALSE ;
63
64// ============================================================================
65// MacOS implementation of thread classes
66// ============================================================================
67
68class wxMacStCritical
69{
70public :
71 wxMacStCritical()
72 {
73 if ( UMASystemIsInitialized() )
74 ThreadBeginCritical() ;
75 }
76 ~wxMacStCritical()
77 {
78 if ( UMASystemIsInitialized() )
79 ThreadEndCritical() ;
80 }
81};
82
83// ----------------------------------------------------------------------------
84// wxMutex implementation
85// ----------------------------------------------------------------------------
86
87class wxMutexInternal
88{
89public:
90 wxMutexInternal()
91 {
92 m_owner = kNoThreadID ;
93 }
94
95 ~wxMutexInternal()
96 {
97 }
98
99public:
100 ThreadID m_owner ;
101 wxArrayLong m_waiters ;
102};
103
104wxMutex::wxMutex()
105{
106 m_internal = new wxMutexInternal;
107
108 m_locked = 0;
109}
110
111wxMutex::~wxMutex()
112{
113 if ( m_locked > 0 )
114 {
115 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked);
116 }
117
118 delete m_internal;
119}
120
121wxMutexError wxMutex::Lock()
122{
123 wxMacStCritical critical ;
124 if ( UMASystemIsInitialized() )
125 {
126 OSErr err ;
127 ThreadID current = kNoThreadID;
128 err = ::MacGetCurrentThread(&current);
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)
132 {
133 m_internal->m_waiters.Add(current);
134 err = ::SetThreadStateEndCritical(kCurrentThreadID, kStoppedThreadState, m_internal->m_owner);
135 err = ::ThreadBeginCritical();
136 }
137 m_internal->m_owner = current;
138 }
139 m_locked++;
140
141 return wxMUTEX_NO_ERROR;
142}
143
144wxMutexError wxMutex::TryLock()
145{
146 wxMacStCritical critical ;
147 if ( UMASystemIsInitialized() )
148 {
149 ThreadID current = kNoThreadID;
150 ::MacGetCurrentThread(&current);
151 // if we are not the owner, give an error back
152 if ( m_internal->m_owner != kNoThreadID && m_internal->m_owner != current )
153 return wxMUTEX_BUSY;
154
155 m_internal->m_owner = current;
156 }
157 m_locked++;
158
159 return wxMUTEX_NO_ERROR;
160}
161
162wxMutexError wxMutex::Unlock()
163{
164 if ( UMASystemIsInitialized() )
165 {
166 OSErr err;
167 err = ::ThreadBeginCritical();
168
169 if (m_locked > 0)
170 m_locked--;
171
172 // this mutex is not owned by anybody anmore
173 m_internal->m_owner = kNoThreadID;
174
175 // now pass on to the first waiting thread
176 ThreadID firstWaiting = kNoThreadID;
177 bool found = false;
178 while (!m_internal->m_waiters.IsEmpty() && !found)
179 {
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);
184 if ( !found )
185 firstWaiting = kNoThreadID ;
186 m_internal->m_waiters.RemoveAt(0) ;
187 }
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);
191 }
192 else
193 {
194 if (m_locked > 0)
195 m_locked--;
196 }
197 return wxMUTEX_NO_ERROR;
198}
199
200// ----------------------------------------------------------------------------
201// wxCondition implementation
202// ----------------------------------------------------------------------------
203
204class wxConditionInternal
205{
206public:
207 wxConditionInternal(wxMutex& mutex) : m_mutex(mutex)
208 {
209 m_excessSignals = 0 ;
210 }
211 ~wxConditionInternal()
212 {
213 }
214
215 bool Wait(unsigned long msectimeout)
216 {
217 wxMacStCritical critical ;
218 if ( m_excessSignals > 0 )
219 {
220 --m_excessSignals ;
221 return TRUE ;
222 }
223 else if ( msectimeout == 0 )
224 {
225 return FALSE ;
226 }
227 else
228 {
229 }
230 /*
231 waiters++;
232
233 // FIXME this should be MsgWaitForMultipleObjects() as well probably
234 DWORD rc = ::WaitForSingleObject(event, timeout);
235
236 waiters--;
237
238 return rc != WAIT_TIMEOUT;
239 */
240 return TRUE ;
241 }
242 void Signal()
243 {
244 wxMacStCritical critical ;
245 }
246
247 wxArrayLong m_waiters ;
248 wxInt32 m_excessSignals ;
249 wxMutex& m_mutex;
250};
251
252wxCondition::wxCondition(wxMutex& mutex)
253{
254 m_internal = new wxConditionInternal(mutex);
255}
256
257wxCondition::~wxCondition()
258{
259 delete m_internal;
260}
261
262void wxCondition::Wait()
263{
264 (void)m_internal->Wait(0xFFFFFFFFL);
265}
266
267bool wxCondition::Wait(unsigned long timeout_millis)
268{
269 return m_internal->Wait(timeout_millis);
270}
271
272void wxCondition::Signal()
273{
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
278 // will be woken up.
279 m_internal->Signal() ;
280}
281
282void wxCondition::Broadcast()
283{
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++ )
288 {
289 Signal();
290 }
291}
292
293// ----------------------------------------------------------------------------
294// wxCriticalSection implementation
295// ----------------------------------------------------------------------------
296
297// it's implemented as a mutex on mac os, so it is defined in the headers
298
299// ----------------------------------------------------------------------------
300// wxThread implementation
301// ----------------------------------------------------------------------------
302
303// wxThreadInternal class
304// ----------------------
305
306class wxThreadInternal
307{
308public:
309 wxThreadInternal()
310 {
311 m_tid = kNoThreadID ;
312 m_state = STATE_NEW;
313 m_priority = WXTHREAD_DEFAULT_PRIORITY;
314 }
315
316 ~wxThreadInternal()
317 {
318 }
319
320 void Free()
321 {
322 }
323
324 // create a new (suspended) thread (for the given thread object)
325 bool Create(wxThread *thread, unsigned int stackSize);
326
327 // suspend/resume/terminate
328 bool Suspend();
329 bool Resume();
330 void Cancel() { m_state = STATE_CANCELED; }
331
332 // thread state
333 void SetState(wxThreadState state) { m_state = state; }
334 wxThreadState GetState() const { return m_state; }
335
336 // thread priority
337 void SetPriority(unsigned int priority);
338 unsigned int GetPriority() const { return m_priority; }
339
340 void SetResult( void *res ) { m_result = res ; }
341 void *GetResult() { return m_result ; }
342
343 // thread handle and id
344 ThreadID GetId() const { return m_tid; }
345
346 // thread function
347 static pascal void* MacThreadStart(wxThread* arg);
348
349private:
350 wxThreadState m_state; // state, see wxThreadState enum
351 unsigned int m_priority; // thread priority in "wx" units
352 ThreadID m_tid; // thread id
353 void* m_result;
354 static ThreadEntryUPP s_threadEntry ;
355};
356
357static wxArrayPtrVoid s_threads ;
358
359ThreadEntryUPP wxThreadInternal::s_threadEntry = NULL ;
360pascal void* wxThreadInternal::MacThreadStart(wxThread *thread)
361{
362 // first of all, check whether we hadn't been cancelled already
363 if ( thread->m_internal->GetState() == STATE_EXITED )
364 {
365 return (void*)-1;
366 }
367
368 void* rc = thread->Entry();
369
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();
375
376 thread->OnExit();
377
378 // if the thread was cancelled (from Delete()), then it the handle is still
379 // needed there
380 if ( thread->IsDetached() && !wasCancelled )
381 {
382 // auto delete
383 delete thread;
384 }
385 //else: the joinable threads handle will be closed when Wait() is done
386
387 return rc;
388}
389void wxThreadInternal::SetPriority(unsigned int priority)
390{
391 // Priorities don't exist on Mac
392}
393
394bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
395{
396 if ( s_threadEntry == NULL )
397 {
398 s_threadEntry = NewThreadEntryUPP( (ThreadEntryProcPtr) MacThreadStart ) ;
399 }
400 OSErr err = NewThread( kCooperativeThread,
401 s_threadEntry,
402 (void*) thread,
403 stackSize,
404 kNewSuspend,
405 &m_result,
406 &m_tid );
407
408 if ( err != noErr )
409 {
410 wxLogSysError(_("Can't create thread"));
411 return FALSE;
412 }
413
414 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
415 {
416 SetPriority(m_priority);
417 }
418
419 return TRUE;
420}
421
422bool wxThreadInternal::Suspend()
423{
424 OSErr err ;
425
426 ::ThreadBeginCritical();
427
428 if ( m_state != STATE_RUNNING )
429 {
430 ::ThreadEndCritical() ;
431 wxLogSysError(_("Can not suspend thread %x"), m_tid);
432 return FALSE;
433 }
434
435 m_state = STATE_PAUSED;
436
437 err = ::SetThreadStateEndCritical(m_tid, kStoppedThreadState, kNoThreadID);
438
439 return TRUE;
440}
441
442bool wxThreadInternal::Resume()
443{
444 ThreadID current ;
445 OSErr err ;
446 err = MacGetCurrentThread( &current ) ;
447
448 wxASSERT( err == noErr ) ;
449 wxASSERT( current != m_tid ) ;
450
451 ::ThreadBeginCritical();
452 if ( m_state != STATE_PAUSED && m_state != STATE_NEW )
453 {
454 ::ThreadEndCritical() ;
455 wxLogSysError(_("Can not resume thread %x"), m_tid);
456 return FALSE;
457
458 }
459 err = ::SetThreadStateEndCritical(m_tid, kReadyThreadState, kNoThreadID);
460 wxASSERT( err == noErr ) ;
461
462 m_state = STATE_RUNNING;
463 ::ThreadEndCritical() ;
464 ::YieldToAnyThread() ;
465 return TRUE;
466}
467
468// static functions
469// ----------------
470wxThread *wxThread::This()
471{
472 wxMacStCritical critical ;
473
474 ThreadID current ;
475 OSErr err ;
476
477 err = MacGetCurrentThread( &current ) ;
478
479 for ( size_t i = 0 ; i < s_threads.Count() ; ++i )
480 {
481 if ( ( (wxThread*) s_threads[i] )->GetId() == current )
482 return (wxThread*) s_threads[i] ;
483 }
484
485 wxLogSysError(_("Couldn't get the current thread pointer"));
486 return NULL;
487}
488
489bool wxThread::IsMain()
490{
491 ThreadID current ;
492 OSErr err ;
493
494 err = MacGetCurrentThread( &current ) ;
495 return current == gs_idMainThread;
496}
497
498#ifdef Yield
499#undef Yield
500#endif
501
502void wxThread::Yield()
503{
504 ::YieldToAnyThread() ;
505}
506
507void wxThread::Sleep(unsigned long milliseconds)
508{
509 clock_t start = clock() ;
510 do
511 {
512 YieldToAnyThread() ;
513 } while( clock() - start < milliseconds / CLOCKS_PER_SEC ) ;
514}
515
516int wxThread::GetCPUCount()
517{
518 // we will use whatever MP API will be used for the new MP Macs
519 return 1;
520}
521
522unsigned long wxThread::GetCurrentId()
523{
524 ThreadID current ;
525 MacGetCurrentThread( &current ) ;
526 return (unsigned long)current;
527}
528
529bool wxThread::SetConcurrency(size_t level)
530{
531 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
532
533 // ok only for the default one
534 if ( level == 0 )
535 return 0;
536
537 // how many CPUs have we got?
538 if ( GetCPUCount() == 1 )
539 {
540 // don't bother with all this complicated stuff - on a single
541 // processor system it doesn't make much sense anyhow
542 return level == 1;
543 }
544
545 return TRUE ;
546}
547
548// ctor and dtor
549// -------------
550
551wxThread::wxThread(wxThreadKind kind)
552{
553 m_internal = new wxThreadInternal();
554
555 m_isDetached = kind == wxTHREAD_DETACHED;
556 s_threads.Add( (void*) this ) ;
557}
558
559wxThread::~wxThread()
560{
561 s_threads.Remove( (void*) this ) ;
562 delete m_internal;
563}
564
565// create/start thread
566// -------------------
567
568wxThreadError wxThread::Create(unsigned int stackSize)
569{
570 wxCriticalSectionLocker lock(m_critsect);
571
572 if ( !m_internal->Create(this, stackSize) )
573 return wxTHREAD_NO_RESOURCE;
574
575 return wxTHREAD_NO_ERROR;
576}
577
578wxThreadError wxThread::Run()
579{
580 wxCriticalSectionLocker lock(m_critsect);
581
582 if ( m_internal->GetState() != STATE_NEW )
583 {
584 // actually, it may be almost any state at all, not only STATE_RUNNING
585 return wxTHREAD_RUNNING;
586 }
587
588 // the thread has just been created and is still suspended - let it run
589 return Resume();
590}
591
592// suspend/resume thread
593// ---------------------
594
595wxThreadError wxThread::Pause()
596{
597 wxCriticalSectionLocker lock(m_critsect);
598
599 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
600}
601
602wxThreadError wxThread::Resume()
603{
604 wxCriticalSectionLocker lock(m_critsect);
605
606 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
607}
608
609// stopping thread
610// ---------------
611
612wxThread::ExitCode wxThread::Wait()
613{
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") );
618
619 ExitCode rc = (ExitCode)-1;
620
621 (void)Delete(&rc);
622
623 m_internal->Free();
624
625 return rc;
626}
627
628wxThreadError wxThread::Delete(ExitCode *pRc)
629{
630 ExitCode rc = 0;
631
632 // Delete() is always safe to call, so consider all possible states
633
634 // has the thread started to run?
635 bool shouldResume = FALSE;
636
637 {
638 wxCriticalSectionLocker lock(m_critsect);
639
640 if ( m_internal->GetState() == STATE_NEW )
641 {
642 // WinThreadStart() will see it and terminate immediately
643 m_internal->SetState(STATE_EXITED);
644
645 shouldResume = TRUE;
646 }
647 }
648
649 // is the thread paused?
650 if ( shouldResume || IsPaused() )
651 Resume();
652
653 // does is still run?
654 if ( IsRunning() )
655 {
656 if ( IsMain() )
657 {
658 // set flag for wxIsWaitingForThread()
659 gs_waitingForThread = TRUE;
660
661#if wxUSE_GUI
662 wxBeginBusyCursor();
663#endif // wxUSE_GUI
664 }
665
666 // ask the thread to terminate
667 {
668 wxCriticalSectionLocker lock(m_critsect);
669
670 m_internal->Cancel();
671 }
672
673#if wxUSE_GUI
674 // simply wait for the thread to terminate
675 while( TestDestroy() )
676 {
677 ::YieldToAnyThread() ;
678 }
679#else // !wxUSE_GUI
680 // simply wait for the thread to terminate
681 while( TestDestroy() )
682 {
683 ::YieldToAnyThread() ;
684 }
685#endif // wxUSE_GUI/!wxUSE_GUI
686
687 if ( IsMain() )
688 {
689 gs_waitingForThread = FALSE;
690
691#if wxUSE_GUI
692 wxEndBusyCursor();
693#endif // wxUSE_GUI
694 }
695 }
696
697 // if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
698 {
699 wxLogLastError("GetExitCodeThread");
700
701 rc = (ExitCode)-1;
702 }
703
704 if ( IsDetached() )
705 {
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
710 delete this;
711 }
712
713 // wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
714 // wxT("thread must be already terminated.") );
715
716 if ( pRc )
717 *pRc = rc;
718
719 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
720}
721
722wxThreadError wxThread::Kill()
723{
724 if ( !IsRunning() )
725 return wxTHREAD_NOT_RUNNING;
726
727// if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
728 {
729 wxLogSysError(_("Couldn't terminate thread"));
730
731 return wxTHREAD_MISC_ERROR;
732 }
733
734 m_internal->Free();
735
736 if ( IsDetached() )
737 {
738 delete this;
739 }
740
741 return wxTHREAD_NO_ERROR;
742}
743
744void wxThread::Exit(ExitCode status)
745{
746 m_internal->Free();
747
748 if ( IsDetached() )
749 {
750 delete this;
751 }
752
753 m_internal->SetResult( status ) ;
754
755/*
756#if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
757 _endthreadex((unsigned)status);
758#else // !VC++
759 ::ExitThread((DWORD)status);
760#endif // VC++/!VC++
761*/
762 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
763}
764
765// priority setting
766// ----------------
767
768// since all these calls are execute cooperatively we don't have to use the critical section
769
770void wxThread::SetPriority(unsigned int prio)
771{
772 m_internal->SetPriority(prio);
773}
774
775unsigned int wxThread::GetPriority() const
776{
777 return m_internal->GetPriority();
778}
779
780unsigned long wxThread::GetId() const
781{
782 return (unsigned long)m_internal->GetId();
783}
784
785bool wxThread::IsRunning() const
786{
787 return m_internal->GetState() == STATE_RUNNING;
788}
789
790bool wxThread::IsAlive() const
791{
792 return (m_internal->GetState() == STATE_RUNNING) ||
793 (m_internal->GetState() == STATE_PAUSED);
794}
795
796bool wxThread::IsPaused() const
797{
798 return m_internal->GetState() == STATE_PAUSED;
799}
800
801bool wxThread::TestDestroy()
802{
803 return m_internal->GetState() == STATE_CANCELED;
804}
805
806// ----------------------------------------------------------------------------
807// Automatic initialization for thread module
808// ----------------------------------------------------------------------------
809
810class wxThreadModule : public wxModule
811{
812public:
813 virtual bool OnInit();
814 virtual void OnExit();
815
816private:
817 DECLARE_DYNAMIC_CLASS(wxThreadModule)
818};
819
820IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
821
822bool wxThreadModule::OnInit()
823{
824 long response;
825 bool hasThreadManager ;
826 hasThreadManager = Gestalt( gestaltThreadMgrAttr, &response) == noErr && response & 1;
827#if !TARGET_CARBON
828#if GENERATINGCFM
829 // verify presence of shared library
830 hasThreadManager = hasThreadManager && ((Ptr)NewThread != (Ptr)kUnresolvedCFragSymbolAddress);
831#endif
832#endif
833 if ( !hasThreadManager )
834 {
835 wxMessageBox( "Error" , "Thread Support is not available on this System" , wxOK ) ;
836 return FALSE ;
837 }
838
839 // no error return for GetCurrentThreadId()
840 MacGetCurrentThread( &gs_idMainThread ) ;
841
842 return TRUE;
843}
844
845void wxThreadModule::OnExit()
846{
847}
848
849// ----------------------------------------------------------------------------
850// under MacOS we don't have currently preemptive threads, so any thread may access
851// the GUI at any time
852// ----------------------------------------------------------------------------
853
854void WXDLLEXPORT wxMutexGuiEnter()
855{
856}
857
858void WXDLLEXPORT wxMutexGuiLeave()
859{
860}
861
862void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
863{
864}
865
866bool WXDLLEXPORT wxGuiOwnedByMainThread()
867{
868 return false ;
869}
870
871// wake up the main thread
872void WXDLLEXPORT wxWakeUpMainThread()
873{
874 wxMacWakeUp() ;
875}
876
877bool WXDLLEXPORT wxIsWaitingForThread()
878{
879 return false ;
880}
881
882#endif // wxUSE_THREADS
883
884// vi:sts=4:sw=4:et