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