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