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