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"
35 #include "wx/msw/missing.h"
37 #include "wx/module.h"
38 #include "wx/thread.h"
40 // must have this symbol defined to get _beginthread/_endthread declarations
45 #if defined(__BORLANDC__)
47 // I can't set -tWM in the IDE (anyone?) so have to do this
51 #if !defined(__MFC_COMPAT__)
52 // Needed to know about _beginthreadex etc..
53 #define __MFC_COMPAT__
57 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
58 // which should be used instead of Win32 ::CreateThread() if possible
59 #if defined(__VISUALC__) || \
60 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
61 (defined(__GNUG__) && defined(__MSVCRT__)) || \
62 defined(__WATCOMC__) || defined(__MWERKS__)
64 #undef wxUSE_BEGIN_THREAD
65 #define wxUSE_BEGIN_THREAD
68 #ifdef wxUSE_BEGIN_THREAD
69 // this is where _beginthreadex() is declared
72 // the return type of the thread function entry point
73 typedef unsigned THREAD_RETVAL
;
75 // the calling convention of the thread function entry point
76 #define THREAD_CALLCONV __stdcall
78 // the settings for CreateThread()
79 typedef DWORD THREAD_RETVAL
;
80 #define THREAD_CALLCONV WINAPI
83 // ----------------------------------------------------------------------------
85 // ----------------------------------------------------------------------------
87 // the possible states of the thread ("=>" shows all possible transitions from
91 STATE_NEW
, // didn't start execution yet (=> RUNNING)
92 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
93 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
94 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
95 STATE_EXITED
// thread is terminating
98 // ----------------------------------------------------------------------------
99 // this module globals
100 // ----------------------------------------------------------------------------
102 // TLS index of the slot where we store the pointer to the current thread
103 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
105 // id of the main thread - the one which can call GUI functions without first
106 // calling wxMutexGuiEnter()
107 static DWORD gs_idMainThread
= 0;
109 // if it's FALSE, some secondary thread is holding the GUI lock
110 static bool gs_bGuiOwnedByMainThread
= TRUE
;
112 // critical section which controls access to all GUI functions: any secondary
113 // thread (i.e. except the main one) must enter this crit section before doing
115 static wxCriticalSection
*gs_critsectGui
= NULL
;
117 // critical section which protects gs_nWaitingForGui variable
118 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
120 // number of threads waiting for GUI in wxMutexGuiEnter()
121 static size_t gs_nWaitingForGui
= 0;
123 // are we waiting for a thread termination?
124 static bool gs_waitingForThread
= FALSE
;
126 // ============================================================================
127 // Windows implementation of thread and related classes
128 // ============================================================================
130 // ----------------------------------------------------------------------------
132 // ----------------------------------------------------------------------------
134 wxCriticalSection::wxCriticalSection()
136 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
137 wxCriticalSectionBufferTooSmall
);
139 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
142 wxCriticalSection::~wxCriticalSection()
144 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
147 void wxCriticalSection::Enter()
149 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
152 void wxCriticalSection::Leave()
154 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
157 // ----------------------------------------------------------------------------
159 // ----------------------------------------------------------------------------
161 class wxMutexInternal
164 wxMutexInternal(wxMutexType mutexType
);
167 bool IsOk() const { return m_mutex
!= NULL
; }
169 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
170 wxMutexError
TryLock() { return LockTimeout(0); }
171 wxMutexError
Unlock();
174 wxMutexError
LockTimeout(DWORD milliseconds
);
178 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
181 // all mutexes are recursive under Win32 so we don't use mutexType
182 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
184 // create a nameless (hence intra process and always private) mutex
185 m_mutex
= ::CreateMutex
187 NULL
, // default secutiry attributes
188 FALSE
, // not initially locked
194 wxLogLastError(_T("CreateMutex()"));
198 wxMutexInternal::~wxMutexInternal()
202 if ( !::CloseHandle(m_mutex
) )
204 wxLogLastError(_T("CloseHandle(mutex)"));
209 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
211 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
212 if ( rc
== WAIT_ABANDONED
)
214 // the previous caller died without releasing the mutex, but now we can
216 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
218 // use 0 timeout, normally we should always get it
219 rc
= ::WaitForSingleObject(m_mutex
, 0);
231 case WAIT_ABANDONED
: // checked for above
233 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
237 wxLogLastError(_T("WaitForSingleObject(mutex)"));
238 return wxMUTEX_MISC_ERROR
;
241 return wxMUTEX_NO_ERROR
;
244 wxMutexError
wxMutexInternal::Unlock()
246 if ( !::ReleaseMutex(m_mutex
) )
248 wxLogLastError(_T("ReleaseMutex()"));
250 return wxMUTEX_MISC_ERROR
;
253 return wxMUTEX_NO_ERROR
;
256 // --------------------------------------------------------------------------
258 // --------------------------------------------------------------------------
260 // a trivial wrapper around Win32 semaphore
261 class wxSemaphoreInternal
264 wxSemaphoreInternal(int initialcount
, int maxcount
);
265 ~wxSemaphoreInternal();
267 bool IsOk() const { return m_semaphore
!= NULL
; }
269 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
270 wxSemaError
TryWait() { return WaitTimeout(0); }
271 wxSemaError
WaitTimeout(unsigned long milliseconds
);
278 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
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
544 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
547 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
552 // first of all, check whether we hadn't been cancelled already and don't
553 // start the user code at all then
554 wxThread
*thread
= (wxThread
*)param
;
555 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
557 rc
= (THREAD_RETVAL
)-1;
560 else // do run thread
562 // store the thread object in the TLS
563 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
565 wxLogSysError(_("Can not start thread: error writing TLS."));
570 rc
= (THREAD_RETVAL
)thread
->Entry();
572 // enter m_critsect before changing the thread state
573 thread
->m_critsect
.Enter();
574 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
575 thread
->m_internal
->SetState(STATE_EXITED
);
576 thread
->m_critsect
.Leave();
581 // if the thread was cancelled (from Delete()), then its handle is still
583 if ( thread
->IsDetached() && !wasCancelled
)
588 //else: the joinable threads handle will be closed when Wait() is done
593 void wxThreadInternal::SetPriority(unsigned int priority
)
595 m_priority
= priority
;
597 // translate wxWindows priority to the Windows one
599 if (m_priority
<= 20)
600 win_priority
= THREAD_PRIORITY_LOWEST
;
601 else if (m_priority
<= 40)
602 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
603 else if (m_priority
<= 60)
604 win_priority
= THREAD_PRIORITY_NORMAL
;
605 else if (m_priority
<= 80)
606 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
607 else if (m_priority
<= 100)
608 win_priority
= THREAD_PRIORITY_HIGHEST
;
611 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
612 win_priority
= THREAD_PRIORITY_NORMAL
;
615 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
617 wxLogSysError(_("Can't set thread priority"));
621 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
623 // for compilers which have it, we should use C RTL function for thread
624 // creation instead of Win32 API one because otherwise we will have memory
625 // leaks if the thread uses C RTL (and most threads do)
626 #ifdef wxUSE_BEGIN_THREAD
628 // Watcom is reported to not like 0 stack size (which means "use default"
629 // for the other compilers and is also the default value for stackSize)
633 #endif // __WATCOMC__
635 m_hThread
= (HANDLE
)_beginthreadex
637 NULL
, // default security
639 wxThreadInternal::WinThreadStart
, // entry point
642 (unsigned int *)&m_tid
644 #else // compiler doesn't have _beginthreadex
645 m_hThread
= ::CreateThread
647 NULL
, // default security
648 stackSize
, // stack size
649 wxThreadInternal::WinThreadStart
, // thread entry point
650 (LPVOID
)thread
, // parameter
651 CREATE_SUSPENDED
, // flags
652 &m_tid
// [out] thread id
654 #endif // _beginthreadex/CreateThread
656 if ( m_hThread
== NULL
)
658 wxLogSysError(_("Can't create thread"));
663 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
665 SetPriority(m_priority
);
671 bool wxThreadInternal::Suspend()
673 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
674 if ( nSuspendCount
== (DWORD
)-1 )
676 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
681 m_state
= STATE_PAUSED
;
686 bool wxThreadInternal::Resume()
688 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
689 if ( nSuspendCount
== (DWORD
)-1 )
691 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
696 // don't change the state from STATE_EXITED because it's special and means
697 // we are going to terminate without running any user code - if we did it,
698 // the codei n Delete() wouldn't work
699 if ( m_state
!= STATE_EXITED
)
701 m_state
= STATE_RUNNING
;
710 wxThread
*wxThread::This()
712 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
714 // be careful, 0 may be a valid return value as well
715 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
717 wxLogSysError(_("Couldn't get the current thread pointer"));
725 bool wxThread::IsMain()
727 return ::GetCurrentThreadId() == gs_idMainThread
;
734 void wxThread::Yield()
736 // 0 argument to Sleep() is special and means to just give away the rest of
741 void wxThread::Sleep(unsigned long milliseconds
)
743 ::Sleep(milliseconds
);
746 int wxThread::GetCPUCount()
751 return si
.dwNumberOfProcessors
;
754 unsigned long wxThread::GetCurrentId()
756 return (unsigned long)::GetCurrentThreadId();
759 bool wxThread::SetConcurrency(size_t level
)
761 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
763 // ok only for the default one
767 // get system affinity mask first
768 HANDLE hProcess
= ::GetCurrentProcess();
769 DWORD dwProcMask
, dwSysMask
;
770 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
772 wxLogLastError(_T("GetProcessAffinityMask"));
777 // how many CPUs have we got?
778 if ( dwSysMask
== 1 )
780 // don't bother with all this complicated stuff - on a single
781 // processor system it doesn't make much sense anyhow
785 // calculate the process mask: it's a bit vector with one bit per
786 // processor; we want to schedule the process to run on first level
791 if ( dwSysMask
& bit
)
793 // ok, we can set this bit
796 // another process added
808 // could we set all bits?
811 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
816 // set it: we can't link to SetProcessAffinityMask() because it doesn't
817 // exist in Win9x, use RT binding instead
819 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
821 // can use static var because we're always in the main thread here
822 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
824 if ( !pfnSetProcessAffinityMask
)
826 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
829 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
830 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
833 // we've discovered a MT version of Win9x!
834 wxASSERT_MSG( pfnSetProcessAffinityMask
,
835 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
838 if ( !pfnSetProcessAffinityMask
)
840 // msg given above - do it only once
844 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
846 wxLogLastError(_T("SetProcessAffinityMask"));
857 wxThread::wxThread(wxThreadKind kind
)
859 m_internal
= new wxThreadInternal();
861 m_isDetached
= kind
== wxTHREAD_DETACHED
;
864 wxThread::~wxThread()
869 // create/start thread
870 // -------------------
872 wxThreadError
wxThread::Create(unsigned int stackSize
)
874 wxCriticalSectionLocker
lock(m_critsect
);
876 if ( !m_internal
->Create(this, stackSize
) )
877 return wxTHREAD_NO_RESOURCE
;
879 return wxTHREAD_NO_ERROR
;
882 wxThreadError
wxThread::Run()
884 wxCriticalSectionLocker
lock(m_critsect
);
886 if ( m_internal
->GetState() != STATE_NEW
)
888 // actually, it may be almost any state at all, not only STATE_RUNNING
889 return wxTHREAD_RUNNING
;
892 // the thread has just been created and is still suspended - let it run
896 // suspend/resume thread
897 // ---------------------
899 wxThreadError
wxThread::Pause()
901 wxCriticalSectionLocker
lock(m_critsect
);
903 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
906 wxThreadError
wxThread::Resume()
908 wxCriticalSectionLocker
lock(m_critsect
);
910 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
916 wxThread::ExitCode
wxThread::Wait()
918 // although under Windows we can wait for any thread, it's an error to
919 // wait for a detached one in wxWin API
920 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
921 _T("can't wait for detached thread") );
923 ExitCode rc
= (ExitCode
)-1;
932 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
936 // Delete() is always safe to call, so consider all possible states
938 // we might need to resume the thread, but we might also not need to cancel
939 // it if it doesn't run yet
940 bool shouldResume
= FALSE
,
944 // check if the thread already started to run
946 wxCriticalSectionLocker
lock(m_critsect
);
948 if ( m_internal
->GetState() == STATE_NEW
)
950 // WinThreadStart() will see it and terminate immediately, no need
951 // to cancel the thread - but we still need to resume it to let it
953 m_internal
->SetState(STATE_EXITED
);
955 Resume(); // it knows about STATE_EXITED special case
957 shouldCancel
= FALSE
;
960 // shouldResume is correctly set to FALSE here
964 shouldResume
= IsPaused();
968 // resume the thread if it is paused
972 HANDLE hThread
= m_internal
->GetHandle();
974 // does is still run?
975 if ( isRunning
|| IsRunning() )
979 // set flag for wxIsWaitingForThread()
980 gs_waitingForThread
= TRUE
;
983 // ask the thread to terminate
986 wxCriticalSectionLocker
lock(m_critsect
);
988 m_internal
->Cancel();
992 // we can't just wait for the thread to terminate because it might be
993 // calling some GUI functions and so it will never terminate before we
994 // process the Windows messages that result from these functions
995 DWORD result
= 0; // suppress warnings from broken compilers
1000 // give the thread we're waiting for chance to do the GUI call
1002 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1008 result
= ::MsgWaitForMultipleObjects
1010 1, // number of objects to wait for
1011 &hThread
, // the objects
1012 FALSE
, // don't wait for all objects
1013 INFINITE
, // no timeout
1014 QS_ALLINPUT
| // return as soon as there are any events
1022 wxLogSysError(_("Can not wait for thread termination"));
1024 return wxTHREAD_KILLED
;
1027 // thread we're waiting for terminated
1030 case WAIT_OBJECT_0
+ 1:
1031 // new message arrived, process it
1032 if ( !wxTheApp
->DoMessage() )
1034 // WM_QUIT received: kill the thread
1037 return wxTHREAD_KILLED
;
1042 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1044 } while ( result
!= WAIT_OBJECT_0
);
1046 // simply wait for the thread to terminate
1048 // OTOH, even console apps create windows (in wxExecute, for WinSock
1049 // &c), so may be use MsgWaitForMultipleObject() too here?
1050 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1052 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1054 #endif // wxUSE_GUI/!wxUSE_GUI
1058 gs_waitingForThread
= FALSE
;
1062 // although the thread might be already in the EXITED state it might not
1063 // have terminated yet and so we are not sure that it has actually
1064 // terminated if the "if" above hadn't been taken
1067 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1069 wxLogLastError(wxT("GetExitCodeThread"));
1073 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1077 // if the thread exits normally, this is done in WinThreadStart, but in
1078 // this case it would have been too early because
1079 // MsgWaitForMultipleObject() would fail if the thread handle was
1080 // closed while we were waiting on it, so we must do it here
1087 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1090 wxThreadError
wxThread::Kill()
1093 return wxTHREAD_NOT_RUNNING
;
1095 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1097 wxLogSysError(_("Couldn't terminate thread"));
1099 return wxTHREAD_MISC_ERROR
;
1109 return wxTHREAD_NO_ERROR
;
1112 void wxThread::Exit(ExitCode status
)
1121 #ifdef wxUSE_BEGIN_THREAD
1122 _endthreadex((unsigned)status
);
1124 ::ExitThread((DWORD
)status
);
1125 #endif // VC++/!VC++
1127 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1133 void wxThread::SetPriority(unsigned int prio
)
1135 wxCriticalSectionLocker
lock(m_critsect
);
1137 m_internal
->SetPriority(prio
);
1140 unsigned int wxThread::GetPriority() const
1142 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1144 return m_internal
->GetPriority();
1147 unsigned long wxThread::GetId() const
1149 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1151 return (unsigned long)m_internal
->GetId();
1154 bool wxThread::IsRunning() const
1156 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1158 return m_internal
->GetState() == STATE_RUNNING
;
1161 bool wxThread::IsAlive() const
1163 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1165 return (m_internal
->GetState() == STATE_RUNNING
) ||
1166 (m_internal
->GetState() == STATE_PAUSED
);
1169 bool wxThread::IsPaused() const
1171 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1173 return m_internal
->GetState() == STATE_PAUSED
;
1176 bool wxThread::TestDestroy()
1178 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1180 return m_internal
->GetState() == STATE_CANCELED
;
1183 // ----------------------------------------------------------------------------
1184 // Automatic initialization for thread module
1185 // ----------------------------------------------------------------------------
1187 class wxThreadModule
: public wxModule
1190 virtual bool OnInit();
1191 virtual void OnExit();
1194 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1197 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1199 bool wxThreadModule::OnInit()
1201 // allocate TLS index for storing the pointer to the current thread
1202 gs_tlsThisThread
= ::TlsAlloc();
1203 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1205 // in normal circumstances it will only happen if all other
1206 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1207 // words, this should never happen
1208 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1213 // main thread doesn't have associated wxThread object, so store 0 in the
1215 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1217 ::TlsFree(gs_tlsThisThread
);
1218 gs_tlsThisThread
= 0xFFFFFFFF;
1220 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1225 gs_critsectWaitingForGui
= new wxCriticalSection();
1227 gs_critsectGui
= new wxCriticalSection();
1228 gs_critsectGui
->Enter();
1230 // no error return for GetCurrentThreadId()
1231 gs_idMainThread
= ::GetCurrentThreadId();
1236 void wxThreadModule::OnExit()
1238 if ( !::TlsFree(gs_tlsThisThread
) )
1240 wxLogLastError(wxT("TlsFree failed."));
1243 if ( gs_critsectGui
)
1245 gs_critsectGui
->Leave();
1246 delete gs_critsectGui
;
1247 gs_critsectGui
= NULL
;
1250 delete gs_critsectWaitingForGui
;
1251 gs_critsectWaitingForGui
= NULL
;
1254 // ----------------------------------------------------------------------------
1255 // under Windows, these functions are implemented using a critical section and
1256 // not a mutex, so the names are a bit confusing
1257 // ----------------------------------------------------------------------------
1259 void WXDLLEXPORT
wxMutexGuiEnter()
1261 // this would dead lock everything...
1262 wxASSERT_MSG( !wxThread::IsMain(),
1263 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1265 // the order in which we enter the critical sections here is crucial!!
1267 // set the flag telling to the main thread that we want to do some GUI
1269 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1271 gs_nWaitingForGui
++;
1274 wxWakeUpMainThread();
1276 // now we may block here because the main thread will soon let us in
1277 // (during the next iteration of OnIdle())
1278 gs_critsectGui
->Enter();
1281 void WXDLLEXPORT
wxMutexGuiLeave()
1283 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1285 if ( wxThread::IsMain() )
1287 gs_bGuiOwnedByMainThread
= FALSE
;
1291 // decrement the number of threads waiting for GUI access now
1292 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1293 wxT("calling wxMutexGuiLeave() without entering it first?") );
1295 gs_nWaitingForGui
--;
1297 wxWakeUpMainThread();
1300 gs_critsectGui
->Leave();
1303 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1305 wxASSERT_MSG( wxThread::IsMain(),
1306 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1308 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1310 if ( gs_nWaitingForGui
== 0 )
1312 // no threads are waiting for GUI - so we may acquire the lock without
1313 // any danger (but only if we don't already have it)
1314 if ( !wxGuiOwnedByMainThread() )
1316 gs_critsectGui
->Enter();
1318 gs_bGuiOwnedByMainThread
= TRUE
;
1320 //else: already have it, nothing to do
1324 // some threads are waiting, release the GUI lock if we have it
1325 if ( wxGuiOwnedByMainThread() )
1329 //else: some other worker thread is doing GUI
1333 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1335 return gs_bGuiOwnedByMainThread
;
1338 // wake up the main thread if it's in ::GetMessage()
1339 void WXDLLEXPORT
wxWakeUpMainThread()
1341 // sending any message would do - hopefully WM_NULL is harmless enough
1342 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1344 // should never happen
1345 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1349 bool WXDLLEXPORT
wxIsWaitingForThread()
1351 return gs_waitingForThread
;
1354 // ----------------------------------------------------------------------------
1355 // include common implementation code
1356 // ----------------------------------------------------------------------------
1358 #include "wx/thrimpl.cpp"
1360 #endif // wxUSE_THREADS