]> git.saurik.com Git - wxWidgets.git/blame - src/msw/thread.cpp
fixed cleanup order to behave correctly in presence of exceptions
[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
14f355c2 13#if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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
3222fde2
VZ
363// ----------------------------------------------------------------------------
364// wxThread implementation
365// ----------------------------------------------------------------------------
366
bf1852e1
VZ
367// wxThreadInternal class
368// ----------------------
369
3222fde2
VZ
370class wxThreadInternal
371{
2bda0e17 372public:
bf1852e1
VZ
373 wxThreadInternal()
374 {
375 m_hThread = 0;
376 m_state = STATE_NEW;
377 m_priority = WXTHREAD_DEFAULT_PRIORITY;
378 }
379
b568d04f
VZ
380 ~wxThreadInternal()
381 {
382 Free();
383 }
384
385 void Free()
386 {
387 if ( m_hThread )
388 {
389 if ( !::CloseHandle(m_hThread) )
390 {
f6bcfd97 391 wxLogLastError(wxT("CloseHandle(thread)"));
b568d04f
VZ
392 }
393
394 m_hThread = 0;
395 }
396 }
397
bf1852e1 398 // create a new (suspended) thread (for the given thread object)
6fe73788 399 bool Create(wxThread *thread, unsigned int stackSize);
bf1852e1 400
68d41720
VZ
401 // wait for the thread to terminate, either by itself, or by asking it
402 // (politely, this is not Kill()!) to do it
403 wxThreadError WaitForTerminate(bool shouldCancel,
404 wxCriticalSection& cs,
405 wxThread::ExitCode *pRc);
406
407 // kill the thread unconditionally
408 wxThreadError Kill();
409
bf1852e1
VZ
410 // suspend/resume/terminate
411 bool Suspend();
412 bool Resume();
413 void Cancel() { m_state = STATE_CANCELED; }
414
415 // thread state
416 void SetState(wxThreadState state) { m_state = state; }
417 wxThreadState GetState() const { return m_state; }
418
419 // thread priority
b568d04f 420 void SetPriority(unsigned int priority);
bf1852e1
VZ
421 unsigned int GetPriority() const { return m_priority; }
422
423 // thread handle and id
424 HANDLE GetHandle() const { return m_hThread; }
425 DWORD GetId() const { return m_tid; }
426
427 // thread function
9f51f2b6 428 static THREAD_RETVAL THREAD_CALLCONV WinThreadStart(void *thread);
2bda0e17 429
bf1852e1
VZ
430private:
431 HANDLE m_hThread; // handle of the thread
432 wxThreadState m_state; // state, see wxThreadState enum
433 unsigned int m_priority; // thread priority in "wx" units
434 DWORD m_tid; // thread id
22f3361e
VZ
435
436 DECLARE_NO_COPY_CLASS(wxThreadInternal)
2bda0e17
KB
437};
438
08d7397c 439THREAD_RETVAL THREAD_CALLCONV wxThreadInternal::WinThreadStart(void *param)
2bda0e17 440{
9f51f2b6 441 THREAD_RETVAL rc;
f6bcfd97
BP
442 bool wasCancelled;
443
444 // first of all, check whether we hadn't been cancelled already and don't
445 // start the user code at all then
9f51f2b6 446 wxThread *thread = (wxThread *)param;
696e1ea0
VZ
447 if ( thread->m_internal->GetState() == STATE_EXITED )
448 {
9f51f2b6 449 rc = (THREAD_RETVAL)-1;
f6bcfd97 450 wasCancelled = TRUE;
696e1ea0 451 }
f6bcfd97 452 else // do run thread
bf1852e1 453 {
f6bcfd97
BP
454 // store the thread object in the TLS
455 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
456 {
457 wxLogSysError(_("Can not start thread: error writing TLS."));
bf1852e1 458
f6bcfd97
BP
459 return (DWORD)-1;
460 }
bf1852e1 461
9f51f2b6 462 rc = (THREAD_RETVAL)thread->Entry();
b568d04f 463
f6bcfd97
BP
464 // enter m_critsect before changing the thread state
465 thread->m_critsect.Enter();
466 wasCancelled = thread->m_internal->GetState() == STATE_CANCELED;
467 thread->m_internal->SetState(STATE_EXITED);
468 thread->m_critsect.Leave();
469 }
b568d04f 470
bee503b0 471 thread->OnExit();
2bda0e17 472
f6bcfd97 473 // if the thread was cancelled (from Delete()), then its handle is still
b568d04f
VZ
474 // needed there
475 if ( thread->IsDetached() && !wasCancelled )
476 {
477 // auto delete
478 delete thread;
479 }
480 //else: the joinable threads handle will be closed when Wait() is done
bf1852e1 481
b568d04f 482 return rc;
2bda0e17
KB
483}
484
b568d04f 485void wxThreadInternal::SetPriority(unsigned int priority)
2bda0e17 486{
b568d04f 487 m_priority = priority;
3222fde2 488
bf1852e1
VZ
489 // translate wxWindows priority to the Windows one
490 int win_priority;
491 if (m_priority <= 20)
492 win_priority = THREAD_PRIORITY_LOWEST;
493 else if (m_priority <= 40)
494 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
495 else if (m_priority <= 60)
496 win_priority = THREAD_PRIORITY_NORMAL;
497 else if (m_priority <= 80)
498 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
499 else if (m_priority <= 100)
500 win_priority = THREAD_PRIORITY_HIGHEST;
3222fde2
VZ
501 else
502 {
223d09f6 503 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
bf1852e1 504 win_priority = THREAD_PRIORITY_NORMAL;
3222fde2
VZ
505 }
506
b568d04f 507 if ( !::SetThreadPriority(m_hThread, win_priority) )
bee503b0
VZ
508 {
509 wxLogSysError(_("Can't set thread priority"));
510 }
b568d04f
VZ
511}
512
6fe73788 513bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
b568d04f 514{
50ef4401
VZ
515 wxASSERT_MSG( m_state == STATE_NEW && !m_hThread,
516 _T("Create()ing thread twice?") );
517
b568d04f
VZ
518 // for compilers which have it, we should use C RTL function for thread
519 // creation instead of Win32 API one because otherwise we will have memory
520 // leaks if the thread uses C RTL (and most threads do)
9f51f2b6 521#ifdef wxUSE_BEGIN_THREAD
414c639c
VZ
522
523 // Watcom is reported to not like 0 stack size (which means "use default"
524 // for the other compilers and is also the default value for stackSize)
525#ifdef __WATCOMC__
526 if ( !stackSize )
527 stackSize = 10240;
528#endif // __WATCOMC__
529
9f51f2b6
VZ
530 m_hThread = (HANDLE)_beginthreadex
531 (
6fe73788
RL
532 NULL, // default security
533 stackSize,
534 wxThreadInternal::WinThreadStart, // entry point
535 thread,
536 CREATE_SUSPENDED,
537 (unsigned int *)&m_tid
9f51f2b6 538 );
611cb666 539#else // compiler doesn't have _beginthreadex
b568d04f
VZ
540 m_hThread = ::CreateThread
541 (
542 NULL, // default security
414c639c 543 stackSize, // stack size
9f51f2b6 544 wxThreadInternal::WinThreadStart, // thread entry point
b568d04f
VZ
545 (LPVOID)thread, // parameter
546 CREATE_SUSPENDED, // flags
547 &m_tid // [out] thread id
548 );
611cb666 549#endif // _beginthreadex/CreateThread
b568d04f
VZ
550
551 if ( m_hThread == NULL )
552 {
553 wxLogSysError(_("Can't create thread"));
554
555 return FALSE;
556 }
557
558 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
559 {
560 SetPriority(m_priority);
561 }
3222fde2 562
bf1852e1 563 return TRUE;
2bda0e17
KB
564}
565
68d41720
VZ
566wxThreadError wxThreadInternal::Kill()
567{
568 if ( !::TerminateThread(m_hThread, (DWORD)-1) )
569 {
570 wxLogSysError(_("Couldn't terminate thread"));
571
572 return wxTHREAD_MISC_ERROR;
573 }
574
575 Free();
576
577 return wxTHREAD_NO_ERROR;
578}
579
580wxThreadError
581wxThreadInternal::WaitForTerminate(bool shouldCancel,
582 wxCriticalSection& cs,
583 wxThread::ExitCode *pRc)
584{
585 wxThread::ExitCode rc = 0;
586
587 // Delete() is always safe to call, so consider all possible states
588
589 // we might need to resume the thread, but we might also not need to cancel
590 // it if it doesn't run yet
591 bool shouldResume = FALSE,
592 isRunning = FALSE;
593
594 // check if the thread already started to run
595 {
596 wxCriticalSectionLocker lock(cs);
597
598 if ( m_state == STATE_NEW )
599 {
600 if ( shouldCancel )
601 {
63fa42b3
VZ
602 // WinThreadStart() will see it and terminate immediately, no
603 // need to cancel the thread -- but we still need to resume it
604 // to let it run
68d41720
VZ
605 m_state = STATE_EXITED;
606
607 Resume(); // it knows about STATE_EXITED special case
608
609 shouldCancel = FALSE;
610 }
611
612 isRunning = TRUE;
613
614 // shouldResume is correctly set to FALSE here
615 }
63fa42b3
VZ
616 else if ( m_state == STATE_EXITED )
617 {
618 return wxTHREAD_NOT_RUNNING;
619 }
620 else // running (but maybe paused or cancelled)
68d41720
VZ
621 {
622 shouldResume = m_state == STATE_PAUSED;
623 }
624 }
625
626 // resume the thread if it is paused
627 if ( shouldResume )
628 Resume();
629
4f45ba63 630 // is it still running?
68d41720
VZ
631 if ( isRunning || m_state == STATE_RUNNING )
632 {
633 if ( wxThread::IsMain() )
634 {
635 // set flag for wxIsWaitingForThread()
636 gs_waitingForThread = TRUE;
637 }
638
639 // ask the thread to terminate
640 if ( shouldCancel )
641 {
642 wxCriticalSectionLocker lock(cs);
643
644 Cancel();
645 }
646
647 // we can't just wait for the thread to terminate because it might be
648 // calling some GUI functions and so it will never terminate before we
649 // process the Windows messages that result from these functions
650 // (note that even in console applications we might have to process
651 // messages if we use wxExecute() or timers or ...)
652 DWORD result = 0; // suppress warnings from broken compilers
653 do
654 {
655 if ( wxThread::IsMain() )
656 {
657 // give the thread we're waiting for chance to do the GUI call
658 // it might be in
659 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
660 {
661 wxMutexGuiLeave();
662 }
663 }
664
665 result = ::MsgWaitForMultipleObjects
666 (
667 1, // number of objects to wait for
668 &m_hThread, // the objects
669 FALSE, // don't wait for all objects
670 INFINITE, // no timeout
671 QS_ALLINPUT | // return as soon as there are any events
672 QS_ALLPOSTMESSAGE
673 );
674
675 switch ( result )
676 {
677 case 0xFFFFFFFF:
678 // error
679 wxLogSysError(_("Can not wait for thread termination"));
680 Kill();
681 return wxTHREAD_KILLED;
682
683 case WAIT_OBJECT_0:
684 // thread we're waiting for terminated
685 break;
686
687 case WAIT_OBJECT_0 + 1:
0e2f1b3e
VZ
688 // new message arrived, process it -- but only if we're the
689 // main thread as we don't support processing messages in
690 // the other ones
691 //
692 // NB: we still must include QS_ALLINPUT even when waiting
693 // in a secondary thread because if it had created some
694 // window somehow (possible not even using wxWindows)
695 // the system might dead lock then
4a08283e 696 if ( wxThread::IsMain() )
68d41720
VZ
697 {
698 // it looks that sometimes WAIT_OBJECT_0 + 1 is
699 // returned but there are no messages in the thread
700 // queue -- prevent DoMessageFromThreadWait() from
701 // blocking inside ::GetMessage() forever in this case
702 ::PostMessage(NULL, WM_NULL, 0, 0);
703
704 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits()
705 : NULL;
706
707 if ( traits && !traits->DoMessageFromThreadWait() )
708 {
709 // WM_QUIT received: kill the thread
710 Kill();
711
712 return wxTHREAD_KILLED;
713 }
714 }
715 break;
716
717 default:
718 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
719 }
720 } while ( result != WAIT_OBJECT_0 );
721
722 if ( wxThread::IsMain() )
723 {
724 gs_waitingForThread = FALSE;
725 }
726 }
727
728 // although the thread might be already in the EXITED state it might not
729 // have terminated yet and so we are not sure that it has actually
730 // terminated if the "if" above hadn't been taken
731 do
732 {
733 if ( !::GetExitCodeThread(m_hThread, (LPDWORD)&rc) )
734 {
735 wxLogLastError(wxT("GetExitCodeThread"));
736
737 rc = (wxThread::ExitCode)-1;
738 }
739 } while ( (DWORD)rc == STILL_ACTIVE );
740
741 if ( pRc )
742 *pRc = rc;
743
4f45ba63
VZ
744 // we don't need the thread handle any more
745 Free();
746
a430d03e 747 wxCriticalSectionLocker lock(cs);
4f45ba63
VZ
748 SetState(STATE_EXITED);
749
68d41720
VZ
750 return rc == (wxThread::ExitCode)-1 ? wxTHREAD_MISC_ERROR
751 : wxTHREAD_NO_ERROR;
752}
753
bf1852e1 754bool wxThreadInternal::Suspend()
2bda0e17 755{
bf1852e1
VZ
756 DWORD nSuspendCount = ::SuspendThread(m_hThread);
757 if ( nSuspendCount == (DWORD)-1 )
bee503b0 758 {
bf1852e1
VZ
759 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
760
761 return FALSE;
bee503b0 762 }
2bda0e17 763
bf1852e1
VZ
764 m_state = STATE_PAUSED;
765
766 return TRUE;
a6b0bd49
VZ
767}
768
bf1852e1 769bool wxThreadInternal::Resume()
a6b0bd49 770{
bf1852e1 771 DWORD nSuspendCount = ::ResumeThread(m_hThread);
a6b0bd49
VZ
772 if ( nSuspendCount == (DWORD)-1 )
773 {
bf1852e1 774 wxLogSysError(_("Can not resume thread %x"), m_hThread);
a6b0bd49 775
bf1852e1 776 return FALSE;
a6b0bd49
VZ
777 }
778
f6bcfd97
BP
779 // don't change the state from STATE_EXITED because it's special and means
780 // we are going to terminate without running any user code - if we did it,
781 // the codei n Delete() wouldn't work
782 if ( m_state != STATE_EXITED )
783 {
784 m_state = STATE_RUNNING;
785 }
bee503b0 786
bf1852e1 787 return TRUE;
a6b0bd49
VZ
788}
789
bf1852e1
VZ
790// static functions
791// ----------------
792
793wxThread *wxThread::This()
a6b0bd49 794{
b568d04f 795 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
bf1852e1
VZ
796
797 // be careful, 0 may be a valid return value as well
798 if ( !thread && (::GetLastError() != NO_ERROR) )
a6b0bd49 799 {
bf1852e1 800 wxLogSysError(_("Couldn't get the current thread pointer"));
a6b0bd49 801
bf1852e1 802 // return NULL...
a6b0bd49
VZ
803 }
804
bf1852e1
VZ
805 return thread;
806}
807
808bool wxThread::IsMain()
809{
b568d04f 810 return ::GetCurrentThreadId() == gs_idMainThread;
bf1852e1
VZ
811}
812
813void wxThread::Yield()
814{
b568d04f
VZ
815 // 0 argument to Sleep() is special and means to just give away the rest of
816 // our timeslice
bf1852e1
VZ
817 ::Sleep(0);
818}
819
820void wxThread::Sleep(unsigned long milliseconds)
821{
822 ::Sleep(milliseconds);
823}
824
ef8d96c2
VZ
825int wxThread::GetCPUCount()
826{
28a4627c
VZ
827 SYSTEM_INFO si;
828 GetSystemInfo(&si);
829
830 return si.dwNumberOfProcessors;
ef8d96c2
VZ
831}
832
4958ea8f
RD
833unsigned long wxThread::GetCurrentId()
834{
835 return (unsigned long)::GetCurrentThreadId();
836}
837
ef8d96c2
VZ
838bool wxThread::SetConcurrency(size_t level)
839{
4676948b 840#ifndef __WXWINCE__
28a4627c
VZ
841 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
842
ef8d96c2 843 // ok only for the default one
28a4627c
VZ
844 if ( level == 0 )
845 return 0;
846
847 // get system affinity mask first
848 HANDLE hProcess = ::GetCurrentProcess();
849 DWORD dwProcMask, dwSysMask;
850 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
851 {
852 wxLogLastError(_T("GetProcessAffinityMask"));
853
854 return FALSE;
855 }
856
857 // how many CPUs have we got?
858 if ( dwSysMask == 1 )
859 {
860 // don't bother with all this complicated stuff - on a single
861 // processor system it doesn't make much sense anyhow
862 return level == 1;
863 }
864
865 // calculate the process mask: it's a bit vector with one bit per
866 // processor; we want to schedule the process to run on first level
867 // CPUs
868 DWORD bit = 1;
869 while ( bit )
870 {
871 if ( dwSysMask & bit )
872 {
873 // ok, we can set this bit
874 dwProcMask |= bit;
875
876 // another process added
877 if ( !--level )
878 {
879 // and that's enough
880 break;
881 }
882 }
883
884 // next bit
885 bit <<= 1;
886 }
887
888 // could we set all bits?
889 if ( level != 0 )
890 {
891 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level);
892
893 return FALSE;
894 }
895
896 // set it: we can't link to SetProcessAffinityMask() because it doesn't
897 // exist in Win9x, use RT binding instead
898
696e1ea0 899 typedef BOOL (*SETPROCESSAFFINITYMASK)(HANDLE, DWORD);
28a4627c
VZ
900
901 // can use static var because we're always in the main thread here
902 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
903
904 if ( !pfnSetProcessAffinityMask )
905 {
906 HMODULE hModKernel = ::LoadLibrary(_T("kernel32"));
907 if ( hModKernel )
908 {
909 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
f6bcfd97 910 ::GetProcAddress(hModKernel, "SetProcessAffinityMask");
28a4627c
VZ
911 }
912
913 // we've discovered a MT version of Win9x!
914 wxASSERT_MSG( pfnSetProcessAffinityMask,
f6bcfd97 915 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
28a4627c
VZ
916 }
917
918 if ( !pfnSetProcessAffinityMask )
919 {
920 // msg given above - do it only once
921 return FALSE;
922 }
923
696e1ea0 924 if ( pfnSetProcessAffinityMask(hProcess, dwProcMask) == 0 )
28a4627c
VZ
925 {
926 wxLogLastError(_T("SetProcessAffinityMask"));
927
928 return FALSE;
929 }
4676948b 930#endif
28a4627c 931 return TRUE;
ef8d96c2
VZ
932}
933
b568d04f
VZ
934// ctor and dtor
935// -------------
936
937wxThread::wxThread(wxThreadKind kind)
938{
9fc3ad34 939 m_internal = new wxThreadInternal();
b568d04f
VZ
940
941 m_isDetached = kind == wxTHREAD_DETACHED;
942}
943
944wxThread::~wxThread()
945{
9fc3ad34 946 delete m_internal;
b568d04f
VZ
947}
948
bf1852e1
VZ
949// create/start thread
950// -------------------
951
6fe73788 952wxThreadError wxThread::Create(unsigned int stackSize)
bf1852e1 953{
b568d04f
VZ
954 wxCriticalSectionLocker lock(m_critsect);
955
6fe73788 956 if ( !m_internal->Create(this, stackSize) )
bf1852e1 957 return wxTHREAD_NO_RESOURCE;
bee503b0 958
a6b0bd49 959 return wxTHREAD_NO_ERROR;
2bda0e17
KB
960}
961
bf1852e1 962wxThreadError wxThread::Run()
2bda0e17 963{
bf1852e1
VZ
964 wxCriticalSectionLocker lock(m_critsect);
965
9fc3ad34 966 if ( m_internal->GetState() != STATE_NEW )
bf1852e1
VZ
967 {
968 // actually, it may be almost any state at all, not only STATE_RUNNING
969 return wxTHREAD_RUNNING;
970 }
971
b568d04f 972 // the thread has just been created and is still suspended - let it run
bf1852e1 973 return Resume();
2bda0e17
KB
974}
975
bf1852e1
VZ
976// suspend/resume thread
977// ---------------------
978
979wxThreadError wxThread::Pause()
2bda0e17 980{
bf1852e1
VZ
981 wxCriticalSectionLocker lock(m_critsect);
982
9fc3ad34 983 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
984}
985
bf1852e1 986wxThreadError wxThread::Resume()
2bda0e17 987{
bf1852e1
VZ
988 wxCriticalSectionLocker lock(m_critsect);
989
9fc3ad34 990 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
991}
992
bf1852e1
VZ
993// stopping thread
994// ---------------
995
b568d04f
VZ
996wxThread::ExitCode wxThread::Wait()
997{
998 // although under Windows we can wait for any thread, it's an error to
999 // wait for a detached one in wxWin API
1000 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
68d41720 1001 _T("wxThread::Wait(): can't wait for detached thread") );
b568d04f
VZ
1002
1003 ExitCode rc = (ExitCode)-1;
1004
68d41720 1005 (void)m_internal->WaitForTerminate(false, m_critsect, &rc);
b568d04f 1006
b568d04f
VZ
1007 return rc;
1008}
1009
1010wxThreadError wxThread::Delete(ExitCode *pRc)
2bda0e17 1011{
4f45ba63 1012 return m_internal->WaitForTerminate(true, m_critsect, pRc);
2bda0e17
KB
1013}
1014
bf1852e1 1015wxThreadError wxThread::Kill()
2bda0e17 1016{
bf1852e1
VZ
1017 if ( !IsRunning() )
1018 return wxTHREAD_NOT_RUNNING;
1019
68d41720 1020 wxThreadError rc = m_internal->Kill();
b568d04f
VZ
1021
1022 if ( IsDetached() )
1023 {
1024 delete this;
1025 }
57fd9bb2
VZ
1026 else // joinable
1027 {
1028 // update the status of the joinable thread
1029 wxCriticalSectionLocker lock(m_critsect);
1030 m_internal->SetState(STATE_EXITED);
1031 }
bf1852e1 1032
68d41720 1033 return rc;
2bda0e17
KB
1034}
1035
b568d04f 1036void wxThread::Exit(ExitCode status)
2bda0e17 1037{
9fc3ad34 1038 m_internal->Free();
2bda0e17 1039
b568d04f
VZ
1040 if ( IsDetached() )
1041 {
1042 delete this;
1043 }
57fd9bb2
VZ
1044 else // joinable
1045 {
1046 // update the status of the joinable thread
1047 wxCriticalSectionLocker lock(m_critsect);
1048 m_internal->SetState(STATE_EXITED);
1049 }
b568d04f 1050
9f51f2b6 1051#ifdef wxUSE_BEGIN_THREAD
b568d04f
VZ
1052 _endthreadex((unsigned)status);
1053#else // !VC++
bf1852e1 1054 ::ExitThread((DWORD)status);
b568d04f 1055#endif // VC++/!VC++
2bda0e17 1056
223d09f6 1057 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
bf1852e1 1058}
2bda0e17 1059
b568d04f
VZ
1060// priority setting
1061// ----------------
1062
bf1852e1
VZ
1063void wxThread::SetPriority(unsigned int prio)
1064{
1065 wxCriticalSectionLocker lock(m_critsect);
1066
9fc3ad34 1067 m_internal->SetPriority(prio);
bf1852e1 1068}
2bda0e17 1069
bf1852e1
VZ
1070unsigned int wxThread::GetPriority() const
1071{
b568d04f 1072 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
2bda0e17 1073
9fc3ad34 1074 return m_internal->GetPriority();
2bda0e17
KB
1075}
1076
b568d04f 1077unsigned long wxThread::GetId() const
2bda0e17 1078{
b568d04f 1079 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1080
9fc3ad34 1081 return (unsigned long)m_internal->GetId();
2bda0e17
KB
1082}
1083
72fd19a1
JS
1084bool wxThread::IsRunning() const
1085{
b568d04f 1086 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1087
9fc3ad34 1088 return m_internal->GetState() == STATE_RUNNING;
72fd19a1
JS
1089}
1090
1091bool wxThread::IsAlive() const
1092{
b568d04f 1093 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1094
9fc3ad34
VZ
1095 return (m_internal->GetState() == STATE_RUNNING) ||
1096 (m_internal->GetState() == STATE_PAUSED);
72fd19a1
JS
1097}
1098
a737331d
GL
1099bool wxThread::IsPaused() const
1100{
b568d04f 1101 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
a737331d 1102
9fc3ad34 1103 return m_internal->GetState() == STATE_PAUSED;
a737331d
GL
1104}
1105
8c10faf1 1106bool wxThread::TestDestroy()
2bda0e17 1107{
b568d04f 1108 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 1109
9fc3ad34 1110 return m_internal->GetState() == STATE_CANCELED;
2bda0e17
KB
1111}
1112
3222fde2
VZ
1113// ----------------------------------------------------------------------------
1114// Automatic initialization for thread module
1115// ----------------------------------------------------------------------------
2bda0e17 1116
3222fde2 1117class wxThreadModule : public wxModule
a6b0bd49 1118{
3222fde2
VZ
1119public:
1120 virtual bool OnInit();
1121 virtual void OnExit();
d524867f 1122
3222fde2
VZ
1123private:
1124 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1125};
d524867f
RR
1126
1127IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1128
3222fde2 1129bool wxThreadModule::OnInit()
d524867f 1130{
bf1852e1 1131 // allocate TLS index for storing the pointer to the current thread
b568d04f
VZ
1132 gs_tlsThisThread = ::TlsAlloc();
1133 if ( gs_tlsThisThread == 0xFFFFFFFF )
bf1852e1
VZ
1134 {
1135 // in normal circumstances it will only happen if all other
1136 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1137 // words, this should never happen
f6bcfd97 1138 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
bf1852e1
VZ
1139
1140 return FALSE;
1141 }
1142
1143 // main thread doesn't have associated wxThread object, so store 0 in the
1144 // TLS instead
b568d04f 1145 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
bf1852e1 1146 {
b568d04f
VZ
1147 ::TlsFree(gs_tlsThisThread);
1148 gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 1149
f6bcfd97 1150 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
bf1852e1
VZ
1151
1152 return FALSE;
1153 }
1154
b568d04f 1155 gs_critsectWaitingForGui = new wxCriticalSection();
bee503b0 1156
b568d04f
VZ
1157 gs_critsectGui = new wxCriticalSection();
1158 gs_critsectGui->Enter();
bee503b0 1159
bf1852e1 1160 // no error return for GetCurrentThreadId()
b568d04f 1161 gs_idMainThread = ::GetCurrentThreadId();
3222fde2 1162
d524867f
RR
1163 return TRUE;
1164}
1165
3222fde2 1166void wxThreadModule::OnExit()
d524867f 1167{
b568d04f 1168 if ( !::TlsFree(gs_tlsThisThread) )
bf1852e1 1169 {
f6bcfd97 1170 wxLogLastError(wxT("TlsFree failed."));
bf1852e1
VZ
1171 }
1172
b568d04f 1173 if ( gs_critsectGui )
3222fde2 1174 {
b568d04f
VZ
1175 gs_critsectGui->Leave();
1176 delete gs_critsectGui;
1177 gs_critsectGui = NULL;
3222fde2 1178 }
bee503b0 1179
b568d04f
VZ
1180 delete gs_critsectWaitingForGui;
1181 gs_critsectWaitingForGui = NULL;
3222fde2
VZ
1182}
1183
bee503b0 1184// ----------------------------------------------------------------------------
b568d04f 1185// under Windows, these functions are implemented using a critical section and
3222fde2 1186// not a mutex, so the names are a bit confusing
bee503b0
VZ
1187// ----------------------------------------------------------------------------
1188
0c2f35dc 1189void WXDLLIMPEXP_BASE wxMutexGuiEnter()
3222fde2 1190{
bee503b0
VZ
1191 // this would dead lock everything...
1192 wxASSERT_MSG( !wxThread::IsMain(),
223d09f6 1193 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
bee503b0
VZ
1194
1195 // the order in which we enter the critical sections here is crucial!!
1196
1197 // set the flag telling to the main thread that we want to do some GUI
1198 {
b568d04f 1199 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1200
b568d04f 1201 gs_nWaitingForGui++;
bee503b0
VZ
1202 }
1203
1204 wxWakeUpMainThread();
1205
1206 // now we may block here because the main thread will soon let us in
1207 // (during the next iteration of OnIdle())
b568d04f 1208 gs_critsectGui->Enter();
3222fde2
VZ
1209}
1210
0c2f35dc 1211void WXDLLIMPEXP_BASE wxMutexGuiLeave()
3222fde2 1212{
b568d04f 1213 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0
VZ
1214
1215 if ( wxThread::IsMain() )
1216 {
b568d04f 1217 gs_bGuiOwnedByMainThread = FALSE;
bee503b0
VZ
1218 }
1219 else
1220 {
4d1c1c3c 1221 // decrement the number of threads waiting for GUI access now
b568d04f 1222 wxASSERT_MSG( gs_nWaitingForGui > 0,
223d09f6 1223 wxT("calling wxMutexGuiLeave() without entering it first?") );
bee503b0 1224
b568d04f 1225 gs_nWaitingForGui--;
bee503b0
VZ
1226
1227 wxWakeUpMainThread();
1228 }
1229
b568d04f 1230 gs_critsectGui->Leave();
bee503b0
VZ
1231}
1232
0c2f35dc 1233void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
bee503b0
VZ
1234{
1235 wxASSERT_MSG( wxThread::IsMain(),
223d09f6 1236 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
bee503b0 1237
b568d04f 1238 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1239
b568d04f 1240 if ( gs_nWaitingForGui == 0 )
bee503b0
VZ
1241 {
1242 // no threads are waiting for GUI - so we may acquire the lock without
1243 // any danger (but only if we don't already have it)
1244 if ( !wxGuiOwnedByMainThread() )
1245 {
b568d04f 1246 gs_critsectGui->Enter();
bee503b0 1247
b568d04f 1248 gs_bGuiOwnedByMainThread = TRUE;
bee503b0
VZ
1249 }
1250 //else: already have it, nothing to do
1251 }
1252 else
1253 {
1254 // some threads are waiting, release the GUI lock if we have it
1255 if ( wxGuiOwnedByMainThread() )
1256 {
1257 wxMutexGuiLeave();
1258 }
1259 //else: some other worker thread is doing GUI
1260 }
1261}
1262
0c2f35dc 1263bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
bee503b0 1264{
b568d04f 1265 return gs_bGuiOwnedByMainThread;
bee503b0
VZ
1266}
1267
1268// wake up the main thread if it's in ::GetMessage()
0c2f35dc 1269void WXDLLIMPEXP_BASE wxWakeUpMainThread()
bee503b0
VZ
1270{
1271 // sending any message would do - hopefully WM_NULL is harmless enough
b568d04f 1272 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
bee503b0
VZ
1273 {
1274 // should never happen
f6bcfd97 1275 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
bee503b0 1276 }
3222fde2 1277}
d524867f 1278
0c2f35dc 1279bool WXDLLIMPEXP_BASE wxIsWaitingForThread()
bf1852e1 1280{
b568d04f 1281 return gs_waitingForThread;
bf1852e1
VZ
1282}
1283
9e84b847
VZ
1284// ----------------------------------------------------------------------------
1285// include common implementation code
1286// ----------------------------------------------------------------------------
1287
1288#include "wx/thrimpl.cpp"
1289
3222fde2 1290#endif // wxUSE_THREADS
6fe73788 1291