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