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