]> git.saurik.com Git - wxWidgets.git/blame - src/os2/thread.cpp
Add doc for wxGraphicsContext.Create(), which is a lightweight context with no target...
[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()
f9226383 60wxThreadIdType wxThread::ms_idMainThread = 0;
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 116 {
4c51a665 117 wxLogSysError(_("Cannot 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))
43b2d5e7 127 {
9a83f860 128 wxLogLastError(wxT("DosCloseMutexSem(mutex)"));
43b2d5e7 129 }
d1bab566 130 }
0e320a79
DW
131}
132
ee864b6d
SN
133wxMutexError wxMutexInternal::TryLock()
134{
135 const wxMutexError rc = LockTimeout( SEM_IMMEDIATE_RETURN );
136
137 // we have a special return code for timeout in this case
138 return rc == wxMUTEX_TIMEOUT ? wxMUTEX_BUSY : rc;
139}
140
d1bab566 141wxMutexError wxMutexInternal::LockTimeout(ULONG ulMilliseconds)
0e320a79 142{
c5fb56c0
DW
143 APIRET ulrc;
144
d1bab566 145 ulrc = ::DosRequestMutexSem(m_vMutex, ulMilliseconds);
d90895ac 146
c5fb56c0 147 switch (ulrc)
d90895ac 148 {
d1bab566 149 case ERROR_TIMEOUT:
ee864b6d 150 return wxMUTEX_TIMEOUT;
c5fb56c0 151 case ERROR_TOO_MANY_SEM_REQUESTS:
d90895ac
DW
152 return wxMUTEX_BUSY;
153
c5fb56c0 154 case NO_ERROR:
d90895ac
DW
155 // ok
156 break;
157
c5fb56c0
DW
158 case ERROR_INVALID_HANDLE:
159 case ERROR_INTERRUPT:
160 case ERROR_SEM_OWNER_DIED:
d90895ac
DW
161 wxLogSysError(_("Couldn't acquire a mutex lock"));
162 return wxMUTEX_MISC_ERROR;
163
d90895ac
DW
164 default:
165 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
d1bab566
SN
166 return wxMUTEX_MISC_ERROR;
167 }
0e320a79
DW
168 return wxMUTEX_NO_ERROR;
169}
170
d1bab566 171wxMutexError wxMutexInternal::Unlock()
0e320a79 172{
c5fb56c0
DW
173 APIRET ulrc;
174
d1bab566 175 ulrc = ::DosReleaseMutexSem(m_vMutex);
c5fb56c0 176 if (ulrc != 0)
d90895ac
DW
177 {
178 wxLogSysError(_("Couldn't release a mutex"));
179 return wxMUTEX_MISC_ERROR;
180 }
0e320a79
DW
181 return wxMUTEX_NO_ERROR;
182}
183
d1bab566
SN
184// --------------------------------------------------------------------------
185// wxSemaphore
186// --------------------------------------------------------------------------
d90895ac 187
d1bab566
SN
188// a trivial wrapper around OS2 event semaphore
189class wxSemaphoreInternal
d90895ac 190{
0e320a79 191public:
d1bab566
SN
192 wxSemaphoreInternal(int initialcount, int maxcount);
193 ~wxSemaphoreInternal();
d01cc696 194
d1bab566 195 bool IsOk() const { return m_vEvent != NULL; }
d01cc696 196
d1bab566
SN
197 wxSemaError Wait() { return WaitTimeout(SEM_INDEFINITE_WAIT); }
198 wxSemaError TryWait() { return WaitTimeout(SEM_IMMEDIATE_RETURN); }
199 wxSemaError WaitTimeout(unsigned long milliseconds);
d01cc696 200
d1bab566 201 wxSemaError Post();
d01cc696 202
d1bab566
SN
203private:
204 HEV m_vEvent;
205 HMTX m_vMutex;
206 int m_count;
207 int m_maxcount;
0e320a79
DW
208};
209
d1bab566 210wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
0e320a79 211{
d1bab566
SN
212 APIRET ulrc;
213 if ( maxcount == 0 )
d90895ac 214 {
d1bab566
SN
215 // make it practically infinite
216 maxcount = INT_MAX;
d90895ac 217 }
0e320a79 218
d1bab566
SN
219 m_count = initialcount;
220 m_maxcount = maxcount;
221 ulrc = ::DosCreateMutexSem(NULL, &m_vMutex, 0L, FALSE);
222 if (ulrc != 0)
47df2b8c 223 {
9a83f860 224 wxLogLastError(wxT("DosCreateMutexSem()"));
d1bab566
SN
225 m_vMutex = NULL;
226 m_vEvent = NULL;
227 return;
47df2b8c 228 }
d1bab566
SN
229 ulrc = ::DosCreateEventSem(NULL, &m_vEvent, 0L, FALSE);
230 if ( ulrc != 0)
47df2b8c 231 {
9a83f860 232 wxLogLastError(wxT("DosCreateEventSem()"));
d1bab566
SN
233 ::DosCloseMutexSem(m_vMutex);
234 m_vMutex = NULL;
235 m_vEvent = NULL;
47df2b8c 236 }
d1bab566
SN
237 if (initialcount)
238 ::DosPostEventSem(m_vEvent);
0e320a79
DW
239}
240
d1bab566 241wxSemaphoreInternal::~wxSemaphoreInternal()
0e320a79 242{
d1bab566 243 if ( m_vEvent )
d90895ac 244 {
d1bab566 245 if ( ::DosCloseEventSem(m_vEvent) )
d90895ac 246 {
9a83f860 247 wxLogLastError(wxT("DosCloseEventSem(semaphore)"));
d90895ac 248 }
d1bab566
SN
249 if ( ::DosCloseMutexSem(m_vMutex) )
250 {
9a83f860 251 wxLogLastError(wxT("DosCloseMutexSem(semaphore)"));
d1bab566
SN
252 }
253 else
254 m_vEvent = NULL;
47df2b8c 255 }
0e320a79
DW
256}
257
d1bab566 258wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long ulMilliseconds)
892b89f3 259{
d1bab566
SN
260 APIRET ulrc;
261 do {
262 ulrc = ::DosWaitEventSem(m_vEvent, ulMilliseconds );
263 switch ( ulrc )
264 {
265 case NO_ERROR:
266 break;
267
268 case ERROR_TIMEOUT:
269 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
270 return wxSEMA_BUSY;
271 else
272 return wxSEMA_TIMEOUT;
273
274 default:
9a83f860 275 wxLogLastError(wxT("DosWaitEventSem(semaphore)"));
d1bab566
SN
276 return wxSEMA_MISC_ERROR;
277 }
278 ulrc = :: DosRequestMutexSem(m_vMutex, ulMilliseconds);
279 switch ( ulrc )
280 {
281 case NO_ERROR:
282 // ok
283 break;
284
285 case ERROR_TIMEOUT:
286 case ERROR_TOO_MANY_SEM_REQUESTS:
287 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
288 return wxSEMA_BUSY;
289 else
290 return wxSEMA_TIMEOUT;
291
292 default:
293 wxFAIL_MSG(wxT("DosRequestMutexSem(mutex)"));
294 return wxSEMA_MISC_ERROR;
295 }
296 bool OK = false;
297 if (m_count > 0)
298 {
299 m_count--;
300 OK = true;
301 }
302 else
303 {
304 ULONG ulPostCount;
305 ::DosResetEventSem(m_vEvent, &ulPostCount);
306 }
307 ::DosReleaseMutexSem(m_vMutex);
308 if (OK)
309 return wxSEMA_NO_ERROR;
310 } while (ulMilliseconds == SEM_INDEFINITE_WAIT);
311
312 if (ulMilliseconds == SEM_IMMEDIATE_RETURN)
313 return wxSEMA_BUSY;
314 return wxSEMA_TIMEOUT;
892b89f3
DW
315}
316
d1bab566 317wxSemaError wxSemaphoreInternal::Post()
892b89f3 318{
d1bab566
SN
319 APIRET ulrc;
320 ulrc = ::DosRequestMutexSem(m_vMutex, SEM_INDEFINITE_WAIT);
321 if (ulrc != NO_ERROR)
322 return wxSEMA_MISC_ERROR;
323 bool OK = false;
324 if (m_count < m_maxcount)
325 {
326 m_count++;
327 ulrc = ::DosPostEventSem(m_vEvent);
328 OK = true;
329 }
330 ::DosReleaseMutexSem(m_vMutex);
331 if (!OK)
332 return wxSEMA_OVERFLOW;
333 if ( ulrc != NO_ERROR && ulrc != ERROR_ALREADY_POSTED )
334 {
9a83f860 335 wxLogLastError(wxT("DosPostEventSem(semaphore)"));
892b89f3 336
d1bab566
SN
337 return wxSEMA_MISC_ERROR;
338 }
892b89f3 339
d1bab566 340 return wxSEMA_NO_ERROR;
892b89f3
DW
341}
342
d90895ac
DW
343// ----------------------------------------------------------------------------
344// wxThread implementation
345// ----------------------------------------------------------------------------
346
347// wxThreadInternal class
348// ----------------------
349
350class wxThreadInternal
351{
352public:
c5fb56c0 353 inline wxThreadInternal()
d90895ac
DW
354 {
355 m_hThread = 0;
c5fb56c0 356 m_eState = STATE_NEW;
90e95e61 357 m_nPriority = wxPRIORITY_DEFAULT;
d90895ac
DW
358 }
359
d01cc696
DW
360 ~wxThreadInternal()
361 {
d1bab566 362 m_hThread = 0;
d01cc696
DW
363 }
364
d90895ac 365 // create a new (suspended) thread (for the given thread object)
793c7f9b
DW
366 bool Create( wxThread* pThread
367 ,unsigned int uStackSize
368 );
d90895ac
DW
369
370 // suspend/resume/terminate
371 bool Suspend();
372 bool Resume();
c5fb56c0 373 inline void Cancel() { m_eState = STATE_CANCELED; }
d90895ac
DW
374
375 // thread state
c5fb56c0
DW
376 inline void SetState(wxThreadState eState) { m_eState = eState; }
377 inline wxThreadState GetState() const { return m_eState; }
d90895ac
DW
378
379 // thread priority
d01cc696 380 void SetPriority(unsigned int nPriority);
c5fb56c0 381 inline unsigned int GetPriority() const { return m_nPriority; }
d90895ac
DW
382
383 // thread handle and id
c5fb56c0
DW
384 inline TID GetHandle() const { return m_hThread; }
385 TID GetId() const { return m_hThread; }
d90895ac
DW
386
387 // thread function
f877815e 388 static void OS2ThreadStart(void* pParam);
d90895ac
DW
389
390private:
c5fb56c0
DW
391 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
392 // PM also has no real Tls mechanism to index pointers by so we'll just
77ffb593 393 // keep track of the wxWidgets parent object here.
c5fb56c0
DW
394 TID m_hThread; // handle and ID of the thread
395 wxThreadState m_eState; // state, see wxThreadState enum
396 unsigned int m_nPriority; // thread priority in "wx" units
d90895ac
DW
397};
398
55034339 399void wxThreadInternal::OS2ThreadStart( void * pParam )
d90895ac 400{
55034339 401 DWORD dwRet;
d1bab566 402 bool bWasCancelled;
d90895ac 403
f877815e
SN
404 wxThread *pThread = (wxThread *)pParam;
405
406 // first of all, wait for the thread to be started.
407 pThread->m_critsect.Enter();
408 pThread->m_critsect.Leave();
409 // Now check whether we hadn't been cancelled already and don't
410 // start the user code at all in this case.
d1bab566
SN
411 if ( pThread->m_internal->GetState() == STATE_EXITED )
412 {
413 dwRet = (DWORD)-1;
6670f564 414 bWasCancelled = true;
d1bab566
SN
415 }
416 else // do run thread
417 {
737928c2
SN
418 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
419 unsigned long ulHab;
17b35e1d
SN
420 if (traits)
421 traits->InitializeGui(ulHab);
d1bab566 422 dwRet = (DWORD)pThread->Entry();
17b35e1d
SN
423 if (traits)
424 traits->TerminateGui(ulHab);
d01cc696 425
17b35e1d
SN
426 // enter m_critsect before changing the thread state
427 pThread->m_critsect.Enter();
d01cc696 428
17b35e1d 429 bWasCancelled = pThread->m_internal->GetState() == STATE_CANCELED;
d01cc696 430
17b35e1d
SN
431 pThread->m_internal->SetState(STATE_EXITED);
432 pThread->m_critsect.Leave();
d1bab566 433 }
c5fb56c0 434 pThread->OnExit();
d90895ac 435
d01cc696
DW
436 // if the thread was cancelled (from Delete()), then it the handle is still
437 // needed there
438 if (pThread->IsDetached() && !bWasCancelled)
439 {
440 // auto delete
43543d98 441 delete pThread;
d01cc696
DW
442 }
443 //else: the joinable threads handle will be closed when Wait() is done
f877815e 444 return;
d90895ac
DW
445}
446
d01cc696
DW
447void wxThreadInternal::SetPriority(
448 unsigned int nPriority
c5fb56c0 449)
d90895ac 450{
77ffb593 451 // translate wxWidgets priority to the PM one
d1bab566
SN
452 ULONG ulOS2_PriorityClass;
453 ULONG ulOS2_SubPriority;
43543d98 454 ULONG ulrc;
c5fb56c0 455
d01cc696 456 m_nPriority = nPriority;
d1bab566
SN
457 if (m_nPriority <= 25)
458 ulOS2_PriorityClass = PRTYC_IDLETIME;
459 else if (m_nPriority <= 50)
460 ulOS2_PriorityClass = PRTYC_REGULAR;
461 else if (m_nPriority <= 75)
462 ulOS2_PriorityClass = PRTYC_TIMECRITICAL;
c5fb56c0 463 else if (m_nPriority <= 100)
d1bab566 464 ulOS2_PriorityClass = PRTYC_FOREGROUNDSERVER;
d90895ac
DW
465 else
466 {
467 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
d1bab566 468 ulOS2_PriorityClass = PRTYC_REGULAR;
d90895ac 469 }
d1bab566 470 ulOS2_SubPriority = (ULONG) (((m_nPriority - 1) % 25 + 1) * 31.0 / 25);
c5fb56c0 471 ulrc = ::DosSetPriority( PRTYS_THREAD
d1bab566
SN
472 ,ulOS2_PriorityClass
473 ,ulOS2_SubPriority
c5fb56c0
DW
474 ,(ULONG)m_hThread
475 );
476 if (ulrc != 0)
d90895ac
DW
477 {
478 wxLogSysError(_("Can't set thread priority"));
479 }
d01cc696
DW
480}
481
6670f564
WS
482bool wxThreadInternal::Create( wxThread* pThread,
483 unsigned int uStackSize)
d01cc696 484{
6670f564 485 int tid;
17b35e1d 486
f877815e 487 if (!uStackSize)
6670f564
WS
488 uStackSize = 131072;
489
f877815e
SN
490 pThread->m_critsect.Enter();
491 tid = _beginthread(wxThreadInternal::OS2ThreadStart,
17b35e1d 492 NULL, uStackSize, pThread);
f877815e 493 if(tid == -1)
d01cc696
DW
494 {
495 wxLogSysError(_("Can't create thread"));
496
6670f564 497 return false;
d01cc696 498 }
f877815e 499 m_hThread = tid;
90e95e61 500 if (m_nPriority != wxPRIORITY_DEFAULT)
d01cc696
DW
501 {
502 SetPriority(m_nPriority);
503 }
1dfc3cda 504
6670f564 505 return true;
d90895ac
DW
506}
507
508bool wxThreadInternal::Suspend()
509{
6670f564 510 ULONG ulrc = ::DosSuspendThread(m_hThread);
d90895ac 511
c5fb56c0
DW
512 if (ulrc != 0)
513 {
4c51a665 514 wxLogSysError(_("Cannot suspend thread %lu"), m_hThread);
6670f564 515 return false;
d90895ac 516 }
c5fb56c0 517 m_eState = STATE_PAUSED;
6670f564
WS
518
519 return true;
d90895ac
DW
520}
521
522bool wxThreadInternal::Resume()
523{
6670f564 524 ULONG ulrc = ::DosResumeThread(m_hThread);
d90895ac 525
c5fb56c0
DW
526 if (ulrc != 0)
527 {
4c51a665 528 wxLogSysError(_("Cannot resume thread %lu"), m_hThread);
6670f564 529 return false;
d90895ac 530 }
d1bab566
SN
531
532 // don't change the state from STATE_EXITED because it's special and means
533 // we are going to terminate without running any user code - if we did it,
534 // the codei n Delete() wouldn't work
535 if ( m_eState != STATE_EXITED )
536 {
537 m_eState = STATE_RUNNING;
538 }
539
6670f564 540 return true;
d90895ac
DW
541}
542
543// static functions
544// ----------------
545
546wxThread *wxThread::This()
547{
c5fb56c0
DW
548 wxThread* pThread = m_pThread;
549 return pThread;
d90895ac
DW
550}
551
d90895ac
DW
552#ifdef Yield
553 #undef Yield
554#endif
555
556void wxThread::Yield()
557{
d90895ac
DW
558 ::DosSleep(0);
559}
560
d1bab566
SN
561int wxThread::GetCPUCount()
562{
563 ULONG CPUCount;
564 APIRET ulrc;
565 ulrc = ::DosQuerySysInfo(26, 26, (void *)&CPUCount, sizeof(ULONG));
566 // QSV_NUMPROCESSORS(26) is typically not defined in header files
567
568 if (ulrc != 0)
569 CPUCount = 1;
570
571 return CPUCount;
572}
573
f9226383 574wxThreadIdType wxThread::GetCurrentId()
d1bab566
SN
575{
576 PTIB ptib;
577 PPIB ppib;
578
579 ::DosGetInfoBlocks(&ptib, &ppib);
f9226383 580 return (wxThreadIdType) ptib->tib_ptib2->tib2_ultid;
d1bab566
SN
581}
582
583bool wxThread::SetConcurrency(size_t level)
584{
9a83f860 585 wxASSERT_MSG( IsMain(), wxT("should only be called from the main thread") );
d1bab566
SN
586
587 // ok only for the default one
588 if ( level == 0 )
589 return 0;
590
591 // Don't know how to realize this on OS/2.
592 return level == 1;
593}
594
d01cc696
DW
595// ctor and dtor
596// -------------
597
598wxThread::wxThread(wxThreadKind kind)
599{
600 m_internal = new wxThreadInternal();
601
602 m_isDetached = kind == wxTHREAD_DETACHED;
603}
604
605wxThread::~wxThread()
606{
607 delete m_internal;
608}
609
d90895ac
DW
610// create/start thread
611// -------------------
612
793c7f9b
DW
613wxThreadError wxThread::Create(
614 unsigned int uStackSize
615)
0e320a79 616{
d1bab566
SN
617 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
618
793c7f9b 619 if ( !m_internal->Create(this, uStackSize) )
d90895ac
DW
620 return wxTHREAD_NO_RESOURCE;
621
0e320a79
DW
622 return wxTHREAD_NO_ERROR;
623}
624
d90895ac 625wxThreadError wxThread::Run()
0e320a79 626{
c5fb56c0 627 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
d90895ac 628
2e57ca64
VS
629 // Create the thread if it wasn't created yet with an explicit
630 // Create() call:
631 if ( !m_internal->GetHandle() )
632 {
633 if ( !m_internal->Create(this, 0) )
634 return wxTHREAD_NO_RESOURCE;
635 }
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
b95a7c31 672wxThread::ExitCode wxThread::Wait(wxThreadWait waitMode)
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,
9a83f860 677 wxT("can't wait for detached thread") );
d01cc696 678 ExitCode rc = (ExitCode)-1;
b95a7c31 679 (void)Delete(&rc, waitMode);
d01cc696
DW
680 return(rc);
681}
682
b95a7c31 683wxThreadError wxThread::Delete(ExitCode *pRc, wxThreadWait WXUNUSED(waitMode))
d01cc696
DW
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
f9226383 937 wxThread::ms_idMainThread = wxThread::GetCurrentId();
d90895ac 938
6670f564 939 return true;
d90895ac
DW
940}
941
942void wxThreadModule::OnExit()
943{
43543d98 944 if (gs_pCritsectGui)
d90895ac 945 {
43543d98 946 gs_pCritsectGui->Leave();
f6bcfd97 947#if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
43543d98 948 delete gs_pCritsectGui;
f6bcfd97 949#endif
43543d98 950 gs_pCritsectGui = NULL;
d90895ac
DW
951 }
952
f6bcfd97 953#if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
43543d98 954 wxDELETE(gs_pCritsectWaitingForGui);
f6bcfd97 955#endif
d90895ac
DW
956}
957
958// ----------------------------------------------------------------------------
c5fb56c0 959// Helper functions
d90895ac
DW
960// ----------------------------------------------------------------------------
961
d1bab566 962// wake up the main thread if it's in ::GetMessage()
c5fb56c0 963void WXDLLEXPORT wxWakeUpMainThread()
d90895ac 964{
8e5052fa 965#if 0
d1bab566
SN
966 if ( !::WinPostQueueMsg(wxTheApp->m_hMq, WM_NULL, 0, 0) )
967 {
968 // should never happen
969 wxLogLastError(wxT("WinPostMessage(WM_NULL)"));
970 }
8e5052fa 971#endif
d90895ac
DW
972}
973
d254213e 974void wxMutexGuiEnterImpl()
28a75c29
SN
975{
976 // this would dead lock everything...
977 wxASSERT_MSG( !wxThread::IsMain(),
978 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
979
980 // the order in which we enter the critical sections here is crucial!!
981
982 // set the flag telling to the main thread that we want to do some GUI
983 {
984 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
985
986 gs_nWaitingForGui++;
987 }
988
989 wxWakeUpMainThread();
990
991 // now we may block here because the main thread will soon let us in
992 // (during the next iteration of OnIdle())
993 gs_pCritsectGui->Enter();
994}
995
d254213e 996void wxMutexGuiLeaveImpl()
d90895ac 997{
43543d98 998 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
d90895ac
DW
999
1000 if ( wxThread::IsMain() )
1001 {
6670f564 1002 gs_bGuiOwnedByMainThread = false;
d90895ac
DW
1003 }
1004 else
1005 {
1006 // decrement the number of waiters now
43543d98 1007 wxASSERT_MSG(gs_nWaitingForGui > 0,
d90895ac
DW
1008 wxT("calling wxMutexGuiLeave() without entering it first?") );
1009
43543d98 1010 gs_nWaitingForGui--;
d90895ac
DW
1011
1012 wxWakeUpMainThread();
1013 }
1014
43543d98 1015 gs_pCritsectGui->Leave();
d90895ac
DW
1016}
1017
1018void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1019{
1020 wxASSERT_MSG( wxThread::IsMain(),
1021 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1022
43543d98 1023 wxCriticalSectionLocker enter(*gs_pCritsectWaitingForGui);
d90895ac 1024
43543d98 1025 if (gs_nWaitingForGui == 0)
d90895ac
DW
1026 {
1027 // no threads are waiting for GUI - so we may acquire the lock without
1028 // any danger (but only if we don't already have it)
c5fb56c0 1029 if (!wxGuiOwnedByMainThread())
d90895ac 1030 {
43543d98 1031 gs_pCritsectGui->Enter();
d90895ac 1032
6670f564 1033 gs_bGuiOwnedByMainThread = true;
d90895ac
DW
1034 }
1035 //else: already have it, nothing to do
1036 }
1037 else
1038 {
1039 // some threads are waiting, release the GUI lock if we have it
c5fb56c0 1040 if (wxGuiOwnedByMainThread())
d90895ac
DW
1041 {
1042 wxMutexGuiLeave();
1043 }
1044 //else: some other worker thread is doing GUI
1045 }
1046}
1047
1048bool WXDLLEXPORT wxGuiOwnedByMainThread()
1049{
43543d98 1050 return gs_bGuiOwnedByMainThread;
d90895ac
DW
1051}
1052
9ed0fac8
DW
1053bool WXDLLEXPORT wxIsWaitingForThread()
1054{
43543d98 1055 return gs_bWaitingForThread;
9ed0fac8
DW
1056}
1057
d1bab566
SN
1058// ----------------------------------------------------------------------------
1059// include common implementation code
1060// ----------------------------------------------------------------------------
1061
1062#include "wx/thrimpl.cpp"
1063
0e320a79
DW
1064#endif
1065 // wxUSE_THREADS