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