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