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