]> git.saurik.com Git - wxWidgets.git/blob - src/os2/thread.cpp
Unified with Unix version.
[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 void OS2ThreadStart(void* pParam);
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 void wxThreadInternal::OS2ThreadStart(
392 void * pParam
393 )
394 {
395 DWORD dwRet;
396 bool bWasCancelled;
397
398 wxThread *pThread = (wxThread *)pParam;
399
400 // first of all, wait for the thread to be started.
401 pThread->m_critsect.Enter();
402 pThread->m_critsect.Leave();
403 // Now check whether we hadn't been cancelled already and don't
404 // start the user code at all in this case.
405 if ( pThread->m_internal->GetState() == STATE_EXITED )
406 {
407 dwRet = (DWORD)-1;
408 bWasCancelled = TRUE;
409 }
410 else // do run thread
411 {
412 dwRet = (DWORD)pThread->Entry();
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 wxWindows 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(
471 wxThread* pThread
472 , unsigned int uStackSize
473 )
474 {
475 int tid;
476
477 if (!uStackSize)
478 uStackSize = 131072;
479 pThread->m_critsect.Enter();
480 tid = _beginthread(wxThreadInternal::OS2ThreadStart,
481 NULL, uStackSize, pThread);
482 if(tid == -1)
483 {
484 wxLogSysError(_("Can't create thread"));
485
486 return FALSE;
487 }
488 m_hThread = tid;
489 if (m_nPriority != WXTHREAD_DEFAULT_PRIORITY)
490 {
491 SetPriority(m_nPriority);
492 }
493
494 return(TRUE);
495 }
496
497 bool wxThreadInternal::Suspend()
498 {
499 ULONG ulrc = ::DosSuspendThread(m_hThread);
500
501 if (ulrc != 0)
502 {
503 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
504 return FALSE;
505 }
506 m_eState = STATE_PAUSED;
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 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 wxUSE_GUI
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(
855 ExitCode pStatus
856 )
857 {
858 delete this;
859 _endthread();
860 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
861 }
862
863 void wxThread::SetPriority(
864 unsigned int nPrio
865 )
866 {
867 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
868
869 m_internal->SetPriority(nPrio);
870 }
871
872 unsigned int wxThread::GetPriority() const
873 {
874 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
875
876 return m_internal->GetPriority();
877 }
878
879 unsigned long wxThread::GetId() const
880 {
881 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
882
883 return (unsigned long)m_internal->GetId();
884 }
885
886 bool wxThread::IsRunning() const
887 {
888 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
889
890 return(m_internal->GetState() == STATE_RUNNING);
891 }
892
893 bool wxThread::IsAlive() const
894 {
895 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
896
897 return (m_internal->GetState() == STATE_RUNNING) ||
898 (m_internal->GetState() == STATE_PAUSED);
899 }
900
901 bool wxThread::IsPaused() const
902 {
903 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
904
905 return (m_internal->GetState() == STATE_PAUSED);
906 }
907
908 bool wxThread::TestDestroy()
909 {
910 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
911
912 return m_internal->GetState() == STATE_CANCELED;
913 }
914
915 // ----------------------------------------------------------------------------
916 // Automatic initialization for thread module
917 // ----------------------------------------------------------------------------
918
919 class wxThreadModule : public wxModule
920 {
921 public:
922 virtual bool OnInit();
923 virtual void OnExit();
924
925 private:
926 DECLARE_DYNAMIC_CLASS(wxThreadModule)
927 };
928
929 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
930
931 bool wxThreadModule::OnInit()
932 {
933 gs_pCritsectWaitingForGui = new wxCriticalSection();
934
935 gs_pCritsectGui = new wxCriticalSection();
936 gs_pCritsectGui->Enter();
937
938 PTIB ptib;
939 PPIB ppib;
940
941 ::DosGetInfoBlocks(&ptib, &ppib);
942
943 s_ulIdMainThread = ptib->tib_ptib2->tib2_ultid;
944 return TRUE;
945 }
946
947 void wxThreadModule::OnExit()
948 {
949 if (gs_pCritsectGui)
950 {
951 gs_pCritsectGui->Leave();
952 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
953 delete gs_pCritsectGui;
954 #endif
955 gs_pCritsectGui = NULL;
956 }
957
958 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
959 wxDELETE(gs_pCritsectWaitingForGui);
960 #endif
961 }
962
963 // ----------------------------------------------------------------------------
964 // Helper functions
965 // ----------------------------------------------------------------------------
966
967 // wake up the main thread if it's in ::GetMessage()
968 void WXDLLEXPORT wxWakeUpMainThread()
969 {
970 #if 0
971 if ( !::WinPostQueueMsg(wxTheApp->m_hMq, WM_NULL, 0, 0) )
972 {
973 // should never happen
974 wxLogLastError(wxT("WinPostMessage(WM_NULL)"));
975 }
976 #endif
977 }
978
979 void WXDLLEXPORT wxMutexGuiEnter()
980 {
981 // this would dead lock everything...
982 wxASSERT_MSG( !wxThread::IsMain(),
983 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
984
985 // the order in which we enter the critical sections here is crucial!!
986
987 // set the flag telling to the main thread that we want to do some GUI
988 {
989 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
990
991 gs_nWaitingForGui++;
992 }
993
994 wxWakeUpMainThread();
995
996 // now we may block here because the main thread will soon let us in
997 // (during the next iteration of OnIdle())
998 gs_pCritsectGui->Enter();
999 }
1000
1001 void WXDLLEXPORT wxMutexGuiLeave()
1002 {
1003 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
1004
1005 if ( wxThread::IsMain() )
1006 {
1007 gs_bGuiOwnedByMainThread = FALSE;
1008 }
1009 else
1010 {
1011 // decrement the number of waiters now
1012 wxASSERT_MSG(gs_nWaitingForGui > 0,
1013 wxT("calling wxMutexGuiLeave() without entering it first?") );
1014
1015 gs_nWaitingForGui--;
1016
1017 wxWakeUpMainThread();
1018 }
1019
1020 gs_pCritsectGui->Leave();
1021 }
1022
1023 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1024 {
1025 wxASSERT_MSG( wxThread::IsMain(),
1026 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1027
1028 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
1029
1030 if (gs_nWaitingForGui == 0)
1031 {
1032 // no threads are waiting for GUI - so we may acquire the lock without
1033 // any danger (but only if we don't already have it)
1034 if (!wxGuiOwnedByMainThread())
1035 {
1036 gs_pCritsectGui->Enter();
1037
1038 gs_bGuiOwnedByMainThread = TRUE;
1039 }
1040 //else: already have it, nothing to do
1041 }
1042 else
1043 {
1044 // some threads are waiting, release the GUI lock if we have it
1045 if (wxGuiOwnedByMainThread())
1046 {
1047 wxMutexGuiLeave();
1048 }
1049 //else: some other worker thread is doing GUI
1050 }
1051 }
1052
1053 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1054 {
1055 return gs_bGuiOwnedByMainThread;
1056 }
1057
1058 bool WXDLLEXPORT wxIsWaitingForThread()
1059 {
1060 return gs_bWaitingForThread;
1061 }
1062
1063 // ----------------------------------------------------------------------------
1064 // include common implementation code
1065 // ----------------------------------------------------------------------------
1066
1067 #include "wx/thrimpl.cpp"
1068
1069 #endif
1070 // wxUSE_THREADS