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