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