Try to get along without wxWakeUpMainThread (wxBase/GTK/Motif/X11 won't
[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/module.h"
30 #include "wx/intl.h"
31 #include "wx/utils.h"
32 #include "wx/log.h"
33 #include "wx/thread.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 static ULONG s_ulIdMainThread = 1;
61 wxMutex* p_wxMainMutex;
62
63 // OS2 substitute for Tls pointer the current parent thread object
64 wxThread* m_pThread; // pointer to the wxWindows 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 TryLock() { return LockTimeout(SEM_IMMEDIATE_RETURN); }
100 wxMutexError Unlock();
101
102 private:
103 wxMutexError LockTimeout(ULONG ulMilliseconds);
104 HMTX m_vMutex;
105 };
106
107 // all mutexes are "pseudo-"recursive under OS2 so we don't use mutexType
108 // (Calls to DosRequestMutexSem and DosReleaseMutexSem can be nested, but
109 // the request count for a semaphore cannot exceed 65535. If an attempt is
110 // made to exceed this number, ERROR_TOO_MANY_SEM_REQUESTS is returned.)
111 wxMutexInternal::wxMutexInternal(
112 wxMutexType WXUNUSED(eMutexType)
113 )
114 {
115 APIRET ulrc;
116
117 ulrc = ::DosCreateMutexSem(NULL, &m_vMutex, 0L, FALSE);
118 if (ulrc != 0)
119 {
120 wxLogSysError(_("Can not create mutex."));
121 m_vMutex = NULL;
122 }
123 }
124
125 wxMutexInternal::~wxMutexInternal()
126 {
127 if (m_vMutex)
128 {
129 if (::DosCloseMutexSem(m_vMutex))
130 wxLogLastError(_T("DosCloseMutexSem(mutex)"));
131 }
132 }
133
134 wxMutexError wxMutexInternal::LockTimeout(ULONG ulMilliseconds)
135 {
136 APIRET ulrc;
137
138 ulrc = ::DosRequestMutexSem(m_vMutex, ulMilliseconds);
139
140 switch (ulrc)
141 {
142 case ERROR_TIMEOUT:
143 case ERROR_TOO_MANY_SEM_REQUESTS:
144 return wxMUTEX_BUSY;
145
146 case NO_ERROR:
147 // ok
148 break;
149
150 case ERROR_INVALID_HANDLE:
151 case ERROR_INTERRUPT:
152 case ERROR_SEM_OWNER_DIED:
153 wxLogSysError(_("Couldn't acquire a mutex lock"));
154 return wxMUTEX_MISC_ERROR;
155
156 default:
157 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
158 return wxMUTEX_MISC_ERROR;
159 }
160 return wxMUTEX_NO_ERROR;
161 }
162
163 wxMutexError wxMutexInternal::Unlock()
164 {
165 APIRET ulrc;
166
167 ulrc = ::DosReleaseMutexSem(m_vMutex);
168 if (ulrc != 0)
169 {
170 wxLogSysError(_("Couldn't release a mutex"));
171 return wxMUTEX_MISC_ERROR;
172 }
173 return wxMUTEX_NO_ERROR;
174 }
175
176 // --------------------------------------------------------------------------
177 // wxSemaphore
178 // --------------------------------------------------------------------------
179
180 // a trivial wrapper around OS2 event semaphore
181 class wxSemaphoreInternal
182 {
183 public:
184 wxSemaphoreInternal(int initialcount, int maxcount);
185 ~wxSemaphoreInternal();
186
187 bool IsOk() const { return m_vEvent != NULL; }
188
189 wxSemaError Wait() { return WaitTimeout(SEM_INDEFINITE_WAIT); }
190 wxSemaError TryWait() { return WaitTimeout(SEM_IMMEDIATE_RETURN); }
191 wxSemaError WaitTimeout(unsigned long milliseconds);
192
193 wxSemaError Post();
194
195 private:
196 HEV m_vEvent;
197 HMTX m_vMutex;
198 int m_count;
199 int m_maxcount;
200 };
201
202 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
203 {
204 APIRET ulrc;
205 if ( maxcount == 0 )
206 {
207 // make it practically infinite
208 maxcount = INT_MAX;
209 }
210
211 m_count = initialcount;
212 m_maxcount = maxcount;
213 ulrc = ::DosCreateMutexSem(NULL, &m_vMutex, 0L, FALSE);
214 if (ulrc != 0)
215 {
216 wxLogLastError(_T("DosCreateMutexSem()"));
217 m_vMutex = NULL;
218 m_vEvent = NULL;
219 return;
220 }
221 ulrc = ::DosCreateEventSem(NULL, &m_vEvent, 0L, FALSE);
222 if ( ulrc != 0)
223 {
224 wxLogLastError(_T("DosCreateEventSem()"));
225 ::DosCloseMutexSem(m_vMutex);
226 m_vMutex = NULL;
227 m_vEvent = NULL;
228 }
229 if (initialcount)
230 ::DosPostEventSem(m_vEvent);
231 }
232
233 wxSemaphoreInternal::~wxSemaphoreInternal()
234 {
235 if ( m_vEvent )
236 {
237 if ( ::DosCloseEventSem(m_vEvent) )
238 {
239 wxLogLastError(_T("DosCloseEventSem(semaphore)"));
240 }
241 if ( ::DosCloseMutexSem(m_vMutex) )
242 {
243 wxLogLastError(_T("DosCloseMutexSem(semaphore)"));
244 }
245 else
246 m_vEvent = NULL;
247 }
248 }
249
250 wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long ulMilliseconds)
251 {
252 APIRET ulrc;
253 do {
254 ulrc = ::DosWaitEventSem(m_vEvent, ulMilliseconds );
255 switch ( ulrc )
256 {
257 case NO_ERROR:
258 break;
259
260 case ERROR_TIMEOUT:
261 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
262 return wxSEMA_BUSY;
263 else
264 return wxSEMA_TIMEOUT;
265
266 default:
267 wxLogLastError(_T("DosWaitEventSem(semaphore)"));
268 return wxSEMA_MISC_ERROR;
269 }
270 ulrc = :: DosRequestMutexSem(m_vMutex, ulMilliseconds);
271 switch ( ulrc )
272 {
273 case NO_ERROR:
274 // ok
275 break;
276
277 case ERROR_TIMEOUT:
278 case ERROR_TOO_MANY_SEM_REQUESTS:
279 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
280 return wxSEMA_BUSY;
281 else
282 return wxSEMA_TIMEOUT;
283
284 default:
285 wxFAIL_MSG(wxT("DosRequestMutexSem(mutex)"));
286 return wxSEMA_MISC_ERROR;
287 }
288 bool OK = false;
289 if (m_count > 0)
290 {
291 m_count--;
292 OK = true;
293 }
294 else
295 {
296 ULONG ulPostCount;
297 ::DosResetEventSem(m_vEvent, &ulPostCount);
298 }
299 ::DosReleaseMutexSem(m_vMutex);
300 if (OK)
301 return wxSEMA_NO_ERROR;
302 } while (ulMilliseconds == SEM_INDEFINITE_WAIT);
303
304 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
305 return wxSEMA_BUSY;
306 return wxSEMA_TIMEOUT;
307 }
308
309 wxSemaError wxSemaphoreInternal::Post()
310 {
311 APIRET ulrc;
312 ulrc = ::DosRequestMutexSem(m_vMutex, SEM_INDEFINITE_WAIT);
313 if (ulrc != NO_ERROR)
314 return wxSEMA_MISC_ERROR;
315 bool OK = false;
316 if (m_count < m_maxcount)
317 {
318 m_count++;
319 ulrc = ::DosPostEventSem(m_vEvent);
320 OK = true;
321 }
322 ::DosReleaseMutexSem(m_vMutex);
323 if (!OK)
324 return wxSEMA_OVERFLOW;
325 if ( ulrc != NO_ERROR && ulrc != ERROR_ALREADY_POSTED )
326 {
327 wxLogLastError(_T("DosPostEventSem(semaphore)"));
328
329 return wxSEMA_MISC_ERROR;
330 }
331
332 return wxSEMA_NO_ERROR;
333 }
334
335 // ----------------------------------------------------------------------------
336 // wxThread implementation
337 // ----------------------------------------------------------------------------
338
339 // wxThreadInternal class
340 // ----------------------
341
342 class wxThreadInternal
343 {
344 public:
345 inline wxThreadInternal()
346 {
347 m_hThread = 0;
348 m_eState = STATE_NEW;
349 m_nPriority = WXTHREAD_DEFAULT_PRIORITY;
350 }
351
352 ~wxThreadInternal()
353 {
354 m_hThread = 0;
355 }
356
357 // create a new (suspended) thread (for the given thread object)
358 bool Create( wxThread* pThread
359 ,unsigned int uStackSize
360 );
361
362 // suspend/resume/terminate
363 bool Suspend();
364 bool Resume();
365 inline void Cancel() { m_eState = STATE_CANCELED; }
366
367 // thread state
368 inline void SetState(wxThreadState eState) { m_eState = eState; }
369 inline wxThreadState GetState() const { return m_eState; }
370
371 // thread priority
372 void SetPriority(unsigned int nPriority);
373 inline unsigned int GetPriority() const { return m_nPriority; }
374
375 // thread handle and id
376 inline TID GetHandle() const { return m_hThread; }
377 TID GetId() const { return m_hThread; }
378
379 // thread function
380 static DWORD OS2ThreadStart(ULONG ulParam);
381
382 private:
383 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
384 // PM also has no real Tls mechanism to index pointers by so we'll just
385 // keep track of the wxWindows parent object here.
386 TID m_hThread; // handle and ID of the thread
387 wxThreadState m_eState; // state, see wxThreadState enum
388 unsigned int m_nPriority; // thread priority in "wx" units
389 };
390
391 ULONG wxThreadInternal::OS2ThreadStart(
392 ULONG ulParam
393 )
394 {
395 DWORD dwRet;
396 bool bWasCancelled;
397
398 // first of all, check whether we hadn't been cancelled already and don't
399 // start the user code at all then
400 wxThread *pThread = (wxThread *)ulParam;
401 if ( pThread->m_internal->GetState() == STATE_EXITED )
402 {
403 dwRet = (DWORD)-1;
404 bWasCancelled = TRUE;
405 }
406 else // do run thread
407 {
408 dwRet = (DWORD)pThread->Entry();
409
410 // enter m_critsect before changing the thread state
411 pThread->m_critsect.Enter();
412
413 bWasCancelled = pThread->m_internal->GetState() == STATE_CANCELED;
414
415 pThread->m_internal->SetState(STATE_EXITED);
416 pThread->m_critsect.Leave();
417 }
418 pThread->OnExit();
419
420 // if the thread was cancelled (from Delete()), then it the handle is still
421 // needed there
422 if (pThread->IsDetached() && !bWasCancelled)
423 {
424 // auto delete
425 delete pThread;
426 }
427 //else: the joinable threads handle will be closed when Wait() is done
428 return dwRet;
429 }
430
431 void wxThreadInternal::SetPriority(
432 unsigned int nPriority
433 )
434 {
435 // translate wxWindows priority to the PM one
436 ULONG ulOS2_PriorityClass;
437 ULONG ulOS2_SubPriority;
438 ULONG ulrc;
439
440 m_nPriority = nPriority;
441 if (m_nPriority <= 25)
442 ulOS2_PriorityClass = PRTYC_IDLETIME;
443 else if (m_nPriority <= 50)
444 ulOS2_PriorityClass = PRTYC_REGULAR;
445 else if (m_nPriority <= 75)
446 ulOS2_PriorityClass = PRTYC_TIMECRITICAL;
447 else if (m_nPriority <= 100)
448 ulOS2_PriorityClass = PRTYC_FOREGROUNDSERVER;
449 else
450 {
451 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
452 ulOS2_PriorityClass = PRTYC_REGULAR;
453 }
454 ulOS2_SubPriority = (ULONG) (((m_nPriority - 1) % 25 + 1) * 31.0 / 25);
455 ulrc = ::DosSetPriority( PRTYS_THREAD
456 ,ulOS2_PriorityClass
457 ,ulOS2_SubPriority
458 ,(ULONG)m_hThread
459 );
460 if (ulrc != 0)
461 {
462 wxLogSysError(_("Can't set thread priority"));
463 }
464 }
465
466 bool wxThreadInternal::Create(
467 wxThread* pThread
468 , unsigned int uStackSize
469 )
470 {
471 APIRET ulrc;
472
473 ulrc = ::DosCreateThread( &m_hThread
474 ,(PFNTHREAD)wxThreadInternal::OS2ThreadStart
475 ,(ULONG)pThread
476 ,CREATE_SUSPENDED | STACK_SPARSE
477 ,(ULONG)uStackSize
478 );
479 if(ulrc != 0)
480 {
481 wxLogSysError(_("Can't create thread"));
482
483 return FALSE;
484 }
485 if (m_nPriority != WXTHREAD_DEFAULT_PRIORITY)
486 {
487 SetPriority(m_nPriority);
488 }
489
490 return(TRUE);
491 }
492
493 bool wxThreadInternal::Suspend()
494 {
495 ULONG ulrc = ::DosSuspendThread(m_hThread);
496
497 if (ulrc != 0)
498 {
499 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
500 return FALSE;
501 }
502 m_eState = STATE_PAUSED;
503 return TRUE;
504 }
505
506 bool wxThreadInternal::Resume()
507 {
508 ULONG ulrc = ::DosResumeThread(m_hThread);
509
510 if (ulrc != 0)
511 {
512 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
513 return FALSE;
514 }
515
516 // don't change the state from STATE_EXITED because it's special and means
517 // we are going to terminate without running any user code - if we did it,
518 // the codei n Delete() wouldn't work
519 if ( m_eState != STATE_EXITED )
520 {
521 m_eState = STATE_RUNNING;
522 }
523
524 return TRUE;
525 }
526
527 // static functions
528 // ----------------
529
530 bool WXDLLEXPORT wxGuiOwnedByMainThread();
531
532 wxThread *wxThread::This()
533 {
534 wxThread* pThread = m_pThread;
535 return pThread;
536 }
537
538 bool wxThread::IsMain()
539 {
540 PTIB ptib;
541 PPIB ppib;
542
543 ::DosGetInfoBlocks(&ptib, &ppib);
544
545 if (ptib->tib_ptib2->tib2_ultid == s_ulIdMainThread)
546 return TRUE;
547 return FALSE;
548 }
549
550 #ifdef Yield
551 #undef Yield
552 #endif
553
554 void wxThread::Yield()
555 {
556 ::DosSleep(0);
557 }
558
559 void wxThread::Sleep(
560 unsigned long ulMilliseconds
561 )
562 {
563 ::DosSleep(ulMilliseconds);
564 }
565
566 int wxThread::GetCPUCount()
567 {
568 ULONG CPUCount;
569 APIRET ulrc;
570 ulrc = ::DosQuerySysInfo(26, 26, (void *)&CPUCount, sizeof(ULONG));
571 // QSV_NUMPROCESSORS(26) is typically not defined in header files
572
573 if (ulrc != 0)
574 CPUCount = 1;
575
576 return CPUCount;
577 }
578
579 unsigned long wxThread::GetCurrentId()
580 {
581 PTIB ptib;
582 PPIB ppib;
583
584 ::DosGetInfoBlocks(&ptib, &ppib);
585 return (unsigned long) ptib->tib_ptib2->tib2_ultid;
586 }
587
588 bool wxThread::SetConcurrency(size_t level)
589 {
590 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
591
592 // ok only for the default one
593 if ( level == 0 )
594 return 0;
595
596 // Don't know how to realize this on OS/2.
597 return level == 1;
598 }
599
600 // ctor and dtor
601 // -------------
602
603 wxThread::wxThread(wxThreadKind kind)
604 {
605 m_internal = new wxThreadInternal();
606
607 m_isDetached = kind == wxTHREAD_DETACHED;
608 }
609
610 wxThread::~wxThread()
611 {
612 delete m_internal;
613 }
614
615 // create/start thread
616 // -------------------
617
618 wxThreadError wxThread::Create(
619 unsigned int uStackSize
620 )
621 {
622 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
623
624 if ( !m_internal->Create(this, uStackSize) )
625 return wxTHREAD_NO_RESOURCE;
626
627 return wxTHREAD_NO_ERROR;
628 }
629
630 wxThreadError wxThread::Run()
631 {
632 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
633
634 if ( m_internal->GetState() != STATE_NEW )
635 {
636 // actually, it may be almost any state at all, not only STATE_RUNNING
637 return wxTHREAD_RUNNING;
638 }
639 return Resume();
640 }
641
642 // suspend/resume thread
643 // ---------------------
644
645 wxThreadError wxThread::Pause()
646 {
647 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
648
649 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
650 }
651
652 wxThreadError wxThread::Resume()
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 wxUSE_GUI
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_WAIT);
749 // FIXME: We ought to have a message processing loop here!!
750
751 switch ( result )
752 {
753 case ERROR_THREAD_NOT_TERMINATED:
754 case ERROR_INVALID_THREADID:
755 // error
756 wxLogSysError(_("Can not wait for thread termination"));
757 Kill();
758 return wxTHREAD_KILLED;
759
760 case NO_ERROR:
761 // thread we're waiting for terminated
762 break;
763
764 default:
765 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
766 }
767 } while ( result != NO_ERROR );
768 #else // !wxUSE_GUI
769 // simply wait for the thread to terminate
770 //
771 // OTOH, even console apps create windows (in wxExecute, for WinSock
772 // &c), so may be use MsgWaitForMultipleObject() too here?
773 if ( ::DosWaitThread(&hThread, DCWW_WAIT) != NO_ERROR )
774 {
775 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
776 }
777 #endif // wxUSE_GUI/!wxUSE_GUI
778
779 if ( IsMain() )
780 {
781 gs_bWaitingForThread = FALSE;
782 }
783 }
784
785 #if 0
786 // although the thread might be already in the EXITED state it might not
787 // have terminated yet and so we are not sure that it has actually
788 // terminated if the "if" above hadn't been taken
789 do
790 {
791 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
792 {
793 wxLogLastError(wxT("GetExitCodeThread"));
794
795 rc = (ExitCode)-1;
796 }
797 } while ( (DWORD)rc == STILL_ACTIVE );
798 #endif
799
800 if ( IsDetached() )
801 {
802 // if the thread exits normally, this is done in WinThreadStart, but in
803 // this case it would have been too early because
804 // MsgWaitForMultipleObject() would fail if the thread handle was
805 // closed while we were waiting on it, so we must do it here
806 delete this;
807 }
808
809 if ( pRc )
810 *pRc = rc;
811
812 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
813 }
814
815 wxThreadError wxThread::Kill()
816 {
817 if (!IsRunning())
818 return wxTHREAD_NOT_RUNNING;
819
820 ::DosKillThread(m_internal->GetHandle());
821 if (IsDetached())
822 {
823 delete this;
824 }
825 return wxTHREAD_NO_ERROR;
826 }
827
828 void wxThread::Exit(
829 ExitCode pStatus
830 )
831 {
832 delete this;
833 ::DosExit(EXIT_THREAD, ULONG(pStatus));
834 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
835 }
836
837 void wxThread::SetPriority(
838 unsigned int nPrio
839 )
840 {
841 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
842
843 m_internal->SetPriority(nPrio);
844 }
845
846 unsigned int wxThread::GetPriority() const
847 {
848 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
849
850 return m_internal->GetPriority();
851 }
852
853 unsigned long wxThread::GetId() const
854 {
855 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
856
857 return (unsigned long)m_internal->GetId();
858 }
859
860 bool wxThread::IsRunning() const
861 {
862 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
863
864 return(m_internal->GetState() == STATE_RUNNING);
865 }
866
867 bool wxThread::IsAlive() const
868 {
869 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
870
871 return (m_internal->GetState() == STATE_RUNNING) ||
872 (m_internal->GetState() == STATE_PAUSED);
873 }
874
875 bool wxThread::IsPaused() const
876 {
877 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
878
879 return (m_internal->GetState() == STATE_PAUSED);
880 }
881
882 bool wxThread::TestDestroy()
883 {
884 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
885
886 return m_internal->GetState() == STATE_CANCELED;
887 }
888
889 // ----------------------------------------------------------------------------
890 // Automatic initialization for thread module
891 // ----------------------------------------------------------------------------
892
893 class wxThreadModule : public wxModule
894 {
895 public:
896 virtual bool OnInit();
897 virtual void OnExit();
898
899 private:
900 DECLARE_DYNAMIC_CLASS(wxThreadModule)
901 };
902
903 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
904
905 bool wxThreadModule::OnInit()
906 {
907 gs_pCritsectWaitingForGui = new wxCriticalSection();
908
909 gs_pCritsectGui = new wxCriticalSection();
910 gs_pCritsectGui->Enter();
911
912 PTIB ptib;
913 PPIB ppib;
914
915 ::DosGetInfoBlocks(&ptib, &ppib);
916
917 s_ulIdMainThread = ptib->tib_ptib2->tib2_ultid;
918 return TRUE;
919 }
920
921 void wxThreadModule::OnExit()
922 {
923 if (gs_pCritsectGui)
924 {
925 gs_pCritsectGui->Leave();
926 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
927 delete gs_pCritsectGui;
928 #endif
929 gs_pCritsectGui = NULL;
930 }
931
932 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
933 wxDELETE(gs_pCritsectWaitingForGui);
934 #endif
935 }
936
937 // ----------------------------------------------------------------------------
938 // Helper functions
939 // ----------------------------------------------------------------------------
940
941 // wake up the main thread if it's in ::GetMessage()
942 void WXDLLEXPORT wxWakeUpMainThread()
943 {
944 #if 0
945 if ( !::WinPostQueueMsg(wxTheApp->m_hMq, WM_NULL, 0, 0) )
946 {
947 // should never happen
948 wxLogLastError(wxT("WinPostMessage(WM_NULL)"));
949 }
950 #endif
951 }
952
953 void WXDLLEXPORT wxMutexGuiEnter()
954 {
955 // this would dead lock everything...
956 wxASSERT_MSG( !wxThread::IsMain(),
957 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
958
959 // the order in which we enter the critical sections here is crucial!!
960
961 // set the flag telling to the main thread that we want to do some GUI
962 {
963 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
964
965 gs_nWaitingForGui++;
966 }
967
968 wxWakeUpMainThread();
969
970 // now we may block here because the main thread will soon let us in
971 // (during the next iteration of OnIdle())
972 gs_pCritsectGui->Enter();
973 }
974
975 void WXDLLEXPORT wxMutexGuiLeave()
976 {
977 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
978
979 if ( wxThread::IsMain() )
980 {
981 gs_bGuiOwnedByMainThread = FALSE;
982 }
983 else
984 {
985 // decrement the number of waiters now
986 wxASSERT_MSG(gs_nWaitingForGui > 0,
987 wxT("calling wxMutexGuiLeave() without entering it first?") );
988
989 gs_nWaitingForGui--;
990
991 wxWakeUpMainThread();
992 }
993
994 gs_pCritsectGui->Leave();
995 }
996
997 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
998 {
999 wxASSERT_MSG( wxThread::IsMain(),
1000 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1001
1002 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
1003
1004 if (gs_nWaitingForGui == 0)
1005 {
1006 // no threads are waiting for GUI - so we may acquire the lock without
1007 // any danger (but only if we don't already have it)
1008 if (!wxGuiOwnedByMainThread())
1009 {
1010 gs_pCritsectGui->Enter();
1011
1012 gs_bGuiOwnedByMainThread = TRUE;
1013 }
1014 //else: already have it, nothing to do
1015 }
1016 else
1017 {
1018 // some threads are waiting, release the GUI lock if we have it
1019 if (wxGuiOwnedByMainThread())
1020 {
1021 wxMutexGuiLeave();
1022 }
1023 //else: some other worker thread is doing GUI
1024 }
1025 }
1026
1027 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1028 {
1029 return gs_bGuiOwnedByMainThread;
1030 }
1031
1032 bool WXDLLEXPORT wxIsWaitingForThread()
1033 {
1034 return gs_bWaitingForThread;
1035 }
1036
1037 // ----------------------------------------------------------------------------
1038 // include common implementation code
1039 // ----------------------------------------------------------------------------
1040
1041 #include "wx/thrimpl.cpp"
1042
1043 #endif
1044 // wxUSE_THREADS