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