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