]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/thread.cpp
patch from Dimitri fixing crashes when decoding the invalid GIFs
[wxWidgets.git] / src / mac / carbon / 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 #include "wx/mac/uma.h"
39 #endif
40
41 // ----------------------------------------------------------------------------
42 // constants
43 // ----------------------------------------------------------------------------
44
45 // the possible states of the thread ("=>" shows all possible transitions from
46 // this state)
47 enum wxThreadState
48 {
49 STATE_NEW, // didn't start execution yet (=> RUNNING)
50 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
51 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
52 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
53 STATE_EXITED // thread is terminating
54 };
55
56 // ----------------------------------------------------------------------------
57 // this module globals
58 // ----------------------------------------------------------------------------
59
60 static ThreadID gs_idMainThread = kNoThreadID ;
61 static bool gs_waitingForThread = FALSE ;
62
63 // ============================================================================
64 // MacOS implementation of thread classes
65 // ============================================================================
66
67 class wxMacStCritical
68 {
69 public :
70 wxMacStCritical()
71 {
72 if ( UMASystemIsInitialized() )
73 ThreadBeginCritical() ;
74 }
75 ~wxMacStCritical()
76 {
77 if ( UMASystemIsInitialized() )
78 ThreadEndCritical() ;
79 }
80 };
81
82 // ----------------------------------------------------------------------------
83 // wxMutex implementation
84 // ----------------------------------------------------------------------------
85
86 class wxMutexInternal
87 {
88 public:
89 wxMutexInternal()
90 {
91 m_owner = kNoThreadID ;
92 }
93
94 ~wxMutexInternal()
95 {
96 }
97
98 public:
99 ThreadID m_owner ;
100 wxArrayLong m_waiters ;
101 };
102
103 wxMutex::wxMutex()
104 {
105 m_internal = new wxMutexInternal;
106
107 m_locked = 0;
108 }
109
110 wxMutex::~wxMutex()
111 {
112 if ( m_locked > 0 )
113 {
114 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked);
115 }
116
117 delete m_internal;
118 }
119
120 wxMutexError wxMutex::Lock()
121 {
122 wxMacStCritical critical ;
123 if ( UMASystemIsInitialized() )
124 {
125 OSErr err ;
126 ThreadID current = kNoThreadID;
127 err = ::MacGetCurrentThread(&current);
128 // if we are not the owner, add this thread to the list of waiting threads, stop this thread
129 // and invoke the scheduler to continue executing the owner's thread
130 while ( m_internal->m_owner != kNoThreadID && m_internal->m_owner != current)
131 {
132 m_internal->m_waiters.Add(current);
133 err = ::SetThreadStateEndCritical(kCurrentThreadID, kStoppedThreadState, m_internal->m_owner);
134 err = ::ThreadBeginCritical();
135 }
136 m_internal->m_owner = current;
137 }
138 m_locked++;
139
140 return wxMUTEX_NO_ERROR;
141 }
142
143 wxMutexError wxMutex::TryLock()
144 {
145 wxMacStCritical critical ;
146 if ( UMASystemIsInitialized() )
147 {
148 OSErr err ;
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
162 wxMutexError 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
204 class wxConditionInternal
205 {
206 public:
207 wxConditionInternal()
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 };
250
251 wxCondition::wxCondition()
252 {
253 m_internal = new wxConditionInternal;
254 }
255
256 wxCondition::~wxCondition()
257 {
258 delete m_internal;
259 }
260
261 void wxCondition::Wait()
262 {
263 (void)m_internal->Wait(0xFFFFFFFFL);
264 }
265
266 bool wxCondition::Wait(unsigned long sec,
267 unsigned long nsec)
268 {
269 return m_internal->Wait(sec*1000 + nsec/1000000);
270 }
271
272 void 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
282 void 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 ( int 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
306 class wxThreadInternal
307 {
308 public:
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
349 private:
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
357 static wxArrayPtrVoid s_threads ;
358
359 ThreadEntryUPP wxThreadInternal::s_threadEntry = NULL ;
360 pascal 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 }
389 void wxThreadInternal::SetPriority(unsigned int priority)
390 {
391 // Priorities don't exist on Mac
392 }
393
394 bool 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
422 bool 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
442 bool 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 // ----------------
470 wxThread *wxThread::This()
471 {
472 wxMacStCritical critical ;
473
474 ThreadID current ;
475 OSErr err ;
476
477 err = MacGetCurrentThread( &current ) ;
478
479 for ( int 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
489 bool 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
502 void wxThread::Yield()
503 {
504 ::YieldToAnyThread() ;
505 }
506
507 void 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
516 int wxThread::GetCPUCount()
517 {
518 // we will use whatever MP API will be used for the new MP Macs
519 return 1;
520 }
521
522 bool wxThread::SetConcurrency(size_t level)
523 {
524 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
525
526 // ok only for the default one
527 if ( level == 0 )
528 return 0;
529
530 // how many CPUs have we got?
531 if ( GetCPUCount() == 1 )
532 {
533 // don't bother with all this complicated stuff - on a single
534 // processor system it doesn't make much sense anyhow
535 return level == 1;
536 }
537
538 return TRUE ;
539 }
540
541 // ctor and dtor
542 // -------------
543
544 wxThread::wxThread(wxThreadKind kind)
545 {
546 m_internal = new wxThreadInternal();
547
548 m_isDetached = kind == wxTHREAD_DETACHED;
549 s_threads.Add( (void*) this ) ;
550 }
551
552 wxThread::~wxThread()
553 {
554 s_threads.Remove( (void*) this ) ;
555 delete m_internal;
556 }
557
558 // create/start thread
559 // -------------------
560
561 wxThreadError wxThread::Create(unsigned int stackSize)
562 {
563 wxCriticalSectionLocker lock(m_critsect);
564
565 if ( !m_internal->Create(this, stackSize) )
566 return wxTHREAD_NO_RESOURCE;
567
568 return wxTHREAD_NO_ERROR;
569 }
570
571 wxThreadError wxThread::Run()
572 {
573 wxCriticalSectionLocker lock(m_critsect);
574
575 if ( m_internal->GetState() != STATE_NEW )
576 {
577 // actually, it may be almost any state at all, not only STATE_RUNNING
578 return wxTHREAD_RUNNING;
579 }
580
581 // the thread has just been created and is still suspended - let it run
582 return Resume();
583 }
584
585 // suspend/resume thread
586 // ---------------------
587
588 wxThreadError wxThread::Pause()
589 {
590 wxCriticalSectionLocker lock(m_critsect);
591
592 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
593 }
594
595 wxThreadError wxThread::Resume()
596 {
597 wxCriticalSectionLocker lock(m_critsect);
598
599 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
600 }
601
602 // stopping thread
603 // ---------------
604
605 wxThread::ExitCode wxThread::Wait()
606 {
607 // although under MacOS we can wait for any thread, it's an error to
608 // wait for a detached one in wxWin API
609 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
610 _T("can't wait for detached thread") );
611
612 ExitCode rc = (ExitCode)-1;
613
614 (void)Delete(&rc);
615
616 m_internal->Free();
617
618 return rc;
619 }
620
621 wxThreadError wxThread::Delete(ExitCode *pRc)
622 {
623 ExitCode rc = 0;
624
625 // Delete() is always safe to call, so consider all possible states
626
627 // has the thread started to run?
628 bool shouldResume = FALSE;
629
630 {
631 wxCriticalSectionLocker lock(m_critsect);
632
633 if ( m_internal->GetState() == STATE_NEW )
634 {
635 // WinThreadStart() will see it and terminate immediately
636 m_internal->SetState(STATE_EXITED);
637
638 shouldResume = TRUE;
639 }
640 }
641
642 // is the thread paused?
643 if ( shouldResume || IsPaused() )
644 Resume();
645
646 // does is still run?
647 if ( IsRunning() )
648 {
649 if ( IsMain() )
650 {
651 // set flag for wxIsWaitingForThread()
652 gs_waitingForThread = TRUE;
653
654 #if wxUSE_GUI
655 wxBeginBusyCursor();
656 #endif // wxUSE_GUI
657 }
658
659 // ask the thread to terminate
660 {
661 wxCriticalSectionLocker lock(m_critsect);
662
663 m_internal->Cancel();
664 }
665
666 #if wxUSE_GUI
667 // simply wait for the thread to terminate
668 while( TestDestroy() )
669 {
670 ::YieldToAnyThread() ;
671 }
672 #else // !wxUSE_GUI
673 // simply wait for the thread to terminate
674 while( TestDestroy() )
675 {
676 ::YieldToAnyThread() ;
677 }
678 #endif // wxUSE_GUI/!wxUSE_GUI
679
680 if ( IsMain() )
681 {
682 gs_waitingForThread = FALSE;
683
684 #if wxUSE_GUI
685 wxEndBusyCursor();
686 #endif // wxUSE_GUI
687 }
688 }
689
690 // if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
691 {
692 wxLogLastError("GetExitCodeThread");
693
694 rc = (ExitCode)-1;
695 }
696
697 if ( IsDetached() )
698 {
699 // if the thread exits normally, this is done in WinThreadStart, but in
700 // this case it would have been too early because
701 // MsgWaitForMultipleObject() would fail if the therad handle was
702 // closed while we were waiting on it, so we must do it here
703 delete this;
704 }
705
706 // wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
707 // wxT("thread must be already terminated.") );
708
709 if ( pRc )
710 *pRc = rc;
711
712 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
713 }
714
715 wxThreadError wxThread::Kill()
716 {
717 if ( !IsRunning() )
718 return wxTHREAD_NOT_RUNNING;
719
720 // if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
721 {
722 wxLogSysError(_("Couldn't terminate thread"));
723
724 return wxTHREAD_MISC_ERROR;
725 }
726
727 m_internal->Free();
728
729 if ( IsDetached() )
730 {
731 delete this;
732 }
733
734 return wxTHREAD_NO_ERROR;
735 }
736
737 void wxThread::Exit(ExitCode status)
738 {
739 m_internal->Free();
740
741 if ( IsDetached() )
742 {
743 delete this;
744 }
745
746 m_internal->SetResult( status ) ;
747
748 /*
749 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
750 _endthreadex((unsigned)status);
751 #else // !VC++
752 ::ExitThread((DWORD)status);
753 #endif // VC++/!VC++
754 */
755 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
756 }
757
758 // priority setting
759 // ----------------
760
761 // since all these calls are execute cooperatively we don't have to use the critical section
762
763 void wxThread::SetPriority(unsigned int prio)
764 {
765 m_internal->SetPriority(prio);
766 }
767
768 unsigned int wxThread::GetPriority() const
769 {
770 return m_internal->GetPriority();
771 }
772
773 unsigned long wxThread::GetId() const
774 {
775 return (unsigned long)m_internal->GetId();
776 }
777
778 bool wxThread::IsRunning() const
779 {
780 return m_internal->GetState() == STATE_RUNNING;
781 }
782
783 bool wxThread::IsAlive() const
784 {
785 return (m_internal->GetState() == STATE_RUNNING) ||
786 (m_internal->GetState() == STATE_PAUSED);
787 }
788
789 bool wxThread::IsPaused() const
790 {
791 return m_internal->GetState() == STATE_PAUSED;
792 }
793
794 bool wxThread::TestDestroy()
795 {
796 return m_internal->GetState() == STATE_CANCELED;
797 }
798
799 // ----------------------------------------------------------------------------
800 // Automatic initialization for thread module
801 // ----------------------------------------------------------------------------
802
803 class wxThreadModule : public wxModule
804 {
805 public:
806 virtual bool OnInit();
807 virtual void OnExit();
808
809 private:
810 DECLARE_DYNAMIC_CLASS(wxThreadModule)
811 };
812
813 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
814
815 bool wxThreadModule::OnInit()
816 {
817 long response;
818 bool hasThreadManager ;
819 hasThreadManager = Gestalt( gestaltThreadMgrAttr, &response) == noErr && response & 1;
820 #if !TARGET_CARBON
821 #if GENERATINGCFM
822 // verify presence of shared library
823 hasThreadManager = hasThreadManager && ((Ptr)NewThread != (Ptr)kUnresolvedCFragSymbolAddress);
824 #endif
825 #endif
826 if ( !hasThreadManager )
827 {
828 wxMessageBox( "Error" , "Thread Support is not available on this System" , wxOK ) ;
829 return FALSE ;
830 }
831
832 // no error return for GetCurrentThreadId()
833 MacGetCurrentThread( &gs_idMainThread ) ;
834
835 return TRUE;
836 }
837
838 void wxThreadModule::OnExit()
839 {
840 }
841
842 // ----------------------------------------------------------------------------
843 // under MacOS we don't have currently preemptive threads, so any thread may access
844 // the GUI at any time
845 // ----------------------------------------------------------------------------
846
847 void WXDLLEXPORT wxMutexGuiEnter()
848 {
849 }
850
851 void WXDLLEXPORT wxMutexGuiLeave()
852 {
853 }
854
855 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
856 {
857 }
858
859 bool WXDLLEXPORT wxGuiOwnedByMainThread()
860 {
861 return false ;
862 }
863
864 // wake up the main thread
865 void WXDLLEXPORT wxWakeUpMainThread()
866 {
867 wxMacWakeUp() ;
868 }
869
870 bool WXDLLEXPORT wxIsWaitingForThread()
871 {
872 return false ;
873 }
874
875 #endif // wxUSE_THREADS
876
877 // vi:sts=4:sw=4:et