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