1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/thread.cpp
3 // Purpose: wxThread Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: Vadim Zeitlin to make it work :-)
8 // Copyright: (c) Wolfram Gloger (1996, 1997), Guilhem Lavaux (1998);
9 // Vadim Zeitlin (1999-2002)
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "thread.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
24 #if defined(__BORLANDC__)
34 #include "wx/msw/private.h"
36 #include "wx/module.h"
37 #include "wx/thread.h"
39 // must have this symbol defined to get _beginthread/_endthread declarations
44 #if defined(__BORLANDC__)
46 // I can't set -tWM in the IDE (anyone?) so have to do this
50 #if !defined(__MFC_COMPAT__)
51 // Needed to know about _beginthreadex etc..
52 #define __MFC_COMPAT__
56 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
57 // which should be used instead of Win32 ::CreateThread() if possible
58 #if defined(__VISUALC__) || \
59 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
60 (defined(__GNUG__) && defined(__MSVCRT__)) || \
61 defined(__WATCOMC__) || defined(__MWERKS__)
63 #undef wxUSE_BEGIN_THREAD
64 #define wxUSE_BEGIN_THREAD
67 #ifdef wxUSE_BEGIN_THREAD
68 // this is where _beginthreadex() is declared
71 // the return type of the thread function entry point
72 typedef unsigned THREAD_RETVAL
;
74 // the calling convention of the thread function entry point
75 #define THREAD_CALLCONV __stdcall
77 // the settings for CreateThread()
78 typedef DWORD THREAD_RETVAL
;
79 #define THREAD_CALLCONV WINAPI
82 // the old mingw32 headers don't have this one
83 #ifndef QS_ALLPOSTMESSAGE
84 #define QS_ALLPOSTMESSAGE 0x0100
87 // ----------------------------------------------------------------------------
89 // ----------------------------------------------------------------------------
91 // the possible states of the thread ("=>" shows all possible transitions from
95 STATE_NEW
, // didn't start execution yet (=> RUNNING)
96 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
97 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
98 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
99 STATE_EXITED
// thread is terminating
102 // ----------------------------------------------------------------------------
103 // this module globals
104 // ----------------------------------------------------------------------------
106 // TLS index of the slot where we store the pointer to the current thread
107 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
109 // id of the main thread - the one which can call GUI functions without first
110 // calling wxMutexGuiEnter()
111 static DWORD gs_idMainThread
= 0;
113 // if it's FALSE, some secondary thread is holding the GUI lock
114 static bool gs_bGuiOwnedByMainThread
= TRUE
;
116 // critical section which controls access to all GUI functions: any secondary
117 // thread (i.e. except the main one) must enter this crit section before doing
119 static wxCriticalSection
*gs_critsectGui
= NULL
;
121 // critical section which protects gs_nWaitingForGui variable
122 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
124 // number of threads waiting for GUI in wxMutexGuiEnter()
125 static size_t gs_nWaitingForGui
= 0;
127 // are we waiting for a thread termination?
128 static bool gs_waitingForThread
= FALSE
;
130 // ============================================================================
131 // Windows implementation of thread and related classes
132 // ============================================================================
134 // ----------------------------------------------------------------------------
136 // ----------------------------------------------------------------------------
138 wxCriticalSection::wxCriticalSection()
140 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
141 wxCriticalSectionBufferTooSmall
);
143 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
146 wxCriticalSection::~wxCriticalSection()
148 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
151 void wxCriticalSection::Enter()
153 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
156 void wxCriticalSection::Leave()
158 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
161 // ----------------------------------------------------------------------------
163 // ----------------------------------------------------------------------------
165 class wxMutexInternal
168 wxMutexInternal(wxMutexType mutexType
);
171 bool IsOk() const { return m_mutex
!= NULL
; }
173 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
174 wxMutexError
TryLock() { return LockTimeout(0); }
175 wxMutexError
Unlock();
178 wxMutexError
LockTimeout(DWORD milliseconds
);
183 // all mutexes are recursive under Win32 so we don't use mutexType
184 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
186 // create a nameless (hence intra process and always private) mutex
187 m_mutex
= ::CreateMutex
189 NULL
, // default secutiry attributes
190 FALSE
, // not initially locked
196 wxLogLastError(_T("CreateMutex()"));
200 wxMutexInternal::~wxMutexInternal()
204 if ( !::CloseHandle(m_mutex
) )
206 wxLogLastError(_T("CloseHandle(mutex)"));
211 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
213 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
214 if ( rc
== WAIT_ABANDONED
)
216 // the previous caller died without releasing the mutex, but now we can
218 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
220 // use 0 timeout, normally we should always get it
221 rc
= ::WaitForSingleObject(m_mutex
, 0);
233 case WAIT_ABANDONED
: // checked for above
235 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
239 wxLogLastError(_T("WaitForSingleObject(mutex)"));
240 return wxMUTEX_MISC_ERROR
;
243 return wxMUTEX_NO_ERROR
;
246 wxMutexError
wxMutexInternal::Unlock()
248 if ( !::ReleaseMutex(m_mutex
) )
250 wxLogLastError(_("ReleaseMutex()"));
252 return wxMUTEX_MISC_ERROR
;
255 return wxMUTEX_NO_ERROR
;
258 // --------------------------------------------------------------------------
260 // --------------------------------------------------------------------------
262 // a trivial wrapper around Win32 semaphore
263 class wxSemaphoreInternal
266 wxSemaphoreInternal(int initialcount
, int maxcount
);
267 ~wxSemaphoreInternal();
269 bool IsOk() const { return m_semaphore
!= NULL
; }
271 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
272 wxSemaError
TryWait() { return WaitTimeout(0); }
273 wxSemaError
WaitTimeout(unsigned long milliseconds
);
281 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
285 // make it practically infinite
289 m_semaphore
= ::CreateSemaphore
291 NULL
, // default security attributes
299 wxLogLastError(_T("CreateSemaphore()"));
303 wxSemaphoreInternal::~wxSemaphoreInternal()
307 if ( !::CloseHandle(m_semaphore
) )
309 wxLogLastError(_T("CloseHandle(semaphore)"));
314 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
316 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
321 return wxSEMA_NO_ERROR
;
327 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
330 return wxSEMA_MISC_ERROR
;
333 wxSemaError
wxSemaphoreInternal::Post()
335 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
337 wxLogLastError(_T("ReleaseSemaphore"));
339 return wxSEMA_MISC_ERROR
;
342 return wxSEMA_NO_ERROR
;
345 // --------------------------------------------------------------------------
347 // --------------------------------------------------------------------------
349 // Win32 doesn't have explicit support for the POSIX condition variables and
350 // the Win32 events have quite different semantics, so we reimplement the
351 // conditions from scratch using the mutexes and semaphores
352 class wxConditionInternal
355 wxConditionInternal(wxMutex
& mutex
);
357 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
360 wxCondError
WaitTimeout(unsigned long milliseconds
);
362 wxCondError
Signal();
363 wxCondError
Broadcast();
366 // the number of threads currently waiting for this condition
369 // the critical section protecting m_numWaiters
370 wxCriticalSection m_csWaiters
;
373 wxSemaphore m_semaphore
;
376 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
379 // another thread can't access it until we return from ctor, so no need to
380 // protect access to m_numWaiters here
384 wxCondError
wxConditionInternal::Wait()
386 // increment the number of waiters
387 ::InterlockedIncrement(&m_numWaiters
);
391 // a potential race condition can occur here
393 // after a thread increments nwaiters, and unlocks the mutex and before the
394 // semaphore.Wait() is called, if another thread can cause a signal to be
397 // this race condition is handled by using a semaphore and incrementing the
398 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
399 // can 'remember' signals the race condition will not occur
401 // wait ( if necessary ) and decrement semaphore
402 wxSemaError err
= m_semaphore
.Wait();
405 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
408 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
410 ::InterlockedIncrement(&m_numWaiters
);
414 // a race condition can occur at this point in the code
416 // please see the comments in Wait(), for details
418 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
420 if ( err
== wxSEMA_BUSY
)
422 // another potential race condition exists here it is caused when a
423 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
424 // has not yet decremented 'nwaiters'.
426 // at this point if another thread calls signal() then the semaphore
427 // will be incremented, but the waiting thread will miss it.
429 // to handle this particular case, the waiting thread calls
430 // WaitForSingleObject again with a timeout of 0, after locking
431 // 'nwaiters_mutex'. this call does not block because of the zero
432 // timeout, but will allow the waiting thread to catch the missed
434 wxCriticalSectionLocker
lock(m_csWaiters
);
436 err
= m_semaphore
.WaitTimeout(0);
438 if ( err
!= wxSEMA_NO_ERROR
)
446 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
449 wxCondError
wxConditionInternal::Signal()
451 wxCriticalSectionLocker
lock(m_csWaiters
);
453 if ( m_numWaiters
> 0 )
455 // increment the semaphore by 1
456 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
457 return wxCOND_MISC_ERROR
;
462 return wxCOND_NO_ERROR
;
465 wxCondError
wxConditionInternal::Broadcast()
467 wxCriticalSectionLocker
lock(m_csWaiters
);
469 while ( m_numWaiters
> 0 )
471 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
472 return wxCOND_MISC_ERROR
;
477 return wxCOND_NO_ERROR
;
480 // ----------------------------------------------------------------------------
481 // wxThread implementation
482 // ----------------------------------------------------------------------------
484 // wxThreadInternal class
485 // ----------------------
487 class wxThreadInternal
494 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
506 if ( !::CloseHandle(m_hThread
) )
508 wxLogLastError(wxT("CloseHandle(thread)"));
515 // create a new (suspended) thread (for the given thread object)
516 bool Create(wxThread
*thread
, unsigned int stackSize
);
518 // suspend/resume/terminate
521 void Cancel() { m_state
= STATE_CANCELED
; }
524 void SetState(wxThreadState state
) { m_state
= state
; }
525 wxThreadState
GetState() const { return m_state
; }
528 void SetPriority(unsigned int priority
);
529 unsigned int GetPriority() const { return m_priority
; }
531 // thread handle and id
532 HANDLE
GetHandle() const { return m_hThread
; }
533 DWORD
GetId() const { return m_tid
; }
536 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
539 HANDLE m_hThread
; // handle of the thread
540 wxThreadState m_state
; // state, see wxThreadState enum
541 unsigned int m_priority
; // thread priority in "wx" units
542 DWORD m_tid
; // thread id
545 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
550 // first of all, check whether we hadn't been cancelled already and don't
551 // start the user code at all then
552 wxThread
*thread
= (wxThread
*)param
;
553 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
555 rc
= (THREAD_RETVAL
)-1;
558 else // do run thread
560 // store the thread object in the TLS
561 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
563 wxLogSysError(_("Can not start thread: error writing TLS."));
568 rc
= (THREAD_RETVAL
)thread
->Entry();
570 // enter m_critsect before changing the thread state
571 thread
->m_critsect
.Enter();
572 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
573 thread
->m_internal
->SetState(STATE_EXITED
);
574 thread
->m_critsect
.Leave();
579 // if the thread was cancelled (from Delete()), then its handle is still
581 if ( thread
->IsDetached() && !wasCancelled
)
586 //else: the joinable threads handle will be closed when Wait() is done
591 void wxThreadInternal::SetPriority(unsigned int priority
)
593 m_priority
= priority
;
595 // translate wxWindows priority to the Windows one
597 if (m_priority
<= 20)
598 win_priority
= THREAD_PRIORITY_LOWEST
;
599 else if (m_priority
<= 40)
600 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
601 else if (m_priority
<= 60)
602 win_priority
= THREAD_PRIORITY_NORMAL
;
603 else if (m_priority
<= 80)
604 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
605 else if (m_priority
<= 100)
606 win_priority
= THREAD_PRIORITY_HIGHEST
;
609 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
610 win_priority
= THREAD_PRIORITY_NORMAL
;
613 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
615 wxLogSysError(_("Can't set thread priority"));
619 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
621 // for compilers which have it, we should use C RTL function for thread
622 // creation instead of Win32 API one because otherwise we will have memory
623 // leaks if the thread uses C RTL (and most threads do)
624 #ifdef wxUSE_BEGIN_THREAD
626 // Watcom is reported to not like 0 stack size (which means "use default"
627 // for the other compilers and is also the default value for stackSize)
631 #endif // __WATCOMC__
633 m_hThread
= (HANDLE
)_beginthreadex
635 NULL
, // default security
637 wxThreadInternal::WinThreadStart
, // entry point
640 (unsigned int *)&m_tid
642 #else // compiler doesn't have _beginthreadex
643 m_hThread
= ::CreateThread
645 NULL
, // default security
646 stackSize
, // stack size
647 wxThreadInternal::WinThreadStart
, // thread entry point
648 (LPVOID
)thread
, // parameter
649 CREATE_SUSPENDED
, // flags
650 &m_tid
// [out] thread id
652 #endif // _beginthreadex/CreateThread
654 if ( m_hThread
== NULL
)
656 wxLogSysError(_("Can't create thread"));
661 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
663 SetPriority(m_priority
);
669 bool wxThreadInternal::Suspend()
671 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
672 if ( nSuspendCount
== (DWORD
)-1 )
674 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
679 m_state
= STATE_PAUSED
;
684 bool wxThreadInternal::Resume()
686 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
687 if ( nSuspendCount
== (DWORD
)-1 )
689 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
694 // don't change the state from STATE_EXITED because it's special and means
695 // we are going to terminate without running any user code - if we did it,
696 // the codei n Delete() wouldn't work
697 if ( m_state
!= STATE_EXITED
)
699 m_state
= STATE_RUNNING
;
708 wxThread
*wxThread::This()
710 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
712 // be careful, 0 may be a valid return value as well
713 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
715 wxLogSysError(_("Couldn't get the current thread pointer"));
723 bool wxThread::IsMain()
725 return ::GetCurrentThreadId() == gs_idMainThread
;
732 void wxThread::Yield()
734 // 0 argument to Sleep() is special and means to just give away the rest of
739 void wxThread::Sleep(unsigned long milliseconds
)
741 ::Sleep(milliseconds
);
744 int wxThread::GetCPUCount()
749 return si
.dwNumberOfProcessors
;
752 unsigned long wxThread::GetCurrentId()
754 return (unsigned long)::GetCurrentThreadId();
757 bool wxThread::SetConcurrency(size_t level
)
759 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
761 // ok only for the default one
765 // get system affinity mask first
766 HANDLE hProcess
= ::GetCurrentProcess();
767 DWORD dwProcMask
, dwSysMask
;
768 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
770 wxLogLastError(_T("GetProcessAffinityMask"));
775 // how many CPUs have we got?
776 if ( dwSysMask
== 1 )
778 // don't bother with all this complicated stuff - on a single
779 // processor system it doesn't make much sense anyhow
783 // calculate the process mask: it's a bit vector with one bit per
784 // processor; we want to schedule the process to run on first level
789 if ( dwSysMask
& bit
)
791 // ok, we can set this bit
794 // another process added
806 // could we set all bits?
809 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
814 // set it: we can't link to SetProcessAffinityMask() because it doesn't
815 // exist in Win9x, use RT binding instead
817 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
819 // can use static var because we're always in the main thread here
820 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
822 if ( !pfnSetProcessAffinityMask
)
824 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
827 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
828 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
831 // we've discovered a MT version of Win9x!
832 wxASSERT_MSG( pfnSetProcessAffinityMask
,
833 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
836 if ( !pfnSetProcessAffinityMask
)
838 // msg given above - do it only once
842 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
844 wxLogLastError(_T("SetProcessAffinityMask"));
855 wxThread::wxThread(wxThreadKind kind
)
857 m_internal
= new wxThreadInternal();
859 m_isDetached
= kind
== wxTHREAD_DETACHED
;
862 wxThread::~wxThread()
867 // create/start thread
868 // -------------------
870 wxThreadError
wxThread::Create(unsigned int stackSize
)
872 wxCriticalSectionLocker
lock(m_critsect
);
874 if ( !m_internal
->Create(this, stackSize
) )
875 return wxTHREAD_NO_RESOURCE
;
877 return wxTHREAD_NO_ERROR
;
880 wxThreadError
wxThread::Run()
882 wxCriticalSectionLocker
lock(m_critsect
);
884 if ( m_internal
->GetState() != STATE_NEW
)
886 // actually, it may be almost any state at all, not only STATE_RUNNING
887 return wxTHREAD_RUNNING
;
890 // the thread has just been created and is still suspended - let it run
894 // suspend/resume thread
895 // ---------------------
897 wxThreadError
wxThread::Pause()
899 wxCriticalSectionLocker
lock(m_critsect
);
901 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
904 wxThreadError
wxThread::Resume()
906 wxCriticalSectionLocker
lock(m_critsect
);
908 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
914 wxThread::ExitCode
wxThread::Wait()
916 // although under Windows we can wait for any thread, it's an error to
917 // wait for a detached one in wxWin API
918 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
919 _T("can't wait for detached thread") );
921 ExitCode rc
= (ExitCode
)-1;
930 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
934 // Delete() is always safe to call, so consider all possible states
936 // we might need to resume the thread, but we might also not need to cancel
937 // it if it doesn't run yet
938 bool shouldResume
= FALSE
,
942 // check if the thread already started to run
944 wxCriticalSectionLocker
lock(m_critsect
);
946 if ( m_internal
->GetState() == STATE_NEW
)
948 // WinThreadStart() will see it and terminate immediately, no need
949 // to cancel the thread - but we still need to resume it to let it
951 m_internal
->SetState(STATE_EXITED
);
953 Resume(); // it knows about STATE_EXITED special case
955 shouldCancel
= FALSE
;
958 // shouldResume is correctly set to FALSE here
962 shouldResume
= IsPaused();
966 // resume the thread if it is paused
970 HANDLE hThread
= m_internal
->GetHandle();
972 // does is still run?
973 if ( isRunning
|| IsRunning() )
977 // set flag for wxIsWaitingForThread()
978 gs_waitingForThread
= TRUE
;
981 // ask the thread to terminate
984 wxCriticalSectionLocker
lock(m_critsect
);
986 m_internal
->Cancel();
990 // we can't just wait for the thread to terminate because it might be
991 // calling some GUI functions and so it will never terminate before we
992 // process the Windows messages that result from these functions
993 DWORD result
= 0; // suppress warnings from broken compilers
998 // give the thread we're waiting for chance to do the GUI call
1000 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1006 result
= ::MsgWaitForMultipleObjects
1008 1, // number of objects to wait for
1009 &hThread
, // the objects
1010 FALSE
, // don't wait for all objects
1011 INFINITE
, // no timeout
1012 QS_ALLINPUT
| // return as soon as there are any events
1020 wxLogSysError(_("Can not wait for thread termination"));
1022 return wxTHREAD_KILLED
;
1025 // thread we're waiting for terminated
1028 case WAIT_OBJECT_0
+ 1:
1029 // new message arrived, process it
1030 if ( !wxTheApp
->DoMessage() )
1032 // WM_QUIT received: kill the thread
1035 return wxTHREAD_KILLED
;
1040 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1042 } while ( result
!= WAIT_OBJECT_0
);
1044 // simply wait for the thread to terminate
1046 // OTOH, even console apps create windows (in wxExecute, for WinSock
1047 // &c), so may be use MsgWaitForMultipleObject() too here?
1048 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1050 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1052 #endif // wxUSE_GUI/!wxUSE_GUI
1056 gs_waitingForThread
= FALSE
;
1060 // although the thread might be already in the EXITED state it might not
1061 // have terminated yet and so we are not sure that it has actually
1062 // terminated if the "if" above hadn't been taken
1065 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1067 wxLogLastError(wxT("GetExitCodeThread"));
1071 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1075 // if the thread exits normally, this is done in WinThreadStart, but in
1076 // this case it would have been too early because
1077 // MsgWaitForMultipleObject() would fail if the thread handle was
1078 // closed while we were waiting on it, so we must do it here
1085 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1088 wxThreadError
wxThread::Kill()
1091 return wxTHREAD_NOT_RUNNING
;
1093 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1095 wxLogSysError(_("Couldn't terminate thread"));
1097 return wxTHREAD_MISC_ERROR
;
1107 return wxTHREAD_NO_ERROR
;
1110 void wxThread::Exit(ExitCode status
)
1119 #ifdef wxUSE_BEGIN_THREAD
1120 _endthreadex((unsigned)status
);
1122 ::ExitThread((DWORD
)status
);
1123 #endif // VC++/!VC++
1125 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1131 void wxThread::SetPriority(unsigned int prio
)
1133 wxCriticalSectionLocker
lock(m_critsect
);
1135 m_internal
->SetPriority(prio
);
1138 unsigned int wxThread::GetPriority() const
1140 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1142 return m_internal
->GetPriority();
1145 unsigned long wxThread::GetId() const
1147 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1149 return (unsigned long)m_internal
->GetId();
1152 bool wxThread::IsRunning() const
1154 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1156 return m_internal
->GetState() == STATE_RUNNING
;
1159 bool wxThread::IsAlive() const
1161 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1163 return (m_internal
->GetState() == STATE_RUNNING
) ||
1164 (m_internal
->GetState() == STATE_PAUSED
);
1167 bool wxThread::IsPaused() const
1169 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1171 return m_internal
->GetState() == STATE_PAUSED
;
1174 bool wxThread::TestDestroy()
1176 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1178 return m_internal
->GetState() == STATE_CANCELED
;
1181 // ----------------------------------------------------------------------------
1182 // Automatic initialization for thread module
1183 // ----------------------------------------------------------------------------
1185 class wxThreadModule
: public wxModule
1188 virtual bool OnInit();
1189 virtual void OnExit();
1192 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1195 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1197 bool wxThreadModule::OnInit()
1199 // allocate TLS index for storing the pointer to the current thread
1200 gs_tlsThisThread
= ::TlsAlloc();
1201 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1203 // in normal circumstances it will only happen if all other
1204 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1205 // words, this should never happen
1206 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1211 // main thread doesn't have associated wxThread object, so store 0 in the
1213 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1215 ::TlsFree(gs_tlsThisThread
);
1216 gs_tlsThisThread
= 0xFFFFFFFF;
1218 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1223 gs_critsectWaitingForGui
= new wxCriticalSection();
1225 gs_critsectGui
= new wxCriticalSection();
1226 gs_critsectGui
->Enter();
1228 // no error return for GetCurrentThreadId()
1229 gs_idMainThread
= ::GetCurrentThreadId();
1234 void wxThreadModule::OnExit()
1236 if ( !::TlsFree(gs_tlsThisThread
) )
1238 wxLogLastError(wxT("TlsFree failed."));
1241 if ( gs_critsectGui
)
1243 gs_critsectGui
->Leave();
1244 delete gs_critsectGui
;
1245 gs_critsectGui
= NULL
;
1248 delete gs_critsectWaitingForGui
;
1249 gs_critsectWaitingForGui
= NULL
;
1252 // ----------------------------------------------------------------------------
1253 // under Windows, these functions are implemented using a critical section and
1254 // not a mutex, so the names are a bit confusing
1255 // ----------------------------------------------------------------------------
1257 void WXDLLEXPORT
wxMutexGuiEnter()
1259 // this would dead lock everything...
1260 wxASSERT_MSG( !wxThread::IsMain(),
1261 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1263 // the order in which we enter the critical sections here is crucial!!
1265 // set the flag telling to the main thread that we want to do some GUI
1267 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1269 gs_nWaitingForGui
++;
1272 wxWakeUpMainThread();
1274 // now we may block here because the main thread will soon let us in
1275 // (during the next iteration of OnIdle())
1276 gs_critsectGui
->Enter();
1279 void WXDLLEXPORT
wxMutexGuiLeave()
1281 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1283 if ( wxThread::IsMain() )
1285 gs_bGuiOwnedByMainThread
= FALSE
;
1289 // decrement the number of threads waiting for GUI access now
1290 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1291 wxT("calling wxMutexGuiLeave() without entering it first?") );
1293 gs_nWaitingForGui
--;
1295 wxWakeUpMainThread();
1298 gs_critsectGui
->Leave();
1301 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1303 wxASSERT_MSG( wxThread::IsMain(),
1304 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1306 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1308 if ( gs_nWaitingForGui
== 0 )
1310 // no threads are waiting for GUI - so we may acquire the lock without
1311 // any danger (but only if we don't already have it)
1312 if ( !wxGuiOwnedByMainThread() )
1314 gs_critsectGui
->Enter();
1316 gs_bGuiOwnedByMainThread
= TRUE
;
1318 //else: already have it, nothing to do
1322 // some threads are waiting, release the GUI lock if we have it
1323 if ( wxGuiOwnedByMainThread() )
1327 //else: some other worker thread is doing GUI
1331 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1333 return gs_bGuiOwnedByMainThread
;
1336 // wake up the main thread if it's in ::GetMessage()
1337 void WXDLLEXPORT
wxWakeUpMainThread()
1339 // sending any message would do - hopefully WM_NULL is harmless enough
1340 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1342 // should never happen
1343 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1347 bool WXDLLEXPORT
wxIsWaitingForThread()
1349 return gs_waitingForThread
;
1352 // ----------------------------------------------------------------------------
1353 // include common implementation code
1354 // ----------------------------------------------------------------------------
1356 #include "wx/thrimpl.cpp"
1358 #endif // wxUSE_THREADS