]> git.saurik.com Git - wxWidgets.git/blame - src/os2/thread.cpp
deleted unused variable
[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
d1bab566 380 static DWORD OS2ThreadStart(ULONG ulParam);
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
c5fb56c0 391ULONG wxThreadInternal::OS2ThreadStart(
d1bab566 392 ULONG ulParam
c5fb56c0 393)
d90895ac 394{
d1bab566
SN
395 DWORD dwRet;
396 bool bWasCancelled;
d90895ac 397
d1bab566
SN
398 // first of all, check whether we hadn't been cancelled already and don't
399 // start the user code at all then
400 wxThread *pThread = (wxThread *)ulParam;
401 if ( pThread->m_internal->GetState() == STATE_EXITED )
402 {
403 dwRet = (DWORD)-1;
404 bWasCancelled = TRUE;
405 }
406 else // do run thread
407 {
408 dwRet = (DWORD)pThread->Entry();
d01cc696 409
d1bab566
SN
410 // enter m_critsect before changing the thread state
411 pThread->m_critsect.Enter();
d01cc696 412
d1bab566 413 bWasCancelled = pThread->m_internal->GetState() == STATE_CANCELED;
d01cc696 414
d1bab566
SN
415 pThread->m_internal->SetState(STATE_EXITED);
416 pThread->m_critsect.Leave();
417 }
c5fb56c0 418 pThread->OnExit();
d90895ac 419
d01cc696
DW
420 // if the thread was cancelled (from Delete()), then it the handle is still
421 // needed there
422 if (pThread->IsDetached() && !bWasCancelled)
423 {
424 // auto delete
43543d98 425 delete pThread;
d01cc696
DW
426 }
427 //else: the joinable threads handle will be closed when Wait() is done
c5fb56c0 428 return dwRet;
d90895ac
DW
429}
430
d01cc696
DW
431void wxThreadInternal::SetPriority(
432 unsigned int nPriority
c5fb56c0 433)
d90895ac 434{
c5fb56c0 435 // translate wxWindows priority to the PM one
d1bab566
SN
436 ULONG ulOS2_PriorityClass;
437 ULONG ulOS2_SubPriority;
43543d98 438 ULONG ulrc;
c5fb56c0 439
d01cc696 440 m_nPriority = nPriority;
d1bab566
SN
441 if (m_nPriority <= 25)
442 ulOS2_PriorityClass = PRTYC_IDLETIME;
443 else if (m_nPriority <= 50)
444 ulOS2_PriorityClass = PRTYC_REGULAR;
445 else if (m_nPriority <= 75)
446 ulOS2_PriorityClass = PRTYC_TIMECRITICAL;
c5fb56c0 447 else if (m_nPriority <= 100)
d1bab566 448 ulOS2_PriorityClass = PRTYC_FOREGROUNDSERVER;
d90895ac
DW
449 else
450 {
451 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
d1bab566 452 ulOS2_PriorityClass = PRTYC_REGULAR;
d90895ac 453 }
d1bab566 454 ulOS2_SubPriority = (ULONG) (((m_nPriority - 1) % 25 + 1) * 31.0 / 25);
c5fb56c0 455 ulrc = ::DosSetPriority( PRTYS_THREAD
d1bab566
SN
456 ,ulOS2_PriorityClass
457 ,ulOS2_SubPriority
c5fb56c0
DW
458 ,(ULONG)m_hThread
459 );
460 if (ulrc != 0)
d90895ac
DW
461 {
462 wxLogSysError(_("Can't set thread priority"));
463 }
d01cc696
DW
464}
465
466bool wxThreadInternal::Create(
467 wxThread* pThread
793c7f9b 468, unsigned int uStackSize
d01cc696
DW
469)
470{
471 APIRET ulrc;
472
473 ulrc = ::DosCreateThread( &m_hThread
474 ,(PFNTHREAD)wxThreadInternal::OS2ThreadStart
475 ,(ULONG)pThread
476 ,CREATE_SUSPENDED | STACK_SPARSE
793c7f9b 477 ,(ULONG)uStackSize
d01cc696
DW
478 );
479 if(ulrc != 0)
480 {
481 wxLogSysError(_("Can't create thread"));
482
483 return FALSE;
484 }
485 if (m_nPriority != WXTHREAD_DEFAULT_PRIORITY)
486 {
487 SetPriority(m_nPriority);
488 }
1dfc3cda 489
d01cc696 490 return(TRUE);
d90895ac
DW
491}
492
493bool wxThreadInternal::Suspend()
494{
c5fb56c0 495 ULONG ulrc = ::DosSuspendThread(m_hThread);
d90895ac 496
c5fb56c0
DW
497 if (ulrc != 0)
498 {
499 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
d90895ac
DW
500 return FALSE;
501 }
c5fb56c0
DW
502 m_eState = STATE_PAUSED;
503 return TRUE;
d90895ac
DW
504}
505
506bool wxThreadInternal::Resume()
507{
c5fb56c0 508 ULONG ulrc = ::DosResumeThread(m_hThread);
d90895ac 509
c5fb56c0
DW
510 if (ulrc != 0)
511 {
512 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
d90895ac
DW
513 return FALSE;
514 }
d1bab566
SN
515
516 // don't change the state from STATE_EXITED because it's special and means
517 // we are going to terminate without running any user code - if we did it,
518 // the codei n Delete() wouldn't work
519 if ( m_eState != STATE_EXITED )
520 {
521 m_eState = STATE_RUNNING;
522 }
523
c5fb56c0 524 return TRUE;
d90895ac
DW
525}
526
527// static functions
528// ----------------
529
530wxThread *wxThread::This()
531{
c5fb56c0
DW
532 wxThread* pThread = m_pThread;
533 return pThread;
d90895ac
DW
534}
535
536bool wxThread::IsMain()
537{
c5fb56c0
DW
538 PTIB ptib;
539 PPIB ppib;
540
541 ::DosGetInfoBlocks(&ptib, &ppib);
542
543 if (ptib->tib_ptib2->tib2_ultid == s_ulIdMainThread)
544 return TRUE;
d90895ac
DW
545 return FALSE;
546}
547
548#ifdef Yield
549 #undef Yield
550#endif
551
552void wxThread::Yield()
553{
d90895ac
DW
554 ::DosSleep(0);
555}
556
c5fb56c0
DW
557void wxThread::Sleep(
558 unsigned long ulMilliseconds
559)
d90895ac 560{
c5fb56c0 561 ::DosSleep(ulMilliseconds);
d90895ac
DW
562}
563
d1bab566
SN
564int wxThread::GetCPUCount()
565{
566 ULONG CPUCount;
567 APIRET ulrc;
568 ulrc = ::DosQuerySysInfo(26, 26, (void *)&CPUCount, sizeof(ULONG));
569 // QSV_NUMPROCESSORS(26) is typically not defined in header files
570
571 if (ulrc != 0)
572 CPUCount = 1;
573
574 return CPUCount;
575}
576
577unsigned long wxThread::GetCurrentId()
578{
579 PTIB ptib;
580 PPIB ppib;
581
582 ::DosGetInfoBlocks(&ptib, &ppib);
583 return (unsigned long) ptib->tib_ptib2->tib2_ultid;
584}
585
586bool wxThread::SetConcurrency(size_t level)
587{
588 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
589
590 // ok only for the default one
591 if ( level == 0 )
592 return 0;
593
594 // Don't know how to realize this on OS/2.
595 return level == 1;
596}
597
d01cc696
DW
598// ctor and dtor
599// -------------
600
601wxThread::wxThread(wxThreadKind kind)
602{
603 m_internal = new wxThreadInternal();
604
605 m_isDetached = kind == wxTHREAD_DETACHED;
606}
607
608wxThread::~wxThread()
609{
610 delete m_internal;
611}
612
d90895ac
DW
613// create/start thread
614// -------------------
615
793c7f9b
DW
616wxThreadError wxThread::Create(
617 unsigned int uStackSize
618)
0e320a79 619{
d1bab566
SN
620 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
621
793c7f9b 622 if ( !m_internal->Create(this, uStackSize) )
d90895ac
DW
623 return wxTHREAD_NO_RESOURCE;
624
0e320a79
DW
625 return wxTHREAD_NO_ERROR;
626}
627
d90895ac 628wxThreadError wxThread::Run()
0e320a79 629{
c5fb56c0 630 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 631
d01cc696 632 if ( m_internal->GetState() != STATE_NEW )
d90895ac
DW
633 {
634 // actually, it may be almost any state at all, not only STATE_RUNNING
635 return wxTHREAD_RUNNING;
636 }
d90895ac 637 return Resume();
0e320a79
DW
638}
639
d90895ac
DW
640// suspend/resume thread
641// ---------------------
642
0e320a79
DW
643wxThreadError wxThread::Pause()
644{
c5fb56c0 645 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 646
d01cc696 647 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
0e320a79
DW
648}
649
650wxThreadError wxThread::Resume()
651{
c5fb56c0 652 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
0e320a79 653
d01cc696 654 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
0e320a79
DW
655}
656
d90895ac
DW
657// stopping thread
658// ---------------
659
d01cc696 660wxThread::ExitCode wxThread::Wait()
0e320a79 661{
d01cc696
DW
662 // although under Windows we can wait for any thread, it's an error to
663 // wait for a detached one in wxWin API
664 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
665 _T("can't wait for detached thread") );
666 ExitCode rc = (ExitCode)-1;
667 (void)Delete(&rc);
d01cc696
DW
668 return(rc);
669}
670
671wxThreadError wxThread::Delete(ExitCode *pRc)
672{
673 ExitCode rc = 0;
d90895ac
DW
674
675 // Delete() is always safe to call, so consider all possible states
d1bab566
SN
676
677 // we might need to resume the thread, but we might also not need to cancel
678 // it if it doesn't run yet
679 bool shouldResume = FALSE,
680 shouldCancel = TRUE,
681 isRunning = FALSE;
682
683 // check if the thread already started to run
684 {
685 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
686
687 if ( m_internal->GetState() == STATE_NEW )
688 {
689 // WinThreadStart() will see it and terminate immediately, no need
690 // to cancel the thread - but we still need to resume it to let it
691 // run
692 m_internal->SetState(STATE_EXITED);
693
694 Resume(); // it knows about STATE_EXITED special case
695
696 shouldCancel = FALSE;
697 isRunning = TRUE;
698
699 // shouldResume is correctly set to FALSE here
700 }
701 else
702 {
703 shouldResume = IsPaused();
704 }
705 }
706
707 // resume the thread if it is paused
708 if ( shouldResume )
d90895ac
DW
709 Resume();
710
d01cc696
DW
711 TID hThread = m_internal->GetHandle();
712
d1bab566 713 if ( isRunning || IsRunning())
d90895ac 714 {
c5fb56c0 715 if (IsMain())
d90895ac
DW
716 {
717 // set flag for wxIsWaitingForThread()
43543d98 718 gs_bWaitingForThread = TRUE;
d1bab566 719 }
d90895ac 720
d01cc696 721 // ask the thread to terminate
d1bab566 722 if ( shouldCancel )
d90895ac 723 {
d01cc696 724 wxCriticalSectionLocker lock(m_critsect);
d1bab566 725
d01cc696 726 m_internal->Cancel();
d90895ac
DW
727 }
728
d01cc696 729#if wxUSE_GUI
d1bab566
SN
730 // we can't just wait for the thread to terminate because it might be
731 // calling some GUI functions and so it will never terminate before we
732 // process the Windows messages that result from these functions
733 DWORD result = 0; // suppress warnings from broken compilers
734 do
d01cc696 735 {
d1bab566
SN
736 if ( IsMain() )
737 {
738 // give the thread we're waiting for chance to do the GUI call
739 // it might be in
740 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
741 {
742 wxMutexGuiLeave();
743 }
744 }
745
746 result = ::DosWaitThread(&hThread, DCWW_WAIT);
747 // FIXME: We ought to have a message processing loop here!!
748
749 switch ( result )
750 {
751 case ERROR_THREAD_NOT_TERMINATED:
752 case ERROR_INVALID_THREADID:
753 // error
754 wxLogSysError(_("Can not wait for thread termination"));
755 Kill();
756 return wxTHREAD_KILLED;
3b9e3455 757
d1bab566
SN
758 case NO_ERROR:
759 // thread we're waiting for terminated
760 break;
3b9e3455 761
d1bab566
SN
762 default:
763 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
764 }
765 } while ( result != NO_ERROR );
766#else // !wxUSE_GUI
767 // simply wait for the thread to terminate
768 //
769 // OTOH, even console apps create windows (in wxExecute, for WinSock
770 // &c), so may be use MsgWaitForMultipleObject() too here?
771 if ( ::DosWaitThread(&hThread, DCWW_WAIT) != NO_ERROR )
772 {
773 wxFAIL_MSG(wxT("unexpected result of DosWaitThread"));
774 }
d01cc696 775#endif // wxUSE_GUI/!wxUSE_GUI
d90895ac 776
d01cc696 777 if ( IsMain() )
d90895ac 778 {
43543d98 779 gs_bWaitingForThread = FALSE;
d90895ac 780 }
d01cc696
DW
781 }
782
d1bab566
SN
783#if 0
784 // although the thread might be already in the EXITED state it might not
785 // have terminated yet and so we are not sure that it has actually
786 // terminated if the "if" above hadn't been taken
787 do
788 {
789 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
790 {
791 wxLogLastError(wxT("GetExitCodeThread"));
792
793 rc = (ExitCode)-1;
794 }
795 } while ( (DWORD)rc == STILL_ACTIVE );
796#endif
797
798 if ( IsDetached() )
d01cc696 799 {
d1bab566
SN
800 // if the thread exits normally, this is done in WinThreadStart, but in
801 // this case it would have been too early because
802 // MsgWaitForMultipleObject() would fail if the thread handle was
803 // closed while we were waiting on it, so we must do it here
d01cc696
DW
804 delete this;
805 }
806
d01cc696
DW
807 if ( pRc )
808 *pRc = rc;
809
810 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
0e320a79
DW
811}
812
d90895ac 813wxThreadError wxThread::Kill()
0e320a79 814{
c5fb56c0 815 if (!IsRunning())
d90895ac
DW
816 return wxTHREAD_NOT_RUNNING;
817
d01cc696 818 ::DosKillThread(m_internal->GetHandle());
3b9e3455
DW
819 if (IsDetached())
820 {
821 delete this;
822 }
d90895ac 823 return wxTHREAD_NO_ERROR;
0e320a79
DW
824}
825
c5fb56c0 826void wxThread::Exit(
3b9e3455 827 ExitCode pStatus
c5fb56c0 828)
0e320a79 829{
d90895ac 830 delete this;
c5fb56c0
DW
831 ::DosExit(EXIT_THREAD, ULONG(pStatus));
832 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
0e320a79
DW
833}
834
c5fb56c0
DW
835void wxThread::SetPriority(
836 unsigned int nPrio
837)
0e320a79 838{
c5fb56c0 839 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 840
d01cc696 841 m_internal->SetPriority(nPrio);
0e320a79
DW
842}
843
d90895ac 844unsigned int wxThread::GetPriority() const
0e320a79 845{
c5fb56c0 846 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 847
d01cc696 848 return m_internal->GetPriority();
0e320a79
DW
849}
850
3b9e3455
DW
851unsigned long wxThread::GetId() const
852{
853 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
854
855 return (unsigned long)m_internal->GetId();
856}
857
d90895ac 858bool wxThread::IsRunning() const
0e320a79 859{
c5fb56c0 860 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 861
3b9e3455 862 return(m_internal->GetState() == STATE_RUNNING);
0e320a79 863}
0e320a79
DW
864
865bool wxThread::IsAlive() const
866{
c5fb56c0 867 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 868
d01cc696
DW
869 return (m_internal->GetState() == STATE_RUNNING) ||
870 (m_internal->GetState() == STATE_PAUSED);
0e320a79
DW
871}
872
d90895ac 873bool wxThread::IsPaused() const
0e320a79 874{
c5fb56c0 875 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 876
d01cc696 877 return (m_internal->GetState() == STATE_PAUSED);
0e320a79
DW
878}
879
d90895ac 880bool wxThread::TestDestroy()
0e320a79 881{
c5fb56c0 882 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 883
d01cc696 884 return m_internal->GetState() == STATE_CANCELED;
0e320a79
DW
885}
886
d90895ac
DW
887// ----------------------------------------------------------------------------
888// Automatic initialization for thread module
889// ----------------------------------------------------------------------------
0e320a79 890
d90895ac
DW
891class wxThreadModule : public wxModule
892{
0e320a79 893public:
d90895ac
DW
894 virtual bool OnInit();
895 virtual void OnExit();
0e320a79 896
d90895ac
DW
897private:
898 DECLARE_DYNAMIC_CLASS(wxThreadModule)
0e320a79
DW
899};
900
901IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
902
d90895ac
DW
903bool wxThreadModule::OnInit()
904{
43543d98 905 gs_pCritsectWaitingForGui = new wxCriticalSection();
d90895ac 906
43543d98
DW
907 gs_pCritsectGui = new wxCriticalSection();
908 gs_pCritsectGui->Enter();
d90895ac 909
c5fb56c0
DW
910 PTIB ptib;
911 PPIB ppib;
d90895ac 912
c5fb56c0 913 ::DosGetInfoBlocks(&ptib, &ppib);
d90895ac 914
c5fb56c0 915 s_ulIdMainThread = ptib->tib_ptib2->tib2_ultid;
d90895ac
DW
916 return TRUE;
917}
918
919void wxThreadModule::OnExit()
920{
43543d98 921 if (gs_pCritsectGui)
d90895ac 922 {
43543d98 923 gs_pCritsectGui->Leave();
f6bcfd97 924#if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
43543d98 925 delete gs_pCritsectGui;
f6bcfd97 926#endif
43543d98 927 gs_pCritsectGui = NULL;
d90895ac
DW
928 }
929
f6bcfd97 930#if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
43543d98 931 wxDELETE(gs_pCritsectWaitingForGui);
f6bcfd97 932#endif
d90895ac
DW
933}
934
935// ----------------------------------------------------------------------------
c5fb56c0 936// Helper functions
d90895ac
DW
937// ----------------------------------------------------------------------------
938
d1bab566 939// wake up the main thread if it's in ::GetMessage()
c5fb56c0 940void WXDLLEXPORT wxWakeUpMainThread()
d90895ac 941{
d1bab566
SN
942 if ( !::WinPostQueueMsg(wxTheApp->m_hMq, WM_NULL, 0, 0) )
943 {
944 // should never happen
945 wxLogLastError(wxT("WinPostMessage(WM_NULL)"));
946 }
d90895ac
DW
947}
948
28a75c29
SN
949void WXDLLEXPORT wxMutexGuiEnter()
950{
951 // this would dead lock everything...
952 wxASSERT_MSG( !wxThread::IsMain(),
953 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
954
955 // the order in which we enter the critical sections here is crucial!!
956
957 // set the flag telling to the main thread that we want to do some GUI
958 {
959 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
960
961 gs_nWaitingForGui++;
962 }
963
964 wxWakeUpMainThread();
965
966 // now we may block here because the main thread will soon let us in
967 // (during the next iteration of OnIdle())
968 gs_pCritsectGui->Enter();
969}
970
d90895ac
DW
971void WXDLLEXPORT wxMutexGuiLeave()
972{
43543d98 973 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
d90895ac
DW
974
975 if ( wxThread::IsMain() )
976 {
43543d98 977 gs_bGuiOwnedByMainThread = FALSE;
d90895ac
DW
978 }
979 else
980 {
981 // decrement the number of waiters now
43543d98 982 wxASSERT_MSG(gs_nWaitingForGui > 0,
d90895ac
DW
983 wxT("calling wxMutexGuiLeave() without entering it first?") );
984
43543d98 985 gs_nWaitingForGui--;
d90895ac
DW
986
987 wxWakeUpMainThread();
988 }
989
43543d98 990 gs_pCritsectGui->Leave();
d90895ac
DW
991}
992
993void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
994{
995 wxASSERT_MSG( wxThread::IsMain(),
996 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
997
43543d98 998 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
d90895ac 999
43543d98 1000 if (gs_nWaitingForGui == 0)
d90895ac
DW
1001 {
1002 // no threads are waiting for GUI - so we may acquire the lock without
1003 // any danger (but only if we don't already have it)
c5fb56c0 1004 if (!wxGuiOwnedByMainThread())
d90895ac 1005 {
43543d98 1006 gs_pCritsectGui->Enter();
d90895ac 1007
43543d98 1008 gs_bGuiOwnedByMainThread = TRUE;
d90895ac
DW
1009 }
1010 //else: already have it, nothing to do
1011 }
1012 else
1013 {
1014 // some threads are waiting, release the GUI lock if we have it
c5fb56c0 1015 if (wxGuiOwnedByMainThread())
d90895ac
DW
1016 {
1017 wxMutexGuiLeave();
1018 }
1019 //else: some other worker thread is doing GUI
1020 }
1021}
1022
1023bool WXDLLEXPORT wxGuiOwnedByMainThread()
1024{
43543d98 1025 return gs_bGuiOwnedByMainThread;
d90895ac
DW
1026}
1027
9ed0fac8
DW
1028bool WXDLLEXPORT wxIsWaitingForThread()
1029{
43543d98 1030 return gs_bWaitingForThread;
9ed0fac8
DW
1031}
1032
d1bab566
SN
1033// ----------------------------------------------------------------------------
1034// include common implementation code
1035// ----------------------------------------------------------------------------
1036
1037#include "wx/thrimpl.cpp"
1038
0e320a79
DW
1039#endif
1040 // wxUSE_THREADS