]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/mac/carbon/thread.cpp
fix a crash when dismissing the popup window because of a key press
[wxWidgets.git] / src / mac / carbon / 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#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)
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()
93 {
94 m_owner = kNoThreadID ;
95 }
96
97 ~wxMutexInternal()
98 {
99 }
100
101public:
102 ThreadID m_owner ;
103 wxArrayLong m_waiters ;
104};
105
106wxMutex::wxMutex()
107{
108 m_internal = new wxMutexInternal;
109
110 m_locked = 0;
111}
112
113wxMutex::~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
123wxMutexError 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
146wxMutexError 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
165wxMutexError 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
207class wxConditionInternal
208{
209public:
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
254wxCondition::wxCondition()
255{
256 m_internal = new wxConditionInternal;
257}
258
259wxCondition::~wxCondition()
260{
261 delete m_internal;
262}
263
264void wxCondition::Wait()
265{
266 (void)m_internal->Wait(0xFFFFFFFFL);
267}
268
269bool wxCondition::Wait(unsigned long sec,
270 unsigned long nsec)
271{
272 return m_internal->Wait(sec*1000 + nsec/1000000);
273}
274
275void 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
285void 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
309class wxThreadInternal
310{
311public:
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
352private:
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
360static wxArrayPtrVoid s_threads ;
361
362ThreadEntryUPP wxThreadInternal::s_threadEntry = NULL ;
363pascal 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}
392void wxThreadInternal::SetPriority(unsigned int priority)
393{
394 // Priorities don't exist on Mac
395}
396
397bool 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
425bool 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
445bool 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// ----------------
473wxThread *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
492bool 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
505void wxThread::Yield()
506{
507 ::YieldToAnyThread() ;
508}
509
510void 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
519int wxThread::GetCPUCount()
520{
521 // we will use whatever MP API will be used for the new MP Macs
522 return 1;
523}
524
525unsigned long wxThread::GetCurrentId()
526{
527 ThreadID current ;
528 MacGetCurrentThread( &current ) ;
529 return (unsigned long)current;
530}
531
532bool wxThread::SetConcurrency(size_t level)
533{
534 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
535
536 // ok only for the default one
537 if ( level == 0 )
538 return 0;
539
540 // how many CPUs have we got?
541 if ( GetCPUCount() == 1 )
542 {
543 // don't bother with all this complicated stuff - on a single
544 // processor system it doesn't make much sense anyhow
545 return level == 1;
546 }
547
548 return TRUE ;
549}
550
551// ctor and dtor
552// -------------
553
554wxThread::wxThread(wxThreadKind kind)
555{
556 m_internal = new wxThreadInternal();
557
558 m_isDetached = kind == wxTHREAD_DETACHED;
559 s_threads.Add( (void*) this ) ;
560}
561
562wxThread::~wxThread()
563{
564 s_threads.Remove( (void*) this ) ;
565 delete m_internal;
566}
567
568// create/start thread
569// -------------------
570
571wxThreadError wxThread::Create(unsigned int stackSize)
572{
573 wxCriticalSectionLocker lock(m_critsect);
574
575 if ( !m_internal->Create(this, stackSize) )
576 return wxTHREAD_NO_RESOURCE;
577
578 return wxTHREAD_NO_ERROR;
579}
580
581wxThreadError wxThread::Run()
582{
583 wxCriticalSectionLocker lock(m_critsect);
584
585 if ( m_internal->GetState() != STATE_NEW )
586 {
587 // actually, it may be almost any state at all, not only STATE_RUNNING
588 return wxTHREAD_RUNNING;
589 }
590
591 // the thread has just been created and is still suspended - let it run
592 return Resume();
593}
594
595// suspend/resume thread
596// ---------------------
597
598wxThreadError wxThread::Pause()
599{
600 wxCriticalSectionLocker lock(m_critsect);
601
602 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
603}
604
605wxThreadError wxThread::Resume()
606{
607 wxCriticalSectionLocker lock(m_critsect);
608
609 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
610}
611
612// stopping thread
613// ---------------
614
615wxThread::ExitCode wxThread::Wait()
616{
617 // although under MacOS we can wait for any thread, it's an error to
618 // wait for a detached one in wxWin API
619 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
620 _T("can't wait for detached thread") );
621
622 ExitCode rc = (ExitCode)-1;
623
624 (void)Delete(&rc);
625
626 m_internal->Free();
627
628 return rc;
629}
630
631wxThreadError wxThread::Delete(ExitCode *pRc)
632{
633 ExitCode rc = 0;
634
635 // Delete() is always safe to call, so consider all possible states
636
637 // has the thread started to run?
638 bool shouldResume = FALSE;
639
640 {
641 wxCriticalSectionLocker lock(m_critsect);
642
643 if ( m_internal->GetState() == STATE_NEW )
644 {
645 // WinThreadStart() will see it and terminate immediately
646 m_internal->SetState(STATE_EXITED);
647
648 shouldResume = TRUE;
649 }
650 }
651
652 // is the thread paused?
653 if ( shouldResume || IsPaused() )
654 Resume();
655
656 // does is still run?
657 if ( IsRunning() )
658 {
659 if ( IsMain() )
660 {
661 // set flag for wxIsWaitingForThread()
662 gs_waitingForThread = TRUE;
663
664#if wxUSE_GUI
665 wxBeginBusyCursor();
666#endif // wxUSE_GUI
667 }
668
669 // ask the thread to terminate
670 {
671 wxCriticalSectionLocker lock(m_critsect);
672
673 m_internal->Cancel();
674 }
675
676#if wxUSE_GUI
677 // simply wait for the thread to terminate
678 while( TestDestroy() )
679 {
680 ::YieldToAnyThread() ;
681 }
682#else // !wxUSE_GUI
683 // simply wait for the thread to terminate
684 while( TestDestroy() )
685 {
686 ::YieldToAnyThread() ;
687 }
688#endif // wxUSE_GUI/!wxUSE_GUI
689
690 if ( IsMain() )
691 {
692 gs_waitingForThread = FALSE;
693
694#if wxUSE_GUI
695 wxEndBusyCursor();
696#endif // wxUSE_GUI
697 }
698 }
699
700 // if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
701 {
702 wxLogLastError("GetExitCodeThread");
703
704 rc = (ExitCode)-1;
705 }
706
707 if ( IsDetached() )
708 {
709 // if the thread exits normally, this is done in WinThreadStart, but in
710 // this case it would have been too early because
711 // MsgWaitForMultipleObject() would fail if the therad handle was
712 // closed while we were waiting on it, so we must do it here
713 delete this;
714 }
715
716 // wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
717 // wxT("thread must be already terminated.") );
718
719 if ( pRc )
720 *pRc = rc;
721
722 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
723}
724
725wxThreadError wxThread::Kill()
726{
727 if ( !IsRunning() )
728 return wxTHREAD_NOT_RUNNING;
729
730// if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
731 {
732 wxLogSysError(_("Couldn't terminate thread"));
733
734 return wxTHREAD_MISC_ERROR;
735 }
736
737 m_internal->Free();
738
739 if ( IsDetached() )
740 {
741 delete this;
742 }
743
744 return wxTHREAD_NO_ERROR;
745}
746
747void wxThread::Exit(ExitCode status)
748{
749 m_internal->Free();
750
751 if ( IsDetached() )
752 {
753 delete this;
754 }
755
756 m_internal->SetResult( status ) ;
757
758/*
759#if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
760 _endthreadex((unsigned)status);
761#else // !VC++
762 ::ExitThread((DWORD)status);
763#endif // VC++/!VC++
764*/
765 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
766}
767
768// priority setting
769// ----------------
770
771// since all these calls are execute cooperatively we don't have to use the critical section
772
773void wxThread::SetPriority(unsigned int prio)
774{
775 m_internal->SetPriority(prio);
776}
777
778unsigned int wxThread::GetPriority() const
779{
780 return m_internal->GetPriority();
781}
782
783unsigned long wxThread::GetId() const
784{
785 return (unsigned long)m_internal->GetId();
786}
787
788bool wxThread::IsRunning() const
789{
790 return m_internal->GetState() == STATE_RUNNING;
791}
792
793bool wxThread::IsAlive() const
794{
795 return (m_internal->GetState() == STATE_RUNNING) ||
796 (m_internal->GetState() == STATE_PAUSED);
797}
798
799bool wxThread::IsPaused() const
800{
801 return m_internal->GetState() == STATE_PAUSED;
802}
803
804bool wxThread::TestDestroy()
805{
806 return m_internal->GetState() == STATE_CANCELED;
807}
808
809// ----------------------------------------------------------------------------
810// Automatic initialization for thread module
811// ----------------------------------------------------------------------------
812
813class wxThreadModule : public wxModule
814{
815public:
816 virtual bool OnInit();
817 virtual void OnExit();
818
819private:
820 DECLARE_DYNAMIC_CLASS(wxThreadModule)
821};
822
823IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
824
825bool wxThreadModule::OnInit()
826{
827 long response;
828 bool hasThreadManager ;
829 hasThreadManager = Gestalt( gestaltThreadMgrAttr, &response) == noErr && response & 1;
830#if !TARGET_CARBON
831#if GENERATINGCFM
832 // verify presence of shared library
833 hasThreadManager = hasThreadManager && ((Ptr)NewThread != (Ptr)kUnresolvedCFragSymbolAddress);
834#endif
835#endif
836 if ( !hasThreadManager )
837 {
838 wxMessageBox( "Error" , "Thread Support is not available on this System" , wxOK ) ;
839 return FALSE ;
840 }
841
842 // no error return for GetCurrentThreadId()
843 MacGetCurrentThread( &gs_idMainThread ) ;
844
845 return TRUE;
846}
847
848void wxThreadModule::OnExit()
849{
850}
851
852// ----------------------------------------------------------------------------
853// under MacOS we don't have currently preemptive threads, so any thread may access
854// the GUI at any time
855// ----------------------------------------------------------------------------
856
857void WXDLLEXPORT wxMutexGuiEnter()
858{
859}
860
861void WXDLLEXPORT wxMutexGuiLeave()
862{
863}
864
865void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
866{
867}
868
869bool WXDLLEXPORT wxGuiOwnedByMainThread()
870{
871 return false ;
872}
873
874// wake up the main thread
875void WXDLLEXPORT wxWakeUpMainThread()
876{
877 wxMacWakeUp() ;
878}
879
880bool WXDLLEXPORT wxIsWaitingForThread()
881{
882 return false ;
883}
884
885#endif // wxUSE_THREADS
886
887// vi:sts=4:sw=4:et