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