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