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