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
); }
271 wxSemaError
TryWait()
273 wxSemaError rc
= WaitTimeout(0);
274 if ( rc
== wxSEMA_TIMEOUT
)
280 wxSemaError
WaitTimeout(unsigned long milliseconds
);
287 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
290 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
294 // make it practically infinite
298 m_semaphore
= ::CreateSemaphore
300 NULL
, // default security attributes
308 wxLogLastError(_T("CreateSemaphore()"));
312 wxSemaphoreInternal::~wxSemaphoreInternal()
316 if ( !::CloseHandle(m_semaphore
) )
318 wxLogLastError(_T("CloseHandle(semaphore)"));
323 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
325 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
330 return wxSEMA_NO_ERROR
;
333 return wxSEMA_TIMEOUT
;
336 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
339 return wxSEMA_MISC_ERROR
;
342 wxSemaError
wxSemaphoreInternal::Post()
344 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
346 wxLogLastError(_T("ReleaseSemaphore"));
348 return wxSEMA_MISC_ERROR
;
351 return wxSEMA_NO_ERROR
;
354 // --------------------------------------------------------------------------
356 // --------------------------------------------------------------------------
358 // Win32 doesn't have explicit support for the POSIX condition variables and
359 // the Win32 events have quite different semantics, so we reimplement the
360 // conditions from scratch using the mutexes and semaphores
361 class wxConditionInternal
364 wxConditionInternal(wxMutex
& mutex
);
366 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
369 wxCondError
WaitTimeout(unsigned long milliseconds
);
371 wxCondError
Signal();
372 wxCondError
Broadcast();
375 // the number of threads currently waiting for this condition
378 // the critical section protecting m_numWaiters
379 wxCriticalSection m_csWaiters
;
382 wxSemaphore m_semaphore
;
385 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
388 // another thread can't access it until we return from ctor, so no need to
389 // protect access to m_numWaiters here
393 wxCondError
wxConditionInternal::Wait()
395 // increment the number of waiters
396 ::InterlockedIncrement(&m_numWaiters
);
400 // a potential race condition can occur here
402 // after a thread increments nwaiters, and unlocks the mutex and before the
403 // semaphore.Wait() is called, if another thread can cause a signal to be
406 // this race condition is handled by using a semaphore and incrementing the
407 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
408 // can 'remember' signals the race condition will not occur
410 // wait ( if necessary ) and decrement semaphore
411 wxSemaError err
= m_semaphore
.Wait();
414 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
417 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
419 ::InterlockedIncrement(&m_numWaiters
);
423 // a race condition can occur at this point in the code
425 // please see the comments in Wait(), for details
427 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
429 if ( err
== wxSEMA_BUSY
)
431 // another potential race condition exists here it is caused when a
432 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
433 // has not yet decremented 'nwaiters'.
435 // at this point if another thread calls signal() then the semaphore
436 // will be incremented, but the waiting thread will miss it.
438 // to handle this particular case, the waiting thread calls
439 // WaitForSingleObject again with a timeout of 0, after locking
440 // 'nwaiters_mutex'. this call does not block because of the zero
441 // timeout, but will allow the waiting thread to catch the missed
443 wxCriticalSectionLocker
lock(m_csWaiters
);
445 err
= m_semaphore
.WaitTimeout(0);
447 if ( err
!= wxSEMA_NO_ERROR
)
455 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
458 wxCondError
wxConditionInternal::Signal()
460 wxCriticalSectionLocker
lock(m_csWaiters
);
462 if ( m_numWaiters
> 0 )
464 // increment the semaphore by 1
465 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
466 return wxCOND_MISC_ERROR
;
471 return wxCOND_NO_ERROR
;
474 wxCondError
wxConditionInternal::Broadcast()
476 wxCriticalSectionLocker
lock(m_csWaiters
);
478 while ( m_numWaiters
> 0 )
480 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
481 return wxCOND_MISC_ERROR
;
486 return wxCOND_NO_ERROR
;
489 // ----------------------------------------------------------------------------
490 // wxThread implementation
491 // ----------------------------------------------------------------------------
493 // wxThreadInternal class
494 // ----------------------
496 class wxThreadInternal
503 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
515 if ( !::CloseHandle(m_hThread
) )
517 wxLogLastError(wxT("CloseHandle(thread)"));
524 // create a new (suspended) thread (for the given thread object)
525 bool Create(wxThread
*thread
, unsigned int stackSize
);
527 // suspend/resume/terminate
530 void Cancel() { m_state
= STATE_CANCELED
; }
533 void SetState(wxThreadState state
) { m_state
= state
; }
534 wxThreadState
GetState() const { return m_state
; }
537 void SetPriority(unsigned int priority
);
538 unsigned int GetPriority() const { return m_priority
; }
540 // thread handle and id
541 HANDLE
GetHandle() const { return m_hThread
; }
542 DWORD
GetId() const { return m_tid
; }
545 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
548 HANDLE m_hThread
; // handle of the thread
549 wxThreadState m_state
; // state, see wxThreadState enum
550 unsigned int m_priority
; // thread priority in "wx" units
551 DWORD m_tid
; // thread id
553 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
556 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
561 // first of all, check whether we hadn't been cancelled already and don't
562 // start the user code at all then
563 wxThread
*thread
= (wxThread
*)param
;
564 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
566 rc
= (THREAD_RETVAL
)-1;
569 else // do run thread
571 // store the thread object in the TLS
572 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
574 wxLogSysError(_("Can not start thread: error writing TLS."));
579 rc
= (THREAD_RETVAL
)thread
->Entry();
581 // enter m_critsect before changing the thread state
582 thread
->m_critsect
.Enter();
583 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
584 thread
->m_internal
->SetState(STATE_EXITED
);
585 thread
->m_critsect
.Leave();
590 // if the thread was cancelled (from Delete()), then its handle is still
592 if ( thread
->IsDetached() && !wasCancelled
)
597 //else: the joinable threads handle will be closed when Wait() is done
602 void wxThreadInternal::SetPriority(unsigned int priority
)
604 m_priority
= priority
;
606 // translate wxWindows priority to the Windows one
608 if (m_priority
<= 20)
609 win_priority
= THREAD_PRIORITY_LOWEST
;
610 else if (m_priority
<= 40)
611 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
612 else if (m_priority
<= 60)
613 win_priority
= THREAD_PRIORITY_NORMAL
;
614 else if (m_priority
<= 80)
615 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
616 else if (m_priority
<= 100)
617 win_priority
= THREAD_PRIORITY_HIGHEST
;
620 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
621 win_priority
= THREAD_PRIORITY_NORMAL
;
624 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
626 wxLogSysError(_("Can't set thread priority"));
630 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
632 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
633 _T("Create()ing thread twice?") );
635 // for compilers which have it, we should use C RTL function for thread
636 // creation instead of Win32 API one because otherwise we will have memory
637 // leaks if the thread uses C RTL (and most threads do)
638 #ifdef wxUSE_BEGIN_THREAD
640 // Watcom is reported to not like 0 stack size (which means "use default"
641 // for the other compilers and is also the default value for stackSize)
645 #endif // __WATCOMC__
647 m_hThread
= (HANDLE
)_beginthreadex
649 NULL
, // default security
651 wxThreadInternal::WinThreadStart
, // entry point
654 (unsigned int *)&m_tid
656 #else // compiler doesn't have _beginthreadex
657 m_hThread
= ::CreateThread
659 NULL
, // default security
660 stackSize
, // stack size
661 wxThreadInternal::WinThreadStart
, // thread entry point
662 (LPVOID
)thread
, // parameter
663 CREATE_SUSPENDED
, // flags
664 &m_tid
// [out] thread id
666 #endif // _beginthreadex/CreateThread
668 if ( m_hThread
== NULL
)
670 wxLogSysError(_("Can't create thread"));
675 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
677 SetPriority(m_priority
);
683 bool wxThreadInternal::Suspend()
685 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
686 if ( nSuspendCount
== (DWORD
)-1 )
688 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
693 m_state
= STATE_PAUSED
;
698 bool wxThreadInternal::Resume()
700 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
701 if ( nSuspendCount
== (DWORD
)-1 )
703 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
708 // don't change the state from STATE_EXITED because it's special and means
709 // we are going to terminate without running any user code - if we did it,
710 // the codei n Delete() wouldn't work
711 if ( m_state
!= STATE_EXITED
)
713 m_state
= STATE_RUNNING
;
722 wxThread
*wxThread::This()
724 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
726 // be careful, 0 may be a valid return value as well
727 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
729 wxLogSysError(_("Couldn't get the current thread pointer"));
737 bool wxThread::IsMain()
739 return ::GetCurrentThreadId() == gs_idMainThread
;
746 void wxThread::Yield()
748 // 0 argument to Sleep() is special and means to just give away the rest of
753 void wxThread::Sleep(unsigned long milliseconds
)
755 ::Sleep(milliseconds
);
758 int wxThread::GetCPUCount()
763 return si
.dwNumberOfProcessors
;
766 unsigned long wxThread::GetCurrentId()
768 return (unsigned long)::GetCurrentThreadId();
771 bool wxThread::SetConcurrency(size_t level
)
773 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
775 // ok only for the default one
779 // get system affinity mask first
780 HANDLE hProcess
= ::GetCurrentProcess();
781 DWORD dwProcMask
, dwSysMask
;
782 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
784 wxLogLastError(_T("GetProcessAffinityMask"));
789 // how many CPUs have we got?
790 if ( dwSysMask
== 1 )
792 // don't bother with all this complicated stuff - on a single
793 // processor system it doesn't make much sense anyhow
797 // calculate the process mask: it's a bit vector with one bit per
798 // processor; we want to schedule the process to run on first level
803 if ( dwSysMask
& bit
)
805 // ok, we can set this bit
808 // another process added
820 // could we set all bits?
823 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
828 // set it: we can't link to SetProcessAffinityMask() because it doesn't
829 // exist in Win9x, use RT binding instead
831 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
833 // can use static var because we're always in the main thread here
834 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
836 if ( !pfnSetProcessAffinityMask
)
838 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
841 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
842 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
845 // we've discovered a MT version of Win9x!
846 wxASSERT_MSG( pfnSetProcessAffinityMask
,
847 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
850 if ( !pfnSetProcessAffinityMask
)
852 // msg given above - do it only once
856 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
858 wxLogLastError(_T("SetProcessAffinityMask"));
869 wxThread::wxThread(wxThreadKind kind
)
871 m_internal
= new wxThreadInternal();
873 m_isDetached
= kind
== wxTHREAD_DETACHED
;
876 wxThread::~wxThread()
881 // create/start thread
882 // -------------------
884 wxThreadError
wxThread::Create(unsigned int stackSize
)
886 wxCriticalSectionLocker
lock(m_critsect
);
888 if ( !m_internal
->Create(this, stackSize
) )
889 return wxTHREAD_NO_RESOURCE
;
891 return wxTHREAD_NO_ERROR
;
894 wxThreadError
wxThread::Run()
896 wxCriticalSectionLocker
lock(m_critsect
);
898 if ( m_internal
->GetState() != STATE_NEW
)
900 // actually, it may be almost any state at all, not only STATE_RUNNING
901 return wxTHREAD_RUNNING
;
904 // the thread has just been created and is still suspended - let it run
908 // suspend/resume thread
909 // ---------------------
911 wxThreadError
wxThread::Pause()
913 wxCriticalSectionLocker
lock(m_critsect
);
915 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
918 wxThreadError
wxThread::Resume()
920 wxCriticalSectionLocker
lock(m_critsect
);
922 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
928 wxThread::ExitCode
wxThread::Wait()
930 // although under Windows we can wait for any thread, it's an error to
931 // wait for a detached one in wxWin API
932 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
933 _T("can't wait for detached thread") );
935 ExitCode rc
= (ExitCode
)-1;
944 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
948 // Delete() is always safe to call, so consider all possible states
950 // we might need to resume the thread, but we might also not need to cancel
951 // it if it doesn't run yet
952 bool shouldResume
= FALSE
,
956 // check if the thread already started to run
958 wxCriticalSectionLocker
lock(m_critsect
);
960 if ( m_internal
->GetState() == STATE_NEW
)
962 // WinThreadStart() will see it and terminate immediately, no need
963 // to cancel the thread - but we still need to resume it to let it
965 m_internal
->SetState(STATE_EXITED
);
967 Resume(); // it knows about STATE_EXITED special case
969 shouldCancel
= FALSE
;
972 // shouldResume is correctly set to FALSE here
976 shouldResume
= IsPaused();
980 // resume the thread if it is paused
984 HANDLE hThread
= m_internal
->GetHandle();
986 // does is still run?
987 if ( isRunning
|| IsRunning() )
991 // set flag for wxIsWaitingForThread()
992 gs_waitingForThread
= TRUE
;
995 // ask the thread to terminate
998 wxCriticalSectionLocker
lock(m_critsect
);
1000 m_internal
->Cancel();
1004 // we can't just wait for the thread to terminate because it might be
1005 // calling some GUI functions and so it will never terminate before we
1006 // process the Windows messages that result from these functions
1007 DWORD result
= 0; // suppress warnings from broken compilers
1012 // give the thread we're waiting for chance to do the GUI call
1014 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1020 result
= ::MsgWaitForMultipleObjects
1022 1, // number of objects to wait for
1023 &hThread
, // the objects
1024 FALSE
, // don't wait for all objects
1025 INFINITE
, // no timeout
1026 QS_ALLINPUT
| // return as soon as there are any events
1034 wxLogSysError(_("Can not wait for thread termination"));
1036 return wxTHREAD_KILLED
;
1039 // thread we're waiting for terminated
1042 case WAIT_OBJECT_0
+ 1:
1043 // new message arrived, process it
1044 if ( !wxTheApp
->DoMessage() )
1046 // WM_QUIT received: kill the thread
1049 return wxTHREAD_KILLED
;
1054 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1056 } while ( result
!= WAIT_OBJECT_0
);
1058 // simply wait for the thread to terminate
1060 // OTOH, even console apps create windows (in wxExecute, for WinSock
1061 // &c), so may be use MsgWaitForMultipleObject() too here?
1062 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1064 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1066 #endif // wxUSE_GUI/!wxUSE_GUI
1070 gs_waitingForThread
= FALSE
;
1074 // although the thread might be already in the EXITED state it might not
1075 // have terminated yet and so we are not sure that it has actually
1076 // terminated if the "if" above hadn't been taken
1079 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1081 wxLogLastError(wxT("GetExitCodeThread"));
1085 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1089 // if the thread exits normally, this is done in WinThreadStart, but in
1090 // this case it would have been too early because
1091 // MsgWaitForMultipleObject() would fail if the thread handle was
1092 // closed while we were waiting on it, so we must do it here
1099 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1102 wxThreadError
wxThread::Kill()
1105 return wxTHREAD_NOT_RUNNING
;
1107 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1109 wxLogSysError(_("Couldn't terminate thread"));
1111 return wxTHREAD_MISC_ERROR
;
1121 return wxTHREAD_NO_ERROR
;
1124 void wxThread::Exit(ExitCode status
)
1133 #ifdef wxUSE_BEGIN_THREAD
1134 _endthreadex((unsigned)status
);
1136 ::ExitThread((DWORD
)status
);
1137 #endif // VC++/!VC++
1139 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1145 void wxThread::SetPriority(unsigned int prio
)
1147 wxCriticalSectionLocker
lock(m_critsect
);
1149 m_internal
->SetPriority(prio
);
1152 unsigned int wxThread::GetPriority() const
1154 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1156 return m_internal
->GetPriority();
1159 unsigned long wxThread::GetId() const
1161 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1163 return (unsigned long)m_internal
->GetId();
1166 bool wxThread::IsRunning() const
1168 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1170 return m_internal
->GetState() == STATE_RUNNING
;
1173 bool wxThread::IsAlive() const
1175 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1177 return (m_internal
->GetState() == STATE_RUNNING
) ||
1178 (m_internal
->GetState() == STATE_PAUSED
);
1181 bool wxThread::IsPaused() const
1183 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1185 return m_internal
->GetState() == STATE_PAUSED
;
1188 bool wxThread::TestDestroy()
1190 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1192 return m_internal
->GetState() == STATE_CANCELED
;
1195 // ----------------------------------------------------------------------------
1196 // Automatic initialization for thread module
1197 // ----------------------------------------------------------------------------
1199 class wxThreadModule
: public wxModule
1202 virtual bool OnInit();
1203 virtual void OnExit();
1206 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1209 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1211 bool wxThreadModule::OnInit()
1213 // allocate TLS index for storing the pointer to the current thread
1214 gs_tlsThisThread
= ::TlsAlloc();
1215 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1217 // in normal circumstances it will only happen if all other
1218 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1219 // words, this should never happen
1220 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1225 // main thread doesn't have associated wxThread object, so store 0 in the
1227 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1229 ::TlsFree(gs_tlsThisThread
);
1230 gs_tlsThisThread
= 0xFFFFFFFF;
1232 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1237 gs_critsectWaitingForGui
= new wxCriticalSection();
1239 gs_critsectGui
= new wxCriticalSection();
1240 gs_critsectGui
->Enter();
1242 // no error return for GetCurrentThreadId()
1243 gs_idMainThread
= ::GetCurrentThreadId();
1248 void wxThreadModule::OnExit()
1250 if ( !::TlsFree(gs_tlsThisThread
) )
1252 wxLogLastError(wxT("TlsFree failed."));
1255 if ( gs_critsectGui
)
1257 gs_critsectGui
->Leave();
1258 delete gs_critsectGui
;
1259 gs_critsectGui
= NULL
;
1262 delete gs_critsectWaitingForGui
;
1263 gs_critsectWaitingForGui
= NULL
;
1266 // ----------------------------------------------------------------------------
1267 // under Windows, these functions are implemented using a critical section and
1268 // not a mutex, so the names are a bit confusing
1269 // ----------------------------------------------------------------------------
1271 void WXDLLEXPORT
wxMutexGuiEnter()
1273 // this would dead lock everything...
1274 wxASSERT_MSG( !wxThread::IsMain(),
1275 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1277 // the order in which we enter the critical sections here is crucial!!
1279 // set the flag telling to the main thread that we want to do some GUI
1281 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1283 gs_nWaitingForGui
++;
1286 wxWakeUpMainThread();
1288 // now we may block here because the main thread will soon let us in
1289 // (during the next iteration of OnIdle())
1290 gs_critsectGui
->Enter();
1293 void WXDLLEXPORT
wxMutexGuiLeave()
1295 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1297 if ( wxThread::IsMain() )
1299 gs_bGuiOwnedByMainThread
= FALSE
;
1303 // decrement the number of threads waiting for GUI access now
1304 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1305 wxT("calling wxMutexGuiLeave() without entering it first?") );
1307 gs_nWaitingForGui
--;
1309 wxWakeUpMainThread();
1312 gs_critsectGui
->Leave();
1315 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1317 wxASSERT_MSG( wxThread::IsMain(),
1318 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1320 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1322 if ( gs_nWaitingForGui
== 0 )
1324 // no threads are waiting for GUI - so we may acquire the lock without
1325 // any danger (but only if we don't already have it)
1326 if ( !wxGuiOwnedByMainThread() )
1328 gs_critsectGui
->Enter();
1330 gs_bGuiOwnedByMainThread
= TRUE
;
1332 //else: already have it, nothing to do
1336 // some threads are waiting, release the GUI lock if we have it
1337 if ( wxGuiOwnedByMainThread() )
1341 //else: some other worker thread is doing GUI
1345 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1347 return gs_bGuiOwnedByMainThread
;
1350 // wake up the main thread if it's in ::GetMessage()
1351 void WXDLLEXPORT
wxWakeUpMainThread()
1353 // sending any message would do - hopefully WM_NULL is harmless enough
1354 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1356 // should never happen
1357 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1361 bool WXDLLEXPORT
wxIsWaitingForThread()
1363 return gs_waitingForThread
;
1366 // ----------------------------------------------------------------------------
1367 // include common implementation code
1368 // ----------------------------------------------------------------------------
1370 #include "wx/thrimpl.cpp"
1372 #endif // wxUSE_THREADS