Added wxThread::GetMainId().
[wxWidgets.git] / src / os2 / thread.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/os2/thread.cpp
3 // Purpose: wxThread Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux/David Webster
5 // Modified by: Stefan Neis
6 // Created: 04/22/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Stefan Neis (2003)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ----------------------------------------------------------------------------
13 // headers
14 // ----------------------------------------------------------------------------
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #if wxUSE_THREADS
20
21 #include "wx/thread.h"
22
23 #ifndef WX_PRECOMP
24 #include "wx/intl.h"
25 #include "wx/log.h"
26 #include "wx/app.h"
27 #include "wx/module.h"
28 #endif //WX_PRECOMP
29
30 #include "wx/apptrait.h"
31 #include "wx/utils.h"
32
33 #include <stdio.h>
34
35 #define INCL_DOSSEMAPHORES
36 #define INCL_DOSPROCESS
37 #define INCL_DOSMISC
38 #define INCL_ERRORS
39 #include <os2.h>
40 #ifndef __EMX__
41 #include <bseerr.h>
42 #endif
43 // the possible states of the thread ("=>" shows all possible transitions from
44 // this state)
45 enum wxThreadState
46 {
47 STATE_NEW, // didn't start execution yet (=> RUNNING)
48 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
49 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
50 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
51 STATE_EXITED // thread is terminating
52 };
53
54 // ----------------------------------------------------------------------------
55 // this module's globals
56 // ----------------------------------------------------------------------------
57
58 // id of the main thread - the one which can call GUI functions without first
59 // calling wxMutexGuiEnter()
60 wxThreadIdType wxThread::ms_idMainThread = 0;
61 wxMutex* p_wxMainMutex;
62
63 // OS2 substitute for Tls pointer the current parent thread object
64 wxThread* m_pThread; // pointer to the wxWidgets thread object
65
66 // if it's false, some secondary thread is holding the GUI lock
67 static bool gs_bGuiOwnedByMainThread = true;
68
69 // critical section which controls access to all GUI functions: any secondary
70 // thread (i.e. except the main one) must enter this crit section before doing
71 // any GUI calls
72 static wxCriticalSection *gs_pCritsectGui = NULL;
73
74 // critical section which protects s_nWaitingForGui variable
75 static wxCriticalSection *gs_pCritsectWaitingForGui = NULL;
76
77 // number of threads waiting for GUI in wxMutexGuiEnter()
78 static size_t gs_nWaitingForGui = 0;
79
80 // are we waiting for a thread termination?
81 static bool gs_bWaitingForThread = false;
82
83 // ============================================================================
84 // OS/2 implementation of thread and related classes
85 // ============================================================================
86
87 // ----------------------------------------------------------------------------
88 // wxMutex implementation
89 // ----------------------------------------------------------------------------
90 class wxMutexInternal
91 {
92 public:
93 wxMutexInternal(wxMutexType mutexType);
94 ~wxMutexInternal();
95
96 bool IsOk() const { return m_vMutex != NULL; }
97
98 wxMutexError Lock() { return LockTimeout(SEM_INDEFINITE_WAIT); }
99 wxMutexError Lock(unsigned long ms) { return LockTimeout(ms); }
100 wxMutexError TryLock();
101 wxMutexError Unlock();
102
103 private:
104 wxMutexError LockTimeout(ULONG ulMilliseconds);
105 HMTX m_vMutex;
106 };
107
108 // all mutexes are "pseudo-"recursive under OS2 so we don't use mutexType
109 // (Calls to DosRequestMutexSem and DosReleaseMutexSem can be nested, but
110 // the request count for a semaphore cannot exceed 65535. If an attempt is
111 // made to exceed this number, ERROR_TOO_MANY_SEM_REQUESTS is returned.)
112 wxMutexInternal::wxMutexInternal(wxMutexType WXUNUSED(eMutexType))
113 {
114 APIRET ulrc = ::DosCreateMutexSem(NULL, &m_vMutex, 0L, FALSE);
115 if (ulrc != 0)
116 {
117 wxLogSysError(_("Can not create mutex."));
118 m_vMutex = NULL;
119 }
120 }
121
122 wxMutexInternal::~wxMutexInternal()
123 {
124 if (m_vMutex)
125 {
126 if (::DosCloseMutexSem(m_vMutex))
127 wxLogLastError(_T("DosCloseMutexSem(mutex)"));
128 }
129 }
130
131 wxMutexError wxMutexInternal::TryLock()
132 {
133 const wxMutexError rc = LockTimeout( SEM_IMMEDIATE_RETURN );
134
135 // we have a special return code for timeout in this case
136 return rc == wxMUTEX_TIMEOUT ? wxMUTEX_BUSY : rc;
137 }
138
139 wxMutexError wxMutexInternal::LockTimeout(ULONG ulMilliseconds)
140 {
141 APIRET ulrc;
142
143 ulrc = ::DosRequestMutexSem(m_vMutex, ulMilliseconds);
144
145 switch (ulrc)
146 {
147 case ERROR_TIMEOUT:
148 return wxMUTEX_TIMEOUT;
149 case ERROR_TOO_MANY_SEM_REQUESTS:
150 return wxMUTEX_BUSY;
151
152 case NO_ERROR:
153 // ok
154 break;
155
156 case ERROR_INVALID_HANDLE:
157 case ERROR_INTERRUPT:
158 case ERROR_SEM_OWNER_DIED:
159 wxLogSysError(_("Couldn't acquire a mutex lock"));
160 return wxMUTEX_MISC_ERROR;
161
162 default:
163 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
164 return wxMUTEX_MISC_ERROR;
165 }
166 return wxMUTEX_NO_ERROR;
167 }
168
169 wxMutexError wxMutexInternal::Unlock()
170 {
171 APIRET ulrc;
172
173 ulrc = ::DosReleaseMutexSem(m_vMutex);
174 if (ulrc != 0)
175 {
176 wxLogSysError(_("Couldn't release a mutex"));
177 return wxMUTEX_MISC_ERROR;
178 }
179 return wxMUTEX_NO_ERROR;
180 }
181
182 // --------------------------------------------------------------------------
183 // wxSemaphore
184 // --------------------------------------------------------------------------
185
186 // a trivial wrapper around OS2 event semaphore
187 class wxSemaphoreInternal
188 {
189 public:
190 wxSemaphoreInternal(int initialcount, int maxcount);
191 ~wxSemaphoreInternal();
192
193 bool IsOk() const { return m_vEvent != NULL; }
194
195 wxSemaError Wait() { return WaitTimeout(SEM_INDEFINITE_WAIT); }
196 wxSemaError TryWait() { return WaitTimeout(SEM_IMMEDIATE_RETURN); }
197 wxSemaError WaitTimeout(unsigned long milliseconds);
198
199 wxSemaError Post();
200
201 private:
202 HEV m_vEvent;
203 HMTX m_vMutex;
204 int m_count;
205 int m_maxcount;
206 };
207
208 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
209 {
210 APIRET ulrc;
211 if ( maxcount == 0 )
212 {
213 // make it practically infinite
214 maxcount = INT_MAX;
215 }
216
217 m_count = initialcount;
218 m_maxcount = maxcount;
219 ulrc = ::DosCreateMutexSem(NULL, &m_vMutex, 0L, FALSE);
220 if (ulrc != 0)
221 {
222 wxLogLastError(_T("DosCreateMutexSem()"));
223 m_vMutex = NULL;
224 m_vEvent = NULL;
225 return;
226 }
227 ulrc = ::DosCreateEventSem(NULL, &m_vEvent, 0L, FALSE);
228 if ( ulrc != 0)
229 {
230 wxLogLastError(_T("DosCreateEventSem()"));
231 ::DosCloseMutexSem(m_vMutex);
232 m_vMutex = NULL;
233 m_vEvent = NULL;
234 }
235 if (initialcount)
236 ::DosPostEventSem(m_vEvent);
237 }
238
239 wxSemaphoreInternal::~wxSemaphoreInternal()
240 {
241 if ( m_vEvent )
242 {
243 if ( ::DosCloseEventSem(m_vEvent) )
244 {
245 wxLogLastError(_T("DosCloseEventSem(semaphore)"));
246 }
247 if ( ::DosCloseMutexSem(m_vMutex) )
248 {
249 wxLogLastError(_T("DosCloseMutexSem(semaphore)"));
250 }
251 else
252 m_vEvent = NULL;
253 }
254 }
255
256 wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long ulMilliseconds)
257 {
258 APIRET ulrc;
259 do {
260 ulrc = ::DosWaitEventSem(m_vEvent, ulMilliseconds );
261 switch ( ulrc )
262 {
263 case NO_ERROR:
264 break;
265
266 case ERROR_TIMEOUT:
267 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
268 return wxSEMA_BUSY;
269 else
270 return wxSEMA_TIMEOUT;
271
272 default:
273 wxLogLastError(_T("DosWaitEventSem(semaphore)"));
274 return wxSEMA_MISC_ERROR;
275 }
276 ulrc = :: DosRequestMutexSem(m_vMutex, ulMilliseconds);
277 switch ( ulrc )
278 {
279 case NO_ERROR:
280 // ok
281 break;
282
283 case ERROR_TIMEOUT:
284 case ERROR_TOO_MANY_SEM_REQUESTS:
285 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
286 return wxSEMA_BUSY;
287 else
288 return wxSEMA_TIMEOUT;
289
290 default:
291 wxFAIL_MSG(wxT("DosRequestMutexSem(mutex)"));
292 return wxSEMA_MISC_ERROR;
293 }
294 bool OK = false;
295 if (m_count > 0)
296 {
297 m_count--;
298 OK = true;
299 }
300 else
301 {
302 ULONG ulPostCount;
303 ::DosResetEventSem(m_vEvent, &ulPostCount);
304 }
305 ::DosReleaseMutexSem(m_vMutex);
306 if (OK)
307 return wxSEMA_NO_ERROR;
308 } while (ulMilliseconds == SEM_INDEFINITE_WAIT);
309
310 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
311 return wxSEMA_BUSY;
312 return wxSEMA_TIMEOUT;
313 }
314
315 wxSemaError wxSemaphoreInternal::Post()
316 {
317 APIRET ulrc;
318 ulrc = ::DosRequestMutexSem(m_vMutex, SEM_INDEFINITE_WAIT);
319 if (ulrc != NO_ERROR)
320 return wxSEMA_MISC_ERROR;
321 bool OK = false;
322 if (m_count < m_maxcount)
323 {
324 m_count++;
325 ulrc = ::DosPostEventSem(m_vEvent);
326 OK = true;
327 }
328 ::DosReleaseMutexSem(m_vMutex);
329 if (!OK)
330 return wxSEMA_OVERFLOW;
331 if ( ulrc != NO_ERROR && ulrc != ERROR_ALREADY_POSTED )
332 {
333 wxLogLastError(_T("DosPostEventSem(semaphore)"));
334
335 return wxSEMA_MISC_ERROR;
336 }
337
338 return wxSEMA_NO_ERROR;
339 }
340
341 // ----------------------------------------------------------------------------
342 // wxThread implementation
343 // ----------------------------------------------------------------------------
344
345 // wxThreadInternal class
346 // ----------------------
347
348 class wxThreadInternal
349 {
350 public:
351 inline wxThreadInternal()
352 {
353 m_hThread = 0;
354 m_eState = STATE_NEW;
355 m_nPriority = WXTHREAD_DEFAULT_PRIORITY;
356 }
357
358 ~wxThreadInternal()
359 {
360 m_hThread = 0;
361 }
362
363 // create a new (suspended) thread (for the given thread object)
364 bool Create( wxThread* pThread
365 ,unsigned int uStackSize
366 );
367
368 // suspend/resume/terminate
369 bool Suspend();
370 bool Resume();
371 inline void Cancel() { m_eState = STATE_CANCELED; }
372
373 // thread state
374 inline void SetState(wxThreadState eState) { m_eState = eState; }
375 inline wxThreadState GetState() const { return m_eState; }
376
377 // thread priority
378 void SetPriority(unsigned int nPriority);
379 inline unsigned int GetPriority() const { return m_nPriority; }
380
381 // thread handle and id
382 inline TID GetHandle() const { return m_hThread; }
383 TID GetId() const { return m_hThread; }
384
385 // thread function
386 static void OS2ThreadStart(void* pParam);
387
388 private:
389 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
390 // PM also has no real Tls mechanism to index pointers by so we'll just
391 // keep track of the wxWidgets parent object here.
392 TID m_hThread; // handle and ID of the thread
393 wxThreadState m_eState; // state, see wxThreadState enum
394 unsigned int m_nPriority; // thread priority in "wx" units
395 };
396
397 void wxThreadInternal::OS2ThreadStart( void * pParam )
398 {
399 DWORD dwRet;
400 bool bWasCancelled;
401
402 wxThread *pThread = (wxThread *)pParam;
403
404 // first of all, wait for the thread to be started.
405 pThread->m_critsect.Enter();
406 pThread->m_critsect.Leave();
407 // Now check whether we hadn't been cancelled already and don't
408 // start the user code at all in this case.
409 if ( pThread->m_internal->GetState() == STATE_EXITED )
410 {
411 dwRet = (DWORD)-1;
412 bWasCancelled = true;
413 }
414 else // do run thread
415 {
416 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
417 unsigned long ulHab;
418 if (traits)
419 traits->InitializeGui(ulHab);
420 dwRet = (DWORD)pThread->Entry();
421 if (traits)
422 traits->TerminateGui(ulHab);
423
424 // enter m_critsect before changing the thread state
425 pThread->m_critsect.Enter();
426
427 bWasCancelled = pThread->m_internal->GetState() == STATE_CANCELED;
428
429 pThread->m_internal->SetState(STATE_EXITED);
430 pThread->m_critsect.Leave();
431 }
432 pThread->OnExit();
433
434 // if the thread was cancelled (from Delete()), then it the handle is still
435 // needed there
436 if (pThread->IsDetached() && !bWasCancelled)
437 {
438 // auto delete
439 delete pThread;
440 }
441 //else: the joinable threads handle will be closed when Wait() is done
442 return;
443 }
444
445 void wxThreadInternal::SetPriority(
446 unsigned int nPriority
447 )
448 {
449 // translate wxWidgets priority to the PM one
450 ULONG ulOS2_PriorityClass;
451 ULONG ulOS2_SubPriority;
452 ULONG ulrc;
453
454 m_nPriority = nPriority;
455 if (m_nPriority <= 25)
456 ulOS2_PriorityClass = PRTYC_IDLETIME;
457 else if (m_nPriority <= 50)
458 ulOS2_PriorityClass = PRTYC_REGULAR;
459 else if (m_nPriority <= 75)
460 ulOS2_PriorityClass = PRTYC_TIMECRITICAL;
461 else if (m_nPriority <= 100)
462 ulOS2_PriorityClass = PRTYC_FOREGROUNDSERVER;
463 else
464 {
465 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
466 ulOS2_PriorityClass = PRTYC_REGULAR;
467 }
468 ulOS2_SubPriority = (ULONG) (((m_nPriority - 1) % 25 + 1) * 31.0 / 25);
469 ulrc = ::DosSetPriority( PRTYS_THREAD
470 ,ulOS2_PriorityClass
471 ,ulOS2_SubPriority
472 ,(ULONG)m_hThread
473 );
474 if (ulrc != 0)
475 {
476 wxLogSysError(_("Can't set thread priority"));
477 }
478 }
479
480 bool wxThreadInternal::Create( wxThread* pThread,
481 unsigned int uStackSize)
482 {
483 int tid;
484
485 if (!uStackSize)
486 uStackSize = 131072;
487
488 pThread->m_critsect.Enter();
489 tid = _beginthread(wxThreadInternal::OS2ThreadStart,
490 NULL, uStackSize, pThread);
491 if(tid == -1)
492 {
493 wxLogSysError(_("Can't create thread"));
494
495 return false;
496 }
497 m_hThread = tid;
498 if (m_nPriority != WXTHREAD_DEFAULT_PRIORITY)
499 {
500 SetPriority(m_nPriority);
501 }
502
503 return true;
504 }
505
506 bool wxThreadInternal::Suspend()
507 {
508 ULONG ulrc = ::DosSuspendThread(m_hThread);
509
510 if (ulrc != 0)
511 {
512 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
513 return false;
514 }
515 m_eState = STATE_PAUSED;
516
517 return true;
518 }
519
520 bool wxThreadInternal::Resume()
521 {
522 ULONG ulrc = ::DosResumeThread(m_hThread);
523
524 if (ulrc != 0)
525 {
526 wxLogSysError(_("Can not resume thread %lu"), m_hThread);
527 return false;
528 }
529
530 // don't change the state from STATE_EXITED because it's special and means
531 // we are going to terminate without running any user code - if we did it,
532 // the codei n Delete() wouldn't work
533 if ( m_eState != STATE_EXITED )
534 {
535 m_eState = STATE_RUNNING;
536 }
537
538 return true;
539 }
540
541 // static functions
542 // ----------------
543
544 wxThread *wxThread::This()
545 {
546 wxThread* pThread = m_pThread;
547 return pThread;
548 }
549
550 #ifdef Yield
551 #undef Yield
552 #endif
553
554 void wxThread::Yield()
555 {
556 ::DosSleep(0);
557 }
558
559 int wxThread::GetCPUCount()
560 {
561 ULONG CPUCount;
562 APIRET ulrc;
563 ulrc = ::DosQuerySysInfo(26, 26, (void *)&CPUCount, sizeof(ULONG));
564 // QSV_NUMPROCESSORS(26) is typically not defined in header files
565
566 if (ulrc != 0)
567 CPUCount = 1;
568
569 return CPUCount;
570 }
571
572 wxThreadIdType wxThread::GetCurrentId()
573 {
574 PTIB ptib;
575 PPIB ppib;
576
577 ::DosGetInfoBlocks(&ptib, &ppib);
578 return (wxThreadIdType) ptib->tib_ptib2->tib2_ultid;
579 }
580
581 bool wxThread::SetConcurrency(size_t level)
582 {
583 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
584
585 // ok only for the default one
586 if ( level == 0 )
587 return 0;
588
589 // Don't know how to realize this on OS/2.
590 return level == 1;
591 }
592
593 // ctor and dtor
594 // -------------
595
596 wxThread::wxThread(wxThreadKind kind)
597 {
598 m_internal = new wxThreadInternal();
599
600 m_isDetached = kind == wxTHREAD_DETACHED;
601 }
602
603 wxThread::~wxThread()
604 {
605 delete m_internal;
606 }
607
608 // create/start thread
609 // -------------------
610
611 wxThreadError wxThread::Create(
612 unsigned int uStackSize
613 )
614 {
615 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
616
617 if ( !m_internal->Create(this, uStackSize) )
618 return wxTHREAD_NO_RESOURCE;
619
620 return wxTHREAD_NO_ERROR;
621 }
622
623 wxThreadError wxThread::Run()
624 {
625 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
626
627 if ( m_internal->GetState() != STATE_NEW )
628 {
629 // actually, it may be almost any state at all, not only STATE_RUNNING
630 return wxTHREAD_RUNNING;
631 }
632 return Resume();
633 }
634
635 // suspend/resume thread
636 // ---------------------
637
638 wxThreadError wxThread::Pause()
639 {
640 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
641
642 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
643 }
644
645 wxThreadError wxThread::Resume()
646 {
647 if (m_internal->GetState() == STATE_NEW)
648 {
649 m_internal->SetState(STATE_RUNNING);
650 m_critsect.Leave();
651 return wxTHREAD_NO_ERROR;
652 }
653
654 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
655
656 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
657 }
658
659 // stopping thread
660 // ---------------
661
662 wxThread::ExitCode wxThread::Wait()
663 {
664 // although under Windows we can wait for any thread, it's an error to
665 // wait for a detached one in wxWin API
666 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
667 _T("can't wait for detached thread") );
668 ExitCode rc = (ExitCode)-1;
669 (void)Delete(&rc);
670 return(rc);
671 }
672
673 wxThreadError wxThread::Delete(ExitCode *pRc)
674 {
675 ExitCode rc = 0;
676
677 // Delete() is always safe to call, so consider all possible states
678
679 // we might need to resume the thread, but we might also not need to cancel
680 // it if it doesn't run yet
681 bool shouldResume = false,
682 shouldCancel = true,
683 isRunning = false;
684
685 // check if the thread already started to run
686 {
687 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
688
689 if ( m_internal->GetState() == STATE_NEW )
690 {
691 // WinThreadStart() will see it and terminate immediately, no need
692 // to cancel the thread - but we still need to resume it to let it
693 // run
694 m_internal->SetState(STATE_EXITED);
695
696 Resume(); // it knows about STATE_EXITED special case
697
698 shouldCancel = false;
699 isRunning = true;
700
701 // shouldResume is correctly set to false here
702 }
703 else
704 {
705 shouldResume = IsPaused();
706 }
707 }
708
709 // resume the thread if it is paused
710 if ( shouldResume )
711 Resume();
712
713 TID hThread = m_internal->GetHandle();
714
715 if ( isRunning || IsRunning())
716 {
717 if (IsMain())
718 {
719 // set flag for wxIsWaitingForThread()
720 gs_bWaitingForThread = true;
721 }
722
723 // ask the thread to terminate
724 if ( shouldCancel )
725 {
726 wxCriticalSectionLocker lock(m_critsect);
727
728 m_internal->Cancel();
729 }
730
731 #if 0
732 // we can't just wait for the thread to terminate because it might be
733 // calling some GUI functions and so it will never terminate before we
734 // process the Windows messages that result from these functions
735 DWORD result = 0; // suppress warnings from broken compilers
736 do
737 {
738 if ( IsMain() )
739 {
740 // give the thread we're waiting for chance to do the GUI call
741 // it might be in
742 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
743 {
744 wxMutexGuiLeave();
745 }
746 }
747
748 result = ::DosWaitThread(&hThread, DCWW_NOWAIT);
749 // FIXME: We ought to have a message processing loop here!!
750
751 switch ( result )
752 {
753 case ERROR_INTERRUPT:
754 case ERROR_THREAD_NOT_TERMINATED:
755 break;
756 case ERROR_INVALID_THREADID:
757 case NO_ERROR:
758 // thread we're waiting for just terminated
759 // or even does not exist any more.
760 result = NO_ERROR;
761 break;
762 default:
763 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
764 }
765 if ( IsMain() )
766 {
767 // event processing - needed if we are the main thread
768 // to give other threads a chance to do remaining GUI
769 // processing and terminate cleanly.
770 wxTheApp->HandleSockets();
771 if (wxTheApp->Pending())
772 if ( !wxTheApp->DoMessage() )
773 {
774 // WM_QUIT received: kill the thread
775 Kill();
776
777 return wxTHREAD_KILLED;
778 }
779 else
780 wxUsleep(10);
781 }
782 else
783 wxUsleep(10);
784 } while ( result != NO_ERROR );
785 #else // !wxUSE_GUI
786 // simply wait for the thread to terminate
787 //
788 // OTOH, even console apps create windows (in wxExecute, for WinSock
789 // &c), so may be use MsgWaitForMultipleObject() too here?
790 if ( ::DosWaitThread(&hThread, DCWW_WAIT) != NO_ERROR )
791 {
792 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
793 }
794 #endif // wxUSE_GUI/!wxUSE_GUI
795
796 if ( IsMain() )
797 {
798 gs_bWaitingForThread = false;
799 }
800 }
801
802 #if 0
803 // although the thread might be already in the EXITED state it might not
804 // have terminated yet and so we are not sure that it has actually
805 // terminated if the "if" above hadn't been taken
806 do
807 {
808 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
809 {
810 wxLogLastError(wxT("GetExitCodeThread"));
811
812 rc = (ExitCode)-1;
813 }
814 } while ( (DWORD)rc == STILL_ACTIVE );
815 #endif
816
817 if ( IsDetached() )
818 {
819 // if the thread exits normally, this is done in WinThreadStart, but in
820 // this case it would have been too early because
821 // MsgWaitForMultipleObject() would fail if the thread handle was
822 // closed while we were waiting on it, so we must do it here
823 delete this;
824 }
825
826 if ( pRc )
827 *pRc = rc;
828
829 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
830 }
831
832 wxThreadError wxThread::Kill()
833 {
834 if (!IsRunning())
835 return wxTHREAD_NOT_RUNNING;
836
837 ::DosKillThread(m_internal->GetHandle());
838 if (IsDetached())
839 {
840 delete this;
841 }
842 return wxTHREAD_NO_ERROR;
843 }
844
845 void wxThread::Exit(ExitCode WXUNUSED(pStatus))
846 {
847 delete this;
848 _endthread();
849 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
850 }
851
852 void wxThread::SetPriority(
853 unsigned int nPrio
854 )
855 {
856 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
857
858 m_internal->SetPriority(nPrio);
859 }
860
861 unsigned int wxThread::GetPriority() const
862 {
863 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
864
865 return m_internal->GetPriority();
866 }
867
868 unsigned long wxThread::GetId() const
869 {
870 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
871
872 return (unsigned long)m_internal->GetId();
873 }
874
875 bool wxThread::IsRunning() const
876 {
877 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
878
879 return(m_internal->GetState() == STATE_RUNNING);
880 }
881
882 bool wxThread::IsAlive() const
883 {
884 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
885
886 return (m_internal->GetState() == STATE_RUNNING) ||
887 (m_internal->GetState() == STATE_PAUSED);
888 }
889
890 bool wxThread::IsPaused() const
891 {
892 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
893
894 return (m_internal->GetState() == STATE_PAUSED);
895 }
896
897 bool wxThread::TestDestroy()
898 {
899 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
900
901 return m_internal->GetState() == STATE_CANCELED;
902 }
903
904 // ----------------------------------------------------------------------------
905 // Automatic initialization for thread module
906 // ----------------------------------------------------------------------------
907
908 class wxThreadModule : public wxModule
909 {
910 public:
911 virtual bool OnInit();
912 virtual void OnExit();
913
914 private:
915 DECLARE_DYNAMIC_CLASS(wxThreadModule)
916 };
917
918 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
919
920 bool wxThreadModule::OnInit()
921 {
922 gs_pCritsectWaitingForGui = new wxCriticalSection();
923
924 gs_pCritsectGui = new wxCriticalSection();
925 gs_pCritsectGui->Enter();
926
927 wxThread::ms_idMainThread = wxThread::GetCurrentId();
928
929 return true;
930 }
931
932 void wxThreadModule::OnExit()
933 {
934 if (gs_pCritsectGui)
935 {
936 gs_pCritsectGui->Leave();
937 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
938 delete gs_pCritsectGui;
939 #endif
940 gs_pCritsectGui = NULL;
941 }
942
943 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
944 wxDELETE(gs_pCritsectWaitingForGui);
945 #endif
946 }
947
948 // ----------------------------------------------------------------------------
949 // Helper functions
950 // ----------------------------------------------------------------------------
951
952 // wake up the main thread if it's in ::GetMessage()
953 void WXDLLEXPORT wxWakeUpMainThread()
954 {
955 #if 0
956 if ( !::WinPostQueueMsg(wxTheApp->m_hMq, WM_NULL, 0, 0) )
957 {
958 // should never happen
959 wxLogLastError(wxT("WinPostMessage(WM_NULL)"));
960 }
961 #endif
962 }
963
964 void wxMutexGuiEnterImpl()
965 {
966 // this would dead lock everything...
967 wxASSERT_MSG( !wxThread::IsMain(),
968 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
969
970 // the order in which we enter the critical sections here is crucial!!
971
972 // set the flag telling to the main thread that we want to do some GUI
973 {
974 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
975
976 gs_nWaitingForGui++;
977 }
978
979 wxWakeUpMainThread();
980
981 // now we may block here because the main thread will soon let us in
982 // (during the next iteration of OnIdle())
983 gs_pCritsectGui->Enter();
984 }
985
986 void wxMutexGuiLeaveImpl()
987 {
988 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
989
990 if ( wxThread::IsMain() )
991 {
992 gs_bGuiOwnedByMainThread = false;
993 }
994 else
995 {
996 // decrement the number of waiters now
997 wxASSERT_MSG(gs_nWaitingForGui > 0,
998 wxT("calling wxMutexGuiLeave() without entering it first?") );
999
1000 gs_nWaitingForGui--;
1001
1002 wxWakeUpMainThread();
1003 }
1004
1005 gs_pCritsectGui->Leave();
1006 }
1007
1008 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1009 {
1010 wxASSERT_MSG( wxThread::IsMain(),
1011 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1012
1013 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
1014
1015 if (gs_nWaitingForGui == 0)
1016 {
1017 // no threads are waiting for GUI - so we may acquire the lock without
1018 // any danger (but only if we don't already have it)
1019 if (!wxGuiOwnedByMainThread())
1020 {
1021 gs_pCritsectGui->Enter();
1022
1023 gs_bGuiOwnedByMainThread = true;
1024 }
1025 //else: already have it, nothing to do
1026 }
1027 else
1028 {
1029 // some threads are waiting, release the GUI lock if we have it
1030 if (wxGuiOwnedByMainThread())
1031 {
1032 wxMutexGuiLeave();
1033 }
1034 //else: some other worker thread is doing GUI
1035 }
1036 }
1037
1038 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1039 {
1040 return gs_bGuiOwnedByMainThread;
1041 }
1042
1043 bool WXDLLEXPORT wxIsWaitingForThread()
1044 {
1045 return gs_bWaitingForThread;
1046 }
1047
1048 // ----------------------------------------------------------------------------
1049 // include common implementation code
1050 // ----------------------------------------------------------------------------
1051
1052 #include "wx/thrimpl.cpp"
1053
1054 #endif
1055 // wxUSE_THREADS