]> git.saurik.com Git - wxWidgets.git/blame - src/msw/thread.cpp
don't include winsock.h directly, this doesn't work (patch 565655)
[wxWidgets.git] / src / msw / thread.cpp
CommitLineData
2bda0e17 1/////////////////////////////////////////////////////////////////////////////
9e84b847 2// Name: src/msw/thread.cpp
2bda0e17
KB
3// Purpose: wxThread Implementation
4// Author: Original from Wolfram Gloger/Guilhem Lavaux
bee503b0 5// Modified by: Vadim Zeitlin to make it work :-)
2bda0e17
KB
6// Created: 04/22/98
7// RCS-ID: $Id$
9e84b847
VZ
8// Copyright: (c) Wolfram Gloger (1996, 1997), Guilhem Lavaux (1998);
9// Vadim Zeitlin (1999-2002)
2bda0e17
KB
10// Licence: wxWindows licence
11/////////////////////////////////////////////////////////////////////////////
12
13#ifdef __GNUG__
3222fde2 14 #pragma implementation "thread.h"
2bda0e17
KB
15#endif
16
3222fde2
VZ
17// ----------------------------------------------------------------------------
18// headers
19// ----------------------------------------------------------------------------
20
a3b46648 21// For compilers that support precompilation, includes "wx.h".
2bda0e17
KB
22#include "wx/wxprec.h"
23
24#if defined(__BORLANDC__)
3222fde2 25 #pragma hdrstop
2bda0e17
KB
26#endif
27
28#ifndef WX_PRECOMP
e0256755 29# include "wx/wx.h"
2bda0e17
KB
30#endif
31
3222fde2
VZ
32#if wxUSE_THREADS
33
0d0512bd 34#include "wx/msw/private.h"
3222fde2 35
2bda0e17
KB
36#include "wx/module.h"
37#include "wx/thread.h"
38
b568d04f
VZ
39// must have this symbol defined to get _beginthread/_endthread declarations
40#ifndef _MT
41 #define _MT
42#endif
43
9f51f2b6
VZ
44#if defined(__BORLANDC__)
45 #if !defined(__MT__)
46 // I can't set -tWM in the IDE (anyone?) so have to do this
47 #define __MT__
48 #endif
49
50 #if !defined(__MFC_COMPAT__)
51 // Needed to know about _beginthreadex etc..
52 #define __MFC_COMPAT__
53 #endif
54#endif // BC++
55
56// define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
57// which should be used instead of Win32 ::CreateThread() if possible
e0256755
GRG
58#if defined(__VISUALC__) || \
59 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
9f51f2b6 60 (defined(__GNUG__) && defined(__MSVCRT__)) || \
ba14d986 61 defined(__WATCOMC__) || defined(__MWERKS__)
ccebc98a 62
9f51f2b6
VZ
63 #undef wxUSE_BEGIN_THREAD
64 #define wxUSE_BEGIN_THREAD
8536082d
BJ
65#endif
66
9f51f2b6
VZ
67#ifdef wxUSE_BEGIN_THREAD
68 // this is where _beginthreadex() is declared
b568d04f 69 #include <process.h>
9f51f2b6
VZ
70
71 // the return type of the thread function entry point
72 typedef unsigned THREAD_RETVAL;
73
74 // the calling convention of the thread function entry point
75 #define THREAD_CALLCONV __stdcall
76#else
77 // the settings for CreateThread()
78 typedef DWORD THREAD_RETVAL;
79 #define THREAD_CALLCONV WINAPI
b568d04f
VZ
80#endif
81
82// ----------------------------------------------------------------------------
83// constants
84// ----------------------------------------------------------------------------
85
bf1852e1
VZ
86// the possible states of the thread ("=>" shows all possible transitions from
87// this state)
88enum wxThreadState
89{
90 STATE_NEW, // didn't start execution yet (=> RUNNING)
91 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
92 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
93 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
94 STATE_EXITED // thread is terminating
2bda0e17
KB
95};
96
3222fde2 97// ----------------------------------------------------------------------------
b568d04f 98// this module globals
3222fde2 99// ----------------------------------------------------------------------------
2bda0e17 100
bf1852e1 101// TLS index of the slot where we store the pointer to the current thread
b568d04f 102static DWORD gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 103
3222fde2
VZ
104// id of the main thread - the one which can call GUI functions without first
105// calling wxMutexGuiEnter()
b568d04f 106static DWORD gs_idMainThread = 0;
bee503b0
VZ
107
108// if it's FALSE, some secondary thread is holding the GUI lock
b568d04f 109static bool gs_bGuiOwnedByMainThread = TRUE;
2bda0e17 110
3222fde2
VZ
111// critical section which controls access to all GUI functions: any secondary
112// thread (i.e. except the main one) must enter this crit section before doing
113// any GUI calls
b568d04f 114static wxCriticalSection *gs_critsectGui = NULL;
bee503b0 115
b568d04f
VZ
116// critical section which protects gs_nWaitingForGui variable
117static wxCriticalSection *gs_critsectWaitingForGui = NULL;
bee503b0
VZ
118
119// number of threads waiting for GUI in wxMutexGuiEnter()
b568d04f 120static size_t gs_nWaitingForGui = 0;
2bda0e17 121
bf1852e1 122// are we waiting for a thread termination?
b568d04f 123static bool gs_waitingForThread = FALSE;
bf1852e1 124
3222fde2 125// ============================================================================
9e84b847 126// Windows implementation of thread and related classes
3222fde2
VZ
127// ============================================================================
128
129// ----------------------------------------------------------------------------
9e84b847
VZ
130// wxCriticalSection
131// ----------------------------------------------------------------------------
132
133wxCriticalSection::wxCriticalSection()
134{
135 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION) <= sizeof(m_buffer),
136 wxCriticalSectionBufferTooSmall );
137
138 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
139}
140
141wxCriticalSection::~wxCriticalSection()
142{
143 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
144}
145
146void wxCriticalSection::Enter()
147{
148 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
149}
150
151void wxCriticalSection::Leave()
152{
153 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
154}
155
156// ----------------------------------------------------------------------------
157// wxMutex
3222fde2 158// ----------------------------------------------------------------------------
0d0512bd 159
3222fde2
VZ
160class wxMutexInternal
161{
2bda0e17 162public:
9e84b847
VZ
163 wxMutexInternal(wxMutexType mutexType);
164 ~wxMutexInternal();
7f684264 165
9e84b847
VZ
166 bool IsOk() const { return m_mutex != NULL; }
167
168 wxMutexError Lock() { return LockTimeout(INFINITE); }
169 wxMutexError TryLock() { return LockTimeout(0); }
170 wxMutexError Unlock();
171
172private:
173 wxMutexError LockTimeout(DWORD milliseconds);
7f684264 174
7f684264 175 HANDLE m_mutex;
2bda0e17
KB
176};
177
9e84b847
VZ
178// all mutexes are recursive under Win32 so we don't use mutexType
179wxMutexInternal::wxMutexInternal(wxMutexType WXUNUSED(mutexType))
2bda0e17 180{
9e84b847
VZ
181 // create a nameless (hence intra process and always private) mutex
182 m_mutex = ::CreateMutex
183 (
184 NULL, // default secutiry attributes
185 FALSE, // not initially locked
186 NULL // no name
187 );
a6b0bd49 188
9e84b847
VZ
189 if ( !m_mutex )
190 {
191 wxLogLastError(_T("CreateMutex()"));
192 }
2bda0e17
KB
193}
194
9e84b847 195wxMutexInternal::~wxMutexInternal()
2bda0e17 196{
9e84b847 197 if ( m_mutex )
7f684264 198 {
9e84b847
VZ
199 if ( !::CloseHandle(m_mutex) )
200 {
201 wxLogLastError(_T("CloseHandle(mutex)"));
202 }
7f684264 203 }
2bda0e17
KB
204}
205
9e84b847 206wxMutexError wxMutexInternal::LockTimeout(DWORD milliseconds)
2bda0e17 207{
9e84b847
VZ
208 DWORD rc = ::WaitForSingleObject(m_mutex, milliseconds);
209 if ( rc == WAIT_ABANDONED )
3222fde2 210 {
9e84b847
VZ
211 // the previous caller died without releasing the mutex, but now we can
212 // really lock it
213 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
214
215 // use 0 timeout, normally we should always get it
216 rc = ::WaitForSingleObject(m_mutex, 0);
217 }
3222fde2 218
9e84b847
VZ
219 switch ( rc )
220 {
3222fde2
VZ
221 case WAIT_OBJECT_0:
222 // ok
223 break;
2bda0e17 224
3222fde2 225 case WAIT_TIMEOUT:
9e84b847
VZ
226 return wxMUTEX_BUSY;
227
228 case WAIT_ABANDONED: // checked for above
3222fde2 229 default:
223d09f6 230 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
9e84b847 231 // fall through
3222fde2 232
9e84b847
VZ
233 case WAIT_FAILED:
234 wxLogLastError(_T("WaitForSingleObject(mutex)"));
235 return wxMUTEX_MISC_ERROR;
236 }
2bda0e17 237
3222fde2 238 return wxMUTEX_NO_ERROR;
2bda0e17
KB
239}
240
9e84b847 241wxMutexError wxMutexInternal::Unlock()
2bda0e17 242{
9e84b847 243 if ( !::ReleaseMutex(m_mutex) )
3222fde2 244 {
9e84b847
VZ
245 wxLogLastError(_("ReleaseMutex()"));
246
3222fde2
VZ
247 return wxMUTEX_MISC_ERROR;
248 }
a6b0bd49 249
3222fde2 250 return wxMUTEX_NO_ERROR;
2bda0e17
KB
251}
252
be809868 253// --------------------------------------------------------------------------
9e84b847 254// wxSemaphore
be809868
VZ
255// --------------------------------------------------------------------------
256
9e84b847 257// a trivial wrapper around Win32 semaphore
be809868 258class wxSemaphoreInternal
3222fde2 259{
2bda0e17 260public:
9e84b847 261 wxSemaphoreInternal(int initialcount, int maxcount);
be809868
VZ
262 ~wxSemaphoreInternal();
263
9e84b847 264 bool IsOk() const { return m_semaphore != NULL; }
be809868 265
9e84b847
VZ
266 wxSemaError Wait() { return WaitTimeout(INFINITE); }
267 wxSemaError TryWait() { return WaitTimeout(0); }
268 wxSemaError WaitTimeout(unsigned long milliseconds);
be809868 269
9e84b847 270 wxSemaError Post();
be809868
VZ
271
272private:
273 HANDLE m_semaphore;
274};
275
9e84b847 276wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
be809868
VZ
277{
278 if ( maxcount == 0 )
b568d04f 279 {
be809868
VZ
280 // make it practically infinite
281 maxcount = INT_MAX;
282 }
4d1c1c3c 283
9e84b847
VZ
284 m_semaphore = ::CreateSemaphore
285 (
286 NULL, // default security attributes
287 initialcount,
288 maxcount,
289 NULL // no name
290 );
291
be809868
VZ
292 if ( !m_semaphore )
293 {
294 wxLogLastError(_T("CreateSemaphore()"));
b568d04f 295 }
be809868
VZ
296}
297
298wxSemaphoreInternal::~wxSemaphoreInternal()
299{
9e84b847 300 if ( m_semaphore )
b568d04f 301 {
9e84b847
VZ
302 if ( !::CloseHandle(m_semaphore) )
303 {
304 wxLogLastError(_T("CloseHandle(semaphore)"));
305 }
be809868
VZ
306 }
307}
b568d04f 308
9e84b847 309wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds)
be809868 310{
9e84b847 311 DWORD rc = ::WaitForSingleObject( m_semaphore, milliseconds );
be809868 312
9e84b847 313 switch ( rc )
be809868
VZ
314 {
315 case WAIT_OBJECT_0:
9e84b847 316 return wxSEMA_NO_ERROR;
b568d04f 317
be809868 318 case WAIT_TIMEOUT:
9e84b847 319 return wxSEMA_BUSY;
be809868
VZ
320
321 default:
9e84b847 322 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
b568d04f
VZ
323 }
324
9e84b847 325 return wxSEMA_MISC_ERROR;
be809868
VZ
326}
327
9e84b847 328wxSemaError wxSemaphoreInternal::Post()
be809868 329{
9e84b847 330 if ( !::ReleaseSemaphore(m_semaphore, 1, NULL /* ptr to previous count */) )
4d1c1c3c 331 {
be809868 332 wxLogLastError(_T("ReleaseSemaphore"));
be809868 333
9e84b847
VZ
334 return wxSEMA_MISC_ERROR;
335 }
be809868 336
9e84b847 337 return wxSEMA_NO_ERROR;
be809868 338}
4d1c1c3c 339
be809868 340// --------------------------------------------------------------------------
9e84b847 341// wxCondition
be809868
VZ
342// --------------------------------------------------------------------------
343
9e84b847
VZ
344// Win32 doesn't have explicit support for the POSIX condition variables and
345// the Win32 events have quite different semantics, so we reimplement the
346// conditions from scratch using the mutexes and semaphores
be809868
VZ
347class wxConditionInternal
348{
349public:
c112e100 350 wxConditionInternal(wxMutex& mutex);
be809868 351
9e84b847 352 bool IsOk() const { return m_mutex.IsOk() && m_semaphore.IsOk(); }
be809868 353
9e84b847
VZ
354 wxCondError Wait();
355 wxCondError WaitTimeout(unsigned long milliseconds);
be809868 356
9e84b847
VZ
357 wxCondError Signal();
358 wxCondError Broadcast();
be809868
VZ
359
360private:
9e84b847
VZ
361 // the number of threads currently waiting for this condition
362 LONG m_numWaiters;
be809868 363
9e84b847
VZ
364 // the critical section protecting m_numWaiters
365 wxCriticalSection m_csWaiters;
be809868 366
9e84b847 367 wxMutex& m_mutex;
be809868
VZ
368 wxSemaphore m_semaphore;
369};
370
c112e100
VZ
371wxConditionInternal::wxConditionInternal(wxMutex& mutex)
372 : m_mutex(mutex)
be809868 373{
9e84b847
VZ
374 // another thread can't access it until we return from ctor, so no need to
375 // protect access to m_numWaiters here
be809868
VZ
376 m_numWaiters = 0;
377}
378
9e84b847 379wxCondError wxConditionInternal::Wait()
be809868
VZ
380{
381 // increment the number of waiters
9e84b847 382 ::InterlockedIncrement(&m_numWaiters);
be809868 383
c112e100 384 m_mutex.Unlock();
be809868
VZ
385
386 // a potential race condition can occur here
387 //
388 // after a thread increments nwaiters, and unlocks the mutex and before the
389 // semaphore.Wait() is called, if another thread can cause a signal to be
390 // generated
391 //
392 // this race condition is handled by using a semaphore and incrementing the
393 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
394 // can 'remember' signals the race condition will not occur
395
396 // wait ( if necessary ) and decrement semaphore
9e84b847 397 wxSemaError err = m_semaphore.Wait();
c112e100 398 m_mutex.Lock();
9e84b847
VZ
399
400 return err == wxSEMA_NO_ERROR ? wxCOND_NO_ERROR : wxCOND_MISC_ERROR;
be809868
VZ
401}
402
9e84b847 403wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds)
be809868 404{
9e84b847 405 ::InterlockedIncrement(&m_numWaiters);
be809868 406
c112e100 407 m_mutex.Unlock();
be809868
VZ
408
409 // a race condition can occur at this point in the code
410 //
411 // please see the comments in Wait(), for details
412
9e84b847 413 wxSemaError err = m_semaphore.WaitTimeout(milliseconds);
be809868 414
9e84b847 415 if ( err == wxSEMA_BUSY )
4d1c1c3c 416 {
be809868
VZ
417 // another potential race condition exists here it is caused when a
418 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
419 // has not yet decremented 'nwaiters'.
420 //
421 // at this point if another thread calls signal() then the semaphore
422 // will be incremented, but the waiting thread will miss it.
423 //
424 // to handle this particular case, the waiting thread calls
425 // WaitForSingleObject again with a timeout of 0, after locking
426 // 'nwaiters_mutex'. this call does not block because of the zero
427 // timeout, but will allow the waiting thread to catch the missed
428 // signals.
9e84b847
VZ
429 wxCriticalSectionLocker lock(m_csWaiters);
430
431 err = m_semaphore.WaitTimeout(0);
be809868 432
9e84b847 433 if ( err != wxSEMA_NO_ERROR )
4d1c1c3c 434 {
be809868 435 m_numWaiters--;
4d1c1c3c
VZ
436 }
437 }
438
c112e100 439 m_mutex.Lock();
be809868 440
9e84b847 441 return err == wxSEMA_NO_ERROR ? wxCOND_NO_ERROR : wxCOND_MISC_ERROR;
be809868
VZ
442}
443
9e84b847 444wxCondError wxConditionInternal::Signal()
be809868 445{
9e84b847 446 wxCriticalSectionLocker lock(m_csWaiters);
be809868
VZ
447
448 if ( m_numWaiters > 0 )
b568d04f 449 {
be809868 450 // increment the semaphore by 1
9e84b847
VZ
451 if ( m_semaphore.Post() != wxSEMA_NO_ERROR )
452 return wxCOND_MISC_ERROR;
be809868
VZ
453
454 m_numWaiters--;
b568d04f
VZ
455 }
456
9e84b847 457 return wxCOND_NO_ERROR;
be809868 458}
4d1c1c3c 459
9e84b847 460wxCondError wxConditionInternal::Broadcast()
be809868 461{
9e84b847 462 wxCriticalSectionLocker lock(m_csWaiters);
2bda0e17 463
be809868
VZ
464 while ( m_numWaiters > 0 )
465 {
9e84b847
VZ
466 if ( m_semaphore.Post() != wxSEMA_NO_ERROR )
467 return wxCOND_MISC_ERROR;
468
be809868
VZ
469 m_numWaiters--;
470 }
471
9e84b847 472 return wxCOND_NO_ERROR;
3222fde2
VZ
473}
474
475// ----------------------------------------------------------------------------
476// wxThread implementation
477// ----------------------------------------------------------------------------
478
bf1852e1
VZ
479// wxThreadInternal class
480// ----------------------
481
3222fde2
VZ
482class wxThreadInternal
483{
2bda0e17 484public:
bf1852e1
VZ
485 wxThreadInternal()
486 {
487 m_hThread = 0;
488 m_state = STATE_NEW;
489 m_priority = WXTHREAD_DEFAULT_PRIORITY;
490 }
491
b568d04f
VZ
492 ~wxThreadInternal()
493 {
494 Free();
495 }
496
497 void Free()
498 {
499 if ( m_hThread )
500 {
501 if ( !::CloseHandle(m_hThread) )
502 {
f6bcfd97 503 wxLogLastError(wxT("CloseHandle(thread)"));
b568d04f
VZ
504 }
505
506 m_hThread = 0;
507 }
508 }
509
bf1852e1 510 // create a new (suspended) thread (for the given thread object)
6fe73788 511 bool Create(wxThread *thread, unsigned int stackSize);
bf1852e1
VZ
512
513 // suspend/resume/terminate
514 bool Suspend();
515 bool Resume();
516 void Cancel() { m_state = STATE_CANCELED; }
517
518 // thread state
519 void SetState(wxThreadState state) { m_state = state; }
520 wxThreadState GetState() const { return m_state; }
521
522 // thread priority
b568d04f 523 void SetPriority(unsigned int priority);
bf1852e1
VZ
524 unsigned int GetPriority() const { return m_priority; }
525
526 // thread handle and id
527 HANDLE GetHandle() const { return m_hThread; }
528 DWORD GetId() const { return m_tid; }
529
530 // thread function
9f51f2b6 531 static THREAD_RETVAL THREAD_CALLCONV WinThreadStart(void *thread);
2bda0e17 532
bf1852e1
VZ
533private:
534 HANDLE m_hThread; // handle of the thread
535 wxThreadState m_state; // state, see wxThreadState enum
536 unsigned int m_priority; // thread priority in "wx" units
537 DWORD m_tid; // thread id
2bda0e17
KB
538};
539
08d7397c 540THREAD_RETVAL THREAD_CALLCONV wxThreadInternal::WinThreadStart(void *param)
2bda0e17 541{
9f51f2b6 542 THREAD_RETVAL rc;
f6bcfd97
BP
543 bool wasCancelled;
544
545 // first of all, check whether we hadn't been cancelled already and don't
546 // start the user code at all then
9f51f2b6 547 wxThread *thread = (wxThread *)param;
696e1ea0
VZ
548 if ( thread->m_internal->GetState() == STATE_EXITED )
549 {
9f51f2b6 550 rc = (THREAD_RETVAL)-1;
f6bcfd97 551 wasCancelled = TRUE;
696e1ea0 552 }
f6bcfd97 553 else // do run thread
bf1852e1 554 {
f6bcfd97
BP
555 // store the thread object in the TLS
556 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
557 {
558 wxLogSysError(_("Can not start thread: error writing TLS."));
bf1852e1 559
f6bcfd97
BP
560 return (DWORD)-1;
561 }
bf1852e1 562
9f51f2b6 563 rc = (THREAD_RETVAL)thread->Entry();
b568d04f 564
f6bcfd97
BP
565 // enter m_critsect before changing the thread state
566 thread->m_critsect.Enter();
567 wasCancelled = thread->m_internal->GetState() == STATE_CANCELED;
568 thread->m_internal->SetState(STATE_EXITED);
569 thread->m_critsect.Leave();
570 }
b568d04f 571
bee503b0 572 thread->OnExit();
2bda0e17 573
f6bcfd97 574 // if the thread was cancelled (from Delete()), then its handle is still
b568d04f
VZ
575 // needed there
576 if ( thread->IsDetached() && !wasCancelled )
577 {
578 // auto delete
579 delete thread;
580 }
581 //else: the joinable threads handle will be closed when Wait() is done
bf1852e1 582
b568d04f 583 return rc;
2bda0e17
KB
584}
585
b568d04f 586void wxThreadInternal::SetPriority(unsigned int priority)
2bda0e17 587{
b568d04f 588 m_priority = priority;
3222fde2 589
bf1852e1
VZ
590 // translate wxWindows priority to the Windows one
591 int win_priority;
592 if (m_priority <= 20)
593 win_priority = THREAD_PRIORITY_LOWEST;
594 else if (m_priority <= 40)
595 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
596 else if (m_priority <= 60)
597 win_priority = THREAD_PRIORITY_NORMAL;
598 else if (m_priority <= 80)
599 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
600 else if (m_priority <= 100)
601 win_priority = THREAD_PRIORITY_HIGHEST;
3222fde2
VZ
602 else
603 {
223d09f6 604 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
bf1852e1 605 win_priority = THREAD_PRIORITY_NORMAL;
3222fde2
VZ
606 }
607
b568d04f 608 if ( !::SetThreadPriority(m_hThread, win_priority) )
bee503b0
VZ
609 {
610 wxLogSysError(_("Can't set thread priority"));
611 }
b568d04f
VZ
612}
613
6fe73788 614bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
b568d04f
VZ
615{
616 // for compilers which have it, we should use C RTL function for thread
617 // creation instead of Win32 API one because otherwise we will have memory
618 // leaks if the thread uses C RTL (and most threads do)
9f51f2b6 619#ifdef wxUSE_BEGIN_THREAD
414c639c
VZ
620
621 // Watcom is reported to not like 0 stack size (which means "use default"
622 // for the other compilers and is also the default value for stackSize)
623#ifdef __WATCOMC__
624 if ( !stackSize )
625 stackSize = 10240;
626#endif // __WATCOMC__
627
9f51f2b6
VZ
628 m_hThread = (HANDLE)_beginthreadex
629 (
6fe73788
RL
630 NULL, // default security
631 stackSize,
632 wxThreadInternal::WinThreadStart, // entry point
633 thread,
634 CREATE_SUSPENDED,
635 (unsigned int *)&m_tid
9f51f2b6 636 );
611cb666 637#else // compiler doesn't have _beginthreadex
b568d04f
VZ
638 m_hThread = ::CreateThread
639 (
640 NULL, // default security
414c639c 641 stackSize, // stack size
9f51f2b6 642 wxThreadInternal::WinThreadStart, // thread entry point
b568d04f
VZ
643 (LPVOID)thread, // parameter
644 CREATE_SUSPENDED, // flags
645 &m_tid // [out] thread id
646 );
611cb666 647#endif // _beginthreadex/CreateThread
b568d04f
VZ
648
649 if ( m_hThread == NULL )
650 {
651 wxLogSysError(_("Can't create thread"));
652
653 return FALSE;
654 }
655
656 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
657 {
658 SetPriority(m_priority);
659 }
3222fde2 660
bf1852e1 661 return TRUE;
2bda0e17
KB
662}
663
bf1852e1 664bool wxThreadInternal::Suspend()
2bda0e17 665{
bf1852e1
VZ
666 DWORD nSuspendCount = ::SuspendThread(m_hThread);
667 if ( nSuspendCount == (DWORD)-1 )
bee503b0 668 {
bf1852e1
VZ
669 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
670
671 return FALSE;
bee503b0 672 }
2bda0e17 673
bf1852e1
VZ
674 m_state = STATE_PAUSED;
675
676 return TRUE;
a6b0bd49
VZ
677}
678
bf1852e1 679bool wxThreadInternal::Resume()
a6b0bd49 680{
bf1852e1 681 DWORD nSuspendCount = ::ResumeThread(m_hThread);
a6b0bd49
VZ
682 if ( nSuspendCount == (DWORD)-1 )
683 {
bf1852e1 684 wxLogSysError(_("Can not resume thread %x"), m_hThread);
a6b0bd49 685
bf1852e1 686 return FALSE;
a6b0bd49
VZ
687 }
688
f6bcfd97
BP
689 // don't change the state from STATE_EXITED because it's special and means
690 // we are going to terminate without running any user code - if we did it,
691 // the codei n Delete() wouldn't work
692 if ( m_state != STATE_EXITED )
693 {
694 m_state = STATE_RUNNING;
695 }
bee503b0 696
bf1852e1 697 return TRUE;
a6b0bd49
VZ
698}
699
bf1852e1
VZ
700// static functions
701// ----------------
702
703wxThread *wxThread::This()
a6b0bd49 704{
b568d04f 705 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
bf1852e1
VZ
706
707 // be careful, 0 may be a valid return value as well
708 if ( !thread && (::GetLastError() != NO_ERROR) )
a6b0bd49 709 {
bf1852e1 710 wxLogSysError(_("Couldn't get the current thread pointer"));
a6b0bd49 711
bf1852e1 712 // return NULL...
a6b0bd49
VZ
713 }
714
bf1852e1
VZ
715 return thread;
716}
717
718bool wxThread::IsMain()
719{
b568d04f 720 return ::GetCurrentThreadId() == gs_idMainThread;
bf1852e1
VZ
721}
722
c25a510b
JS
723#ifdef Yield
724#undef Yield
725#endif
726
bf1852e1
VZ
727void wxThread::Yield()
728{
b568d04f
VZ
729 // 0 argument to Sleep() is special and means to just give away the rest of
730 // our timeslice
bf1852e1
VZ
731 ::Sleep(0);
732}
733
734void wxThread::Sleep(unsigned long milliseconds)
735{
736 ::Sleep(milliseconds);
737}
738
ef8d96c2
VZ
739int wxThread::GetCPUCount()
740{
28a4627c
VZ
741 SYSTEM_INFO si;
742 GetSystemInfo(&si);
743
744 return si.dwNumberOfProcessors;
ef8d96c2
VZ
745}
746
4958ea8f
RD
747unsigned long wxThread::GetCurrentId()
748{
749 return (unsigned long)::GetCurrentThreadId();
750}
751
ef8d96c2
VZ
752bool wxThread::SetConcurrency(size_t level)
753{
28a4627c
VZ
754 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
755
ef8d96c2 756 // ok only for the default one
28a4627c
VZ
757 if ( level == 0 )
758 return 0;
759
760 // get system affinity mask first
761 HANDLE hProcess = ::GetCurrentProcess();
762 DWORD dwProcMask, dwSysMask;
763 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
764 {
765 wxLogLastError(_T("GetProcessAffinityMask"));
766
767 return FALSE;
768 }
769
770 // how many CPUs have we got?
771 if ( dwSysMask == 1 )
772 {
773 // don't bother with all this complicated stuff - on a single
774 // processor system it doesn't make much sense anyhow
775 return level == 1;
776 }
777
778 // calculate the process mask: it's a bit vector with one bit per
779 // processor; we want to schedule the process to run on first level
780 // CPUs
781 DWORD bit = 1;
782 while ( bit )
783 {
784 if ( dwSysMask & bit )
785 {
786 // ok, we can set this bit
787 dwProcMask |= bit;
788
789 // another process added
790 if ( !--level )
791 {
792 // and that's enough
793 break;
794 }
795 }
796
797 // next bit
798 bit <<= 1;
799 }
800
801 // could we set all bits?
802 if ( level != 0 )
803 {
804 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level);
805
806 return FALSE;
807 }
808
809 // set it: we can't link to SetProcessAffinityMask() because it doesn't
810 // exist in Win9x, use RT binding instead
811
696e1ea0 812 typedef BOOL (*SETPROCESSAFFINITYMASK)(HANDLE, DWORD);
28a4627c
VZ
813
814 // can use static var because we're always in the main thread here
815 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
816
817 if ( !pfnSetProcessAffinityMask )
818 {
819 HMODULE hModKernel = ::LoadLibrary(_T("kernel32"));
820 if ( hModKernel )
821 {
822 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
f6bcfd97 823 ::GetProcAddress(hModKernel, "SetProcessAffinityMask");
28a4627c
VZ
824 }
825
826 // we've discovered a MT version of Win9x!
827 wxASSERT_MSG( pfnSetProcessAffinityMask,
f6bcfd97 828 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
28a4627c
VZ
829 }
830
831 if ( !pfnSetProcessAffinityMask )
832 {
833 // msg given above - do it only once
834 return FALSE;
835 }
836
696e1ea0 837 if ( pfnSetProcessAffinityMask(hProcess, dwProcMask) == 0 )
28a4627c
VZ
838 {
839 wxLogLastError(_T("SetProcessAffinityMask"));
840
841 return FALSE;
842 }
843
844 return TRUE;
ef8d96c2
VZ
845}
846
b568d04f
VZ
847// ctor and dtor
848// -------------
849
850wxThread::wxThread(wxThreadKind kind)
851{
9fc3ad34 852 m_internal = new wxThreadInternal();
b568d04f
VZ
853
854 m_isDetached = kind == wxTHREAD_DETACHED;
855}
856
857wxThread::~wxThread()
858{
9fc3ad34 859 delete m_internal;
b568d04f
VZ
860}
861
bf1852e1
VZ
862// create/start thread
863// -------------------
864
6fe73788 865wxThreadError wxThread::Create(unsigned int stackSize)
bf1852e1 866{
b568d04f
VZ
867 wxCriticalSectionLocker lock(m_critsect);
868
6fe73788 869 if ( !m_internal->Create(this, stackSize) )
bf1852e1 870 return wxTHREAD_NO_RESOURCE;
bee503b0 871
a6b0bd49 872 return wxTHREAD_NO_ERROR;
2bda0e17
KB
873}
874
bf1852e1 875wxThreadError wxThread::Run()
2bda0e17 876{
bf1852e1
VZ
877 wxCriticalSectionLocker lock(m_critsect);
878
9fc3ad34 879 if ( m_internal->GetState() != STATE_NEW )
bf1852e1
VZ
880 {
881 // actually, it may be almost any state at all, not only STATE_RUNNING
882 return wxTHREAD_RUNNING;
883 }
884
b568d04f 885 // the thread has just been created and is still suspended - let it run
bf1852e1 886 return Resume();
2bda0e17
KB
887}
888
bf1852e1
VZ
889// suspend/resume thread
890// ---------------------
891
892wxThreadError wxThread::Pause()
2bda0e17 893{
bf1852e1
VZ
894 wxCriticalSectionLocker lock(m_critsect);
895
9fc3ad34 896 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
897}
898
bf1852e1 899wxThreadError wxThread::Resume()
2bda0e17 900{
bf1852e1
VZ
901 wxCriticalSectionLocker lock(m_critsect);
902
9fc3ad34 903 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
904}
905
bf1852e1
VZ
906// stopping thread
907// ---------------
908
b568d04f
VZ
909wxThread::ExitCode wxThread::Wait()
910{
911 // although under Windows we can wait for any thread, it's an error to
912 // wait for a detached one in wxWin API
913 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
914 _T("can't wait for detached thread") );
915
916 ExitCode rc = (ExitCode)-1;
917
918 (void)Delete(&rc);
919
9fc3ad34 920 m_internal->Free();
b568d04f
VZ
921
922 return rc;
923}
924
925wxThreadError wxThread::Delete(ExitCode *pRc)
2bda0e17 926{
bf1852e1
VZ
927 ExitCode rc = 0;
928
929 // Delete() is always safe to call, so consider all possible states
696e1ea0 930
f6bcfd97
BP
931 // we might need to resume the thread, but we might also not need to cancel
932 // it if it doesn't run yet
933 bool shouldResume = FALSE,
934 shouldCancel = TRUE,
935 isRunning = FALSE;
696e1ea0 936
f6bcfd97 937 // check if the thread already started to run
696e1ea0
VZ
938 {
939 wxCriticalSectionLocker lock(m_critsect);
940
941 if ( m_internal->GetState() == STATE_NEW )
942 {
f6bcfd97
BP
943 // WinThreadStart() will see it and terminate immediately, no need
944 // to cancel the thread - but we still need to resume it to let it
945 // run
696e1ea0
VZ
946 m_internal->SetState(STATE_EXITED);
947
f6bcfd97
BP
948 Resume(); // it knows about STATE_EXITED special case
949
950 shouldCancel = FALSE;
951 isRunning = TRUE;
952
953 // shouldResume is correctly set to FALSE here
954 }
955 else
956 {
957 shouldResume = IsPaused();
696e1ea0
VZ
958 }
959 }
960
f6bcfd97
BP
961 // resume the thread if it is paused
962 if ( shouldResume )
bf1852e1
VZ
963 Resume();
964
9fc3ad34 965 HANDLE hThread = m_internal->GetHandle();
b568d04f 966
696e1ea0 967 // does is still run?
f6bcfd97 968 if ( isRunning || IsRunning() )
bf1852e1
VZ
969 {
970 if ( IsMain() )
971 {
972 // set flag for wxIsWaitingForThread()
b568d04f 973 gs_waitingForThread = TRUE;
bf1852e1 974
b568d04f 975#if wxUSE_GUI
bf1852e1 976 wxBeginBusyCursor();
b568d04f 977#endif // wxUSE_GUI
bf1852e1
VZ
978 }
979
b568d04f 980 // ask the thread to terminate
f6bcfd97 981 if ( shouldCancel )
bf1852e1
VZ
982 {
983 wxCriticalSectionLocker lock(m_critsect);
984
9fc3ad34 985 m_internal->Cancel();
bf1852e1
VZ
986 }
987
b568d04f 988#if wxUSE_GUI
bf1852e1
VZ
989 // we can't just wait for the thread to terminate because it might be
990 // calling some GUI functions and so it will never terminate before we
991 // process the Windows messages that result from these functions
992 DWORD result;
993 do
994 {
995 result = ::MsgWaitForMultipleObjects
996 (
997 1, // number of objects to wait for
998 &hThread, // the objects
999 FALSE, // don't wait for all objects
1000 INFINITE, // no timeout
1001 QS_ALLEVENTS // return as soon as there are any events
1002 );
1003
1004 switch ( result )
1005 {
1006 case 0xFFFFFFFF:
1007 // error
1008 wxLogSysError(_("Can not wait for thread termination"));
1009 Kill();
b568d04f 1010 return wxTHREAD_KILLED;
bf1852e1
VZ
1011
1012 case WAIT_OBJECT_0:
1013 // thread we're waiting for terminated
1014 break;
1015
1016 case WAIT_OBJECT_0 + 1:
1017 // new message arrived, process it
1018 if ( !wxTheApp->DoMessage() )
1019 {
1020 // WM_QUIT received: kill the thread
1021 Kill();
1022
b568d04f 1023 return wxTHREAD_KILLED;
bf1852e1
VZ
1024 }
1025
1026 if ( IsMain() )
1027 {
1028 // give the thread we're waiting for chance to exit
1029 // from the GUI call it might have been in
b568d04f 1030 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
bf1852e1
VZ
1031 {
1032 wxMutexGuiLeave();
1033 }
1034 }
1035
1036 break;
1037
1038 default:
223d09f6 1039 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
bf1852e1
VZ
1040 }
1041 } while ( result != WAIT_OBJECT_0 );
b568d04f
VZ
1042#else // !wxUSE_GUI
1043 // simply wait for the thread to terminate
1044 //
1045 // OTOH, even console apps create windows (in wxExecute, for WinSock
1046 // &c), so may be use MsgWaitForMultipleObject() too here?
1047 if ( WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0 )
1048 {
1049 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1050 }
1051#endif // wxUSE_GUI/!wxUSE_GUI
bf1852e1
VZ
1052
1053 if ( IsMain() )
1054 {
b568d04f 1055 gs_waitingForThread = FALSE;
bf1852e1 1056
b568d04f 1057#if wxUSE_GUI
bf1852e1 1058 wxEndBusyCursor();
b568d04f 1059#endif // wxUSE_GUI
bf1852e1 1060 }
b568d04f 1061 }
bf1852e1 1062
10671c67
VZ
1063 // although the thread might be already in the EXITED state it might not
1064 // have terminated yet and so we are not sure that it has actually
1065 // terminated if the "if" above hadn't been taken
1066 do
b568d04f 1067 {
10671c67
VZ
1068 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
1069 {
1070 wxLogLastError(wxT("GetExitCodeThread"));
bf1852e1 1071
10671c67
VZ
1072 rc = (ExitCode)-1;
1073 }
1074 } while ( (DWORD)rc == STILL_ACTIVE );
bf1852e1 1075
b568d04f
VZ
1076 if ( IsDetached() )
1077 {
1078 // if the thread exits normally, this is done in WinThreadStart, but in
1079 // this case it would have been too early because
f6bcfd97 1080 // MsgWaitForMultipleObject() would fail if the thread handle was
b568d04f
VZ
1081 // closed while we were waiting on it, so we must do it here
1082 delete this;
bf1852e1
VZ
1083 }
1084
b568d04f
VZ
1085 if ( pRc )
1086 *pRc = rc;
1087
1088 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
2bda0e17
KB
1089}
1090
bf1852e1 1091wxThreadError wxThread::Kill()
2bda0e17 1092{
bf1852e1
VZ
1093 if ( !IsRunning() )
1094 return wxTHREAD_NOT_RUNNING;
1095
9fc3ad34 1096 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
bf1852e1
VZ
1097 {
1098 wxLogSysError(_("Couldn't terminate thread"));
1099
1100 return wxTHREAD_MISC_ERROR;
1101 }
1102
9fc3ad34 1103 m_internal->Free();
b568d04f
VZ
1104
1105 if ( IsDetached() )
1106 {
1107 delete this;
1108 }
bf1852e1
VZ
1109
1110 return wxTHREAD_NO_ERROR;
2bda0e17
KB
1111}
1112
b568d04f 1113void wxThread::Exit(ExitCode status)
2bda0e17 1114{
9fc3ad34 1115 m_internal->Free();
2bda0e17 1116
b568d04f
VZ
1117 if ( IsDetached() )
1118 {
1119 delete this;
1120 }
1121
9f51f2b6 1122#ifdef wxUSE_BEGIN_THREAD
b568d04f
VZ
1123 _endthreadex((unsigned)status);
1124#else // !VC++
bf1852e1 1125 ::ExitThread((DWORD)status);
b568d04f 1126#endif // VC++/!VC++
2bda0e17 1127
223d09f6 1128 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
bf1852e1 1129}
2bda0e17 1130
b568d04f
VZ
1131// priority setting
1132// ----------------
1133
bf1852e1
VZ
1134void wxThread::SetPriority(unsigned int prio)
1135{
1136 wxCriticalSectionLocker lock(m_critsect);
1137
9fc3ad34 1138 m_internal->SetPriority(prio);
bf1852e1 1139}
2bda0e17 1140
bf1852e1
VZ
1141unsigned int wxThread::GetPriority() const
1142{
b568d04f 1143 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
2bda0e17 1144
9fc3ad34 1145 return m_internal->GetPriority();
2bda0e17
KB
1146}
1147
b568d04f 1148unsigned long wxThread::GetId() const
2bda0e17 1149{
b568d04f 1150 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1151
9fc3ad34 1152 return (unsigned long)m_internal->GetId();
2bda0e17
KB
1153}
1154
72fd19a1
JS
1155bool wxThread::IsRunning() const
1156{
b568d04f 1157 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1158
9fc3ad34 1159 return m_internal->GetState() == STATE_RUNNING;
72fd19a1
JS
1160}
1161
1162bool wxThread::IsAlive() const
1163{
b568d04f 1164 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1165
9fc3ad34
VZ
1166 return (m_internal->GetState() == STATE_RUNNING) ||
1167 (m_internal->GetState() == STATE_PAUSED);
72fd19a1
JS
1168}
1169
a737331d
GL
1170bool wxThread::IsPaused() const
1171{
b568d04f 1172 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
a737331d 1173
9fc3ad34 1174 return m_internal->GetState() == STATE_PAUSED;
a737331d
GL
1175}
1176
8c10faf1 1177bool wxThread::TestDestroy()
2bda0e17 1178{
b568d04f 1179 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1180
9fc3ad34 1181 return m_internal->GetState() == STATE_CANCELED;
2bda0e17
KB
1182}
1183
3222fde2
VZ
1184// ----------------------------------------------------------------------------
1185// Automatic initialization for thread module
1186// ----------------------------------------------------------------------------
2bda0e17 1187
3222fde2 1188class wxThreadModule : public wxModule
a6b0bd49 1189{
3222fde2
VZ
1190public:
1191 virtual bool OnInit();
1192 virtual void OnExit();
d524867f 1193
3222fde2
VZ
1194private:
1195 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1196};
d524867f
RR
1197
1198IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1199
3222fde2 1200bool wxThreadModule::OnInit()
d524867f 1201{
bf1852e1 1202 // allocate TLS index for storing the pointer to the current thread
b568d04f
VZ
1203 gs_tlsThisThread = ::TlsAlloc();
1204 if ( gs_tlsThisThread == 0xFFFFFFFF )
bf1852e1
VZ
1205 {
1206 // in normal circumstances it will only happen if all other
1207 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1208 // words, this should never happen
f6bcfd97 1209 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
bf1852e1
VZ
1210
1211 return FALSE;
1212 }
1213
1214 // main thread doesn't have associated wxThread object, so store 0 in the
1215 // TLS instead
b568d04f 1216 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
bf1852e1 1217 {
b568d04f
VZ
1218 ::TlsFree(gs_tlsThisThread);
1219 gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 1220
f6bcfd97 1221 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
bf1852e1
VZ
1222
1223 return FALSE;
1224 }
1225
b568d04f 1226 gs_critsectWaitingForGui = new wxCriticalSection();
bee503b0 1227
b568d04f
VZ
1228 gs_critsectGui = new wxCriticalSection();
1229 gs_critsectGui->Enter();
bee503b0 1230
bf1852e1 1231 // no error return for GetCurrentThreadId()
b568d04f 1232 gs_idMainThread = ::GetCurrentThreadId();
3222fde2 1233
d524867f
RR
1234 return TRUE;
1235}
1236
3222fde2 1237void wxThreadModule::OnExit()
d524867f 1238{
b568d04f 1239 if ( !::TlsFree(gs_tlsThisThread) )
bf1852e1 1240 {
f6bcfd97 1241 wxLogLastError(wxT("TlsFree failed."));
bf1852e1
VZ
1242 }
1243
b568d04f 1244 if ( gs_critsectGui )
3222fde2 1245 {
b568d04f
VZ
1246 gs_critsectGui->Leave();
1247 delete gs_critsectGui;
1248 gs_critsectGui = NULL;
3222fde2 1249 }
bee503b0 1250
b568d04f
VZ
1251 delete gs_critsectWaitingForGui;
1252 gs_critsectWaitingForGui = NULL;
3222fde2
VZ
1253}
1254
bee503b0 1255// ----------------------------------------------------------------------------
b568d04f 1256// under Windows, these functions are implemented using a critical section and
3222fde2 1257// not a mutex, so the names are a bit confusing
bee503b0
VZ
1258// ----------------------------------------------------------------------------
1259
3222fde2
VZ
1260void WXDLLEXPORT wxMutexGuiEnter()
1261{
bee503b0
VZ
1262 // this would dead lock everything...
1263 wxASSERT_MSG( !wxThread::IsMain(),
223d09f6 1264 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
bee503b0
VZ
1265
1266 // the order in which we enter the critical sections here is crucial!!
1267
1268 // set the flag telling to the main thread that we want to do some GUI
1269 {
b568d04f 1270 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1271
b568d04f 1272 gs_nWaitingForGui++;
bee503b0
VZ
1273 }
1274
1275 wxWakeUpMainThread();
1276
1277 // now we may block here because the main thread will soon let us in
1278 // (during the next iteration of OnIdle())
b568d04f 1279 gs_critsectGui->Enter();
3222fde2
VZ
1280}
1281
1282void WXDLLEXPORT wxMutexGuiLeave()
1283{
b568d04f 1284 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0
VZ
1285
1286 if ( wxThread::IsMain() )
1287 {
b568d04f 1288 gs_bGuiOwnedByMainThread = FALSE;
bee503b0
VZ
1289 }
1290 else
1291 {
4d1c1c3c 1292 // decrement the number of threads waiting for GUI access now
b568d04f 1293 wxASSERT_MSG( gs_nWaitingForGui > 0,
223d09f6 1294 wxT("calling wxMutexGuiLeave() without entering it first?") );
bee503b0 1295
b568d04f 1296 gs_nWaitingForGui--;
bee503b0
VZ
1297
1298 wxWakeUpMainThread();
1299 }
1300
b568d04f 1301 gs_critsectGui->Leave();
bee503b0
VZ
1302}
1303
1304void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1305{
1306 wxASSERT_MSG( wxThread::IsMain(),
223d09f6 1307 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
bee503b0 1308
b568d04f 1309 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1310
b568d04f 1311 if ( gs_nWaitingForGui == 0 )
bee503b0
VZ
1312 {
1313 // no threads are waiting for GUI - so we may acquire the lock without
1314 // any danger (but only if we don't already have it)
1315 if ( !wxGuiOwnedByMainThread() )
1316 {
b568d04f 1317 gs_critsectGui->Enter();
bee503b0 1318
b568d04f 1319 gs_bGuiOwnedByMainThread = TRUE;
bee503b0
VZ
1320 }
1321 //else: already have it, nothing to do
1322 }
1323 else
1324 {
1325 // some threads are waiting, release the GUI lock if we have it
1326 if ( wxGuiOwnedByMainThread() )
1327 {
1328 wxMutexGuiLeave();
1329 }
1330 //else: some other worker thread is doing GUI
1331 }
1332}
1333
1334bool WXDLLEXPORT wxGuiOwnedByMainThread()
1335{
b568d04f 1336 return gs_bGuiOwnedByMainThread;
bee503b0
VZ
1337}
1338
1339// wake up the main thread if it's in ::GetMessage()
1340void WXDLLEXPORT wxWakeUpMainThread()
1341{
1342 // sending any message would do - hopefully WM_NULL is harmless enough
b568d04f 1343 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
bee503b0
VZ
1344 {
1345 // should never happen
f6bcfd97 1346 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
bee503b0 1347 }
3222fde2 1348}
d524867f 1349
bf1852e1
VZ
1350bool WXDLLEXPORT wxIsWaitingForThread()
1351{
b568d04f 1352 return gs_waitingForThread;
bf1852e1
VZ
1353}
1354
9e84b847
VZ
1355// ----------------------------------------------------------------------------
1356// include common implementation code
1357// ----------------------------------------------------------------------------
1358
1359#include "wx/thrimpl.cpp"
1360
3222fde2 1361#endif // wxUSE_THREADS
6fe73788 1362