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