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