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