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__)
33 #include "wx/apptrait.h"
35 #include "wx/msw/private.h"
36 #include "wx/msw/missing.h"
38 #include "wx/module.h"
39 #include "wx/thread.h"
41 // must have this symbol defined to get _beginthread/_endthread declarations
46 #if defined(__BORLANDC__)
48 // I can't set -tWM in the IDE (anyone?) so have to do this
52 #if !defined(__MFC_COMPAT__)
53 // Needed to know about _beginthreadex etc..
54 #define __MFC_COMPAT__
58 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
59 // which should be used instead of Win32 ::CreateThread() if possible
60 #if defined(__VISUALC__) || \
61 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
62 (defined(__GNUG__) && defined(__MSVCRT__)) || \
63 defined(__WATCOMC__) || defined(__MWERKS__)
65 #undef wxUSE_BEGIN_THREAD
66 #define wxUSE_BEGIN_THREAD
69 #ifdef wxUSE_BEGIN_THREAD
70 // this is where _beginthreadex() is declared
73 // the return type of the thread function entry point
74 typedef unsigned THREAD_RETVAL
;
76 // the calling convention of the thread function entry point
77 #define THREAD_CALLCONV __stdcall
79 // the settings for CreateThread()
80 typedef DWORD THREAD_RETVAL
;
81 #define THREAD_CALLCONV WINAPI
84 // ----------------------------------------------------------------------------
86 // ----------------------------------------------------------------------------
88 // the possible states of the thread ("=>" shows all possible transitions from
92 STATE_NEW
, // didn't start execution yet (=> RUNNING)
93 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
94 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
95 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
96 STATE_EXITED
// thread is terminating
99 // ----------------------------------------------------------------------------
100 // this module globals
101 // ----------------------------------------------------------------------------
103 // TLS index of the slot where we store the pointer to the current thread
104 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
106 // id of the main thread - the one which can call GUI functions without first
107 // calling wxMutexGuiEnter()
108 static DWORD gs_idMainThread
= 0;
110 // if it's FALSE, some secondary thread is holding the GUI lock
111 static bool gs_bGuiOwnedByMainThread
= TRUE
;
113 // critical section which controls access to all GUI functions: any secondary
114 // thread (i.e. except the main one) must enter this crit section before doing
116 static wxCriticalSection
*gs_critsectGui
= NULL
;
118 // critical section which protects gs_nWaitingForGui variable
119 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
121 // number of threads waiting for GUI in wxMutexGuiEnter()
122 static size_t gs_nWaitingForGui
= 0;
124 // are we waiting for a thread termination?
125 static bool gs_waitingForThread
= FALSE
;
127 // ============================================================================
128 // Windows implementation of thread and related classes
129 // ============================================================================
131 // ----------------------------------------------------------------------------
133 // ----------------------------------------------------------------------------
135 wxCriticalSection::wxCriticalSection()
137 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
138 wxCriticalSectionBufferTooSmall
);
140 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
143 wxCriticalSection::~wxCriticalSection()
145 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
148 void wxCriticalSection::Enter()
150 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
153 void wxCriticalSection::Leave()
155 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
158 // ----------------------------------------------------------------------------
160 // ----------------------------------------------------------------------------
162 class wxMutexInternal
165 wxMutexInternal(wxMutexType mutexType
);
168 bool IsOk() const { return m_mutex
!= NULL
; }
170 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
171 wxMutexError
TryLock() { return LockTimeout(0); }
172 wxMutexError
Unlock();
175 wxMutexError
LockTimeout(DWORD milliseconds
);
179 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
182 // all mutexes are recursive under Win32 so we don't use mutexType
183 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
185 // create a nameless (hence intra process and always private) mutex
186 m_mutex
= ::CreateMutex
188 NULL
, // default secutiry attributes
189 FALSE
, // not initially locked
195 wxLogLastError(_T("CreateMutex()"));
199 wxMutexInternal::~wxMutexInternal()
203 if ( !::CloseHandle(m_mutex
) )
205 wxLogLastError(_T("CloseHandle(mutex)"));
210 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
212 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
213 if ( rc
== WAIT_ABANDONED
)
215 // the previous caller died without releasing the mutex, but now we can
217 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
219 // use 0 timeout, normally we should always get it
220 rc
= ::WaitForSingleObject(m_mutex
, 0);
232 case WAIT_ABANDONED
: // checked for above
234 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
238 wxLogLastError(_T("WaitForSingleObject(mutex)"));
239 return wxMUTEX_MISC_ERROR
;
242 return wxMUTEX_NO_ERROR
;
245 wxMutexError
wxMutexInternal::Unlock()
247 if ( !::ReleaseMutex(m_mutex
) )
249 wxLogLastError(_T("ReleaseMutex()"));
251 return wxMUTEX_MISC_ERROR
;
254 return wxMUTEX_NO_ERROR
;
257 // --------------------------------------------------------------------------
259 // --------------------------------------------------------------------------
261 // a trivial wrapper around Win32 semaphore
262 class wxSemaphoreInternal
265 wxSemaphoreInternal(int initialcount
, int maxcount
);
266 ~wxSemaphoreInternal();
268 bool IsOk() const { return m_semaphore
!= NULL
; }
270 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
272 wxSemaError
TryWait()
274 wxSemaError rc
= WaitTimeout(0);
275 if ( rc
== wxSEMA_TIMEOUT
)
281 wxSemaError
WaitTimeout(unsigned long milliseconds
);
288 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
291 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
295 // make it practically infinite
299 m_semaphore
= ::CreateSemaphore
301 NULL
, // default security attributes
309 wxLogLastError(_T("CreateSemaphore()"));
313 wxSemaphoreInternal::~wxSemaphoreInternal()
317 if ( !::CloseHandle(m_semaphore
) )
319 wxLogLastError(_T("CloseHandle(semaphore)"));
324 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
326 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
331 return wxSEMA_NO_ERROR
;
334 return wxSEMA_TIMEOUT
;
337 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
340 return wxSEMA_MISC_ERROR
;
343 wxSemaError
wxSemaphoreInternal::Post()
345 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
347 wxLogLastError(_T("ReleaseSemaphore"));
349 return wxSEMA_MISC_ERROR
;
352 return wxSEMA_NO_ERROR
;
355 // --------------------------------------------------------------------------
357 // --------------------------------------------------------------------------
359 // Win32 doesn't have explicit support for the POSIX condition variables and
360 // the Win32 events have quite different semantics, so we reimplement the
361 // conditions from scratch using the mutexes and semaphores
362 class wxConditionInternal
365 wxConditionInternal(wxMutex
& mutex
);
367 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
370 wxCondError
WaitTimeout(unsigned long milliseconds
);
372 wxCondError
Signal();
373 wxCondError
Broadcast();
376 // the number of threads currently waiting for this condition
379 // the critical section protecting m_numWaiters
380 wxCriticalSection m_csWaiters
;
383 wxSemaphore m_semaphore
;
386 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
389 // another thread can't access it until we return from ctor, so no need to
390 // protect access to m_numWaiters here
394 wxCondError
wxConditionInternal::Wait()
396 // increment the number of waiters
397 ::InterlockedIncrement(&m_numWaiters
);
401 // a potential race condition can occur here
403 // after a thread increments nwaiters, and unlocks the mutex and before the
404 // semaphore.Wait() is called, if another thread can cause a signal to be
407 // this race condition is handled by using a semaphore and incrementing the
408 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
409 // can 'remember' signals the race condition will not occur
411 // wait ( if necessary ) and decrement semaphore
412 wxSemaError err
= m_semaphore
.Wait();
415 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
418 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
420 ::InterlockedIncrement(&m_numWaiters
);
424 // a race condition can occur at this point in the code
426 // please see the comments in Wait(), for details
428 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
430 if ( err
== wxSEMA_BUSY
)
432 // another potential race condition exists here it is caused when a
433 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
434 // has not yet decremented 'nwaiters'.
436 // at this point if another thread calls signal() then the semaphore
437 // will be incremented, but the waiting thread will miss it.
439 // to handle this particular case, the waiting thread calls
440 // WaitForSingleObject again with a timeout of 0, after locking
441 // 'nwaiters_mutex'. this call does not block because of the zero
442 // timeout, but will allow the waiting thread to catch the missed
444 wxCriticalSectionLocker
lock(m_csWaiters
);
446 err
= m_semaphore
.WaitTimeout(0);
448 if ( err
!= wxSEMA_NO_ERROR
)
456 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
459 wxCondError
wxConditionInternal::Signal()
461 wxCriticalSectionLocker
lock(m_csWaiters
);
463 if ( m_numWaiters
> 0 )
465 // increment the semaphore by 1
466 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
467 return wxCOND_MISC_ERROR
;
472 return wxCOND_NO_ERROR
;
475 wxCondError
wxConditionInternal::Broadcast()
477 wxCriticalSectionLocker
lock(m_csWaiters
);
479 while ( m_numWaiters
> 0 )
481 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
482 return wxCOND_MISC_ERROR
;
487 return wxCOND_NO_ERROR
;
490 // ----------------------------------------------------------------------------
491 // wxThread implementation
492 // ----------------------------------------------------------------------------
494 // wxThreadInternal class
495 // ----------------------
497 class wxThreadInternal
504 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
516 if ( !::CloseHandle(m_hThread
) )
518 wxLogLastError(wxT("CloseHandle(thread)"));
525 // create a new (suspended) thread (for the given thread object)
526 bool Create(wxThread
*thread
, unsigned int stackSize
);
528 // suspend/resume/terminate
531 void Cancel() { m_state
= STATE_CANCELED
; }
534 void SetState(wxThreadState state
) { m_state
= state
; }
535 wxThreadState
GetState() const { return m_state
; }
538 void SetPriority(unsigned int priority
);
539 unsigned int GetPriority() const { return m_priority
; }
541 // thread handle and id
542 HANDLE
GetHandle() const { return m_hThread
; }
543 DWORD
GetId() const { return m_tid
; }
546 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
549 HANDLE m_hThread
; // handle of the thread
550 wxThreadState m_state
; // state, see wxThreadState enum
551 unsigned int m_priority
; // thread priority in "wx" units
552 DWORD m_tid
; // thread id
554 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
557 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
562 // first of all, check whether we hadn't been cancelled already and don't
563 // start the user code at all then
564 wxThread
*thread
= (wxThread
*)param
;
565 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
567 rc
= (THREAD_RETVAL
)-1;
570 else // do run thread
572 // store the thread object in the TLS
573 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
575 wxLogSysError(_("Can not start thread: error writing TLS."));
580 rc
= (THREAD_RETVAL
)thread
->Entry();
582 // enter m_critsect before changing the thread state
583 thread
->m_critsect
.Enter();
584 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
585 thread
->m_internal
->SetState(STATE_EXITED
);
586 thread
->m_critsect
.Leave();
591 // if the thread was cancelled (from Delete()), then its handle is still
593 if ( thread
->IsDetached() && !wasCancelled
)
598 //else: the joinable threads handle will be closed when Wait() is done
603 void wxThreadInternal::SetPriority(unsigned int priority
)
605 m_priority
= priority
;
607 // translate wxWindows priority to the Windows one
609 if (m_priority
<= 20)
610 win_priority
= THREAD_PRIORITY_LOWEST
;
611 else if (m_priority
<= 40)
612 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
613 else if (m_priority
<= 60)
614 win_priority
= THREAD_PRIORITY_NORMAL
;
615 else if (m_priority
<= 80)
616 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
617 else if (m_priority
<= 100)
618 win_priority
= THREAD_PRIORITY_HIGHEST
;
621 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
622 win_priority
= THREAD_PRIORITY_NORMAL
;
625 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
627 wxLogSysError(_("Can't set thread priority"));
631 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
633 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
634 _T("Create()ing thread twice?") );
636 // for compilers which have it, we should use C RTL function for thread
637 // creation instead of Win32 API one because otherwise we will have memory
638 // leaks if the thread uses C RTL (and most threads do)
639 #ifdef wxUSE_BEGIN_THREAD
641 // Watcom is reported to not like 0 stack size (which means "use default"
642 // for the other compilers and is also the default value for stackSize)
646 #endif // __WATCOMC__
648 m_hThread
= (HANDLE
)_beginthreadex
650 NULL
, // default security
652 wxThreadInternal::WinThreadStart
, // entry point
655 (unsigned int *)&m_tid
657 #else // compiler doesn't have _beginthreadex
658 m_hThread
= ::CreateThread
660 NULL
, // default security
661 stackSize
, // stack size
662 wxThreadInternal::WinThreadStart
, // thread entry point
663 (LPVOID
)thread
, // parameter
664 CREATE_SUSPENDED
, // flags
665 &m_tid
// [out] thread id
667 #endif // _beginthreadex/CreateThread
669 if ( m_hThread
== NULL
)
671 wxLogSysError(_("Can't create thread"));
676 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
678 SetPriority(m_priority
);
684 bool wxThreadInternal::Suspend()
686 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
687 if ( nSuspendCount
== (DWORD
)-1 )
689 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
694 m_state
= STATE_PAUSED
;
699 bool wxThreadInternal::Resume()
701 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
702 if ( nSuspendCount
== (DWORD
)-1 )
704 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
709 // don't change the state from STATE_EXITED because it's special and means
710 // we are going to terminate without running any user code - if we did it,
711 // the codei n Delete() wouldn't work
712 if ( m_state
!= STATE_EXITED
)
714 m_state
= STATE_RUNNING
;
723 wxThread
*wxThread::This()
725 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
727 // be careful, 0 may be a valid return value as well
728 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
730 wxLogSysError(_("Couldn't get the current thread pointer"));
738 bool wxThread::IsMain()
740 return ::GetCurrentThreadId() == gs_idMainThread
;
747 void wxThread::Yield()
749 // 0 argument to Sleep() is special and means to just give away the rest of
754 void wxThread::Sleep(unsigned long milliseconds
)
756 ::Sleep(milliseconds
);
759 int wxThread::GetCPUCount()
764 return si
.dwNumberOfProcessors
;
767 unsigned long wxThread::GetCurrentId()
769 return (unsigned long)::GetCurrentThreadId();
772 bool wxThread::SetConcurrency(size_t level
)
774 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
776 // ok only for the default one
780 // get system affinity mask first
781 HANDLE hProcess
= ::GetCurrentProcess();
782 DWORD dwProcMask
, dwSysMask
;
783 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
785 wxLogLastError(_T("GetProcessAffinityMask"));
790 // how many CPUs have we got?
791 if ( dwSysMask
== 1 )
793 // don't bother with all this complicated stuff - on a single
794 // processor system it doesn't make much sense anyhow
798 // calculate the process mask: it's a bit vector with one bit per
799 // processor; we want to schedule the process to run on first level
804 if ( dwSysMask
& bit
)
806 // ok, we can set this bit
809 // another process added
821 // could we set all bits?
824 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
829 // set it: we can't link to SetProcessAffinityMask() because it doesn't
830 // exist in Win9x, use RT binding instead
832 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
834 // can use static var because we're always in the main thread here
835 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
837 if ( !pfnSetProcessAffinityMask
)
839 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
842 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
843 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
846 // we've discovered a MT version of Win9x!
847 wxASSERT_MSG( pfnSetProcessAffinityMask
,
848 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
851 if ( !pfnSetProcessAffinityMask
)
853 // msg given above - do it only once
857 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
859 wxLogLastError(_T("SetProcessAffinityMask"));
870 wxThread::wxThread(wxThreadKind kind
)
872 m_internal
= new wxThreadInternal();
874 m_isDetached
= kind
== wxTHREAD_DETACHED
;
877 wxThread::~wxThread()
882 // create/start thread
883 // -------------------
885 wxThreadError
wxThread::Create(unsigned int stackSize
)
887 wxCriticalSectionLocker
lock(m_critsect
);
889 if ( !m_internal
->Create(this, stackSize
) )
890 return wxTHREAD_NO_RESOURCE
;
892 return wxTHREAD_NO_ERROR
;
895 wxThreadError
wxThread::Run()
897 wxCriticalSectionLocker
lock(m_critsect
);
899 if ( m_internal
->GetState() != STATE_NEW
)
901 // actually, it may be almost any state at all, not only STATE_RUNNING
902 return wxTHREAD_RUNNING
;
905 // the thread has just been created and is still suspended - let it run
909 // suspend/resume thread
910 // ---------------------
912 wxThreadError
wxThread::Pause()
914 wxCriticalSectionLocker
lock(m_critsect
);
916 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
919 wxThreadError
wxThread::Resume()
921 wxCriticalSectionLocker
lock(m_critsect
);
923 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
929 wxThread::ExitCode
wxThread::Wait()
931 // although under Windows we can wait for any thread, it's an error to
932 // wait for a detached one in wxWin API
933 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
934 _T("can't wait for detached thread") );
936 ExitCode rc
= (ExitCode
)-1;
945 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
949 // Delete() is always safe to call, so consider all possible states
951 // we might need to resume the thread, but we might also not need to cancel
952 // it if it doesn't run yet
953 bool shouldResume
= FALSE
,
957 // check if the thread already started to run
959 wxCriticalSectionLocker
lock(m_critsect
);
961 if ( m_internal
->GetState() == STATE_NEW
)
963 // WinThreadStart() will see it and terminate immediately, no need
964 // to cancel the thread - but we still need to resume it to let it
966 m_internal
->SetState(STATE_EXITED
);
968 Resume(); // it knows about STATE_EXITED special case
970 shouldCancel
= FALSE
;
973 // shouldResume is correctly set to FALSE here
977 shouldResume
= IsPaused();
981 // resume the thread if it is paused
985 HANDLE hThread
= m_internal
->GetHandle();
987 // does is still run?
988 if ( isRunning
|| IsRunning() )
992 // set flag for wxIsWaitingForThread()
993 gs_waitingForThread
= TRUE
;
996 // ask the thread to terminate
999 wxCriticalSectionLocker
lock(m_critsect
);
1001 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 // (note that even in console applications we might have to process
1008 // messages if we use wxExecute() or timers or ...)
1009 DWORD result
= 0; // suppress warnings from broken compilers
1014 // give the thread we're waiting for chance to do the GUI call
1016 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1022 result
= ::MsgWaitForMultipleObjects
1024 1, // number of objects to wait for
1025 &hThread
, // the objects
1026 FALSE
, // don't wait for all objects
1027 INFINITE
, // no timeout
1028 QS_ALLINPUT
| // return as soon as there are any events
1036 wxLogSysError(_("Can not wait for thread termination"));
1038 return wxTHREAD_KILLED
;
1041 // thread we're waiting for terminated
1044 case WAIT_OBJECT_0
+ 1:
1045 // new message arrived, process it
1047 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
1050 if ( traits
&& !traits
->DoMessageFromThreadWait() )
1052 // WM_QUIT received: kill the thread
1055 return wxTHREAD_KILLED
;
1061 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1063 } while ( result
!= WAIT_OBJECT_0
);
1067 gs_waitingForThread
= FALSE
;
1071 // although the thread might be already in the EXITED state it might not
1072 // have terminated yet and so we are not sure that it has actually
1073 // terminated if the "if" above hadn't been taken
1076 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1078 wxLogLastError(wxT("GetExitCodeThread"));
1082 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1086 // if the thread exits normally, this is done in WinThreadStart, but in
1087 // this case it would have been too early because
1088 // MsgWaitForMultipleObject() would fail if the thread handle was
1089 // closed while we were waiting on it, so we must do it here
1096 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1099 wxThreadError
wxThread::Kill()
1102 return wxTHREAD_NOT_RUNNING
;
1104 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1106 wxLogSysError(_("Couldn't terminate thread"));
1108 return wxTHREAD_MISC_ERROR
;
1118 return wxTHREAD_NO_ERROR
;
1121 void wxThread::Exit(ExitCode status
)
1130 #ifdef wxUSE_BEGIN_THREAD
1131 _endthreadex((unsigned)status
);
1133 ::ExitThread((DWORD
)status
);
1134 #endif // VC++/!VC++
1136 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1142 void wxThread::SetPriority(unsigned int prio
)
1144 wxCriticalSectionLocker
lock(m_critsect
);
1146 m_internal
->SetPriority(prio
);
1149 unsigned int wxThread::GetPriority() const
1151 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1153 return m_internal
->GetPriority();
1156 unsigned long wxThread::GetId() const
1158 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1160 return (unsigned long)m_internal
->GetId();
1163 bool wxThread::IsRunning() const
1165 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1167 return m_internal
->GetState() == STATE_RUNNING
;
1170 bool wxThread::IsAlive() const
1172 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1174 return (m_internal
->GetState() == STATE_RUNNING
) ||
1175 (m_internal
->GetState() == STATE_PAUSED
);
1178 bool wxThread::IsPaused() const
1180 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1182 return m_internal
->GetState() == STATE_PAUSED
;
1185 bool wxThread::TestDestroy()
1187 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1189 return m_internal
->GetState() == STATE_CANCELED
;
1192 // ----------------------------------------------------------------------------
1193 // Automatic initialization for thread module
1194 // ----------------------------------------------------------------------------
1196 class wxThreadModule
: public wxModule
1199 virtual bool OnInit();
1200 virtual void OnExit();
1203 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1206 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1208 bool wxThreadModule::OnInit()
1210 // allocate TLS index for storing the pointer to the current thread
1211 gs_tlsThisThread
= ::TlsAlloc();
1212 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1214 // in normal circumstances it will only happen if all other
1215 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1216 // words, this should never happen
1217 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1222 // main thread doesn't have associated wxThread object, so store 0 in the
1224 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1226 ::TlsFree(gs_tlsThisThread
);
1227 gs_tlsThisThread
= 0xFFFFFFFF;
1229 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1234 gs_critsectWaitingForGui
= new wxCriticalSection();
1236 gs_critsectGui
= new wxCriticalSection();
1237 gs_critsectGui
->Enter();
1239 // no error return for GetCurrentThreadId()
1240 gs_idMainThread
= ::GetCurrentThreadId();
1245 void wxThreadModule::OnExit()
1247 if ( !::TlsFree(gs_tlsThisThread
) )
1249 wxLogLastError(wxT("TlsFree failed."));
1252 if ( gs_critsectGui
)
1254 gs_critsectGui
->Leave();
1255 delete gs_critsectGui
;
1256 gs_critsectGui
= NULL
;
1259 delete gs_critsectWaitingForGui
;
1260 gs_critsectWaitingForGui
= NULL
;
1263 // ----------------------------------------------------------------------------
1264 // under Windows, these functions are implemented using a critical section and
1265 // not a mutex, so the names are a bit confusing
1266 // ----------------------------------------------------------------------------
1268 void WXDLLEXPORT
wxMutexGuiEnter()
1270 // this would dead lock everything...
1271 wxASSERT_MSG( !wxThread::IsMain(),
1272 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1274 // the order in which we enter the critical sections here is crucial!!
1276 // set the flag telling to the main thread that we want to do some GUI
1278 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1280 gs_nWaitingForGui
++;
1283 wxWakeUpMainThread();
1285 // now we may block here because the main thread will soon let us in
1286 // (during the next iteration of OnIdle())
1287 gs_critsectGui
->Enter();
1290 void WXDLLEXPORT
wxMutexGuiLeave()
1292 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1294 if ( wxThread::IsMain() )
1296 gs_bGuiOwnedByMainThread
= FALSE
;
1300 // decrement the number of threads waiting for GUI access now
1301 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1302 wxT("calling wxMutexGuiLeave() without entering it first?") );
1304 gs_nWaitingForGui
--;
1306 wxWakeUpMainThread();
1309 gs_critsectGui
->Leave();
1312 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1314 wxASSERT_MSG( wxThread::IsMain(),
1315 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1317 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1319 if ( gs_nWaitingForGui
== 0 )
1321 // no threads are waiting for GUI - so we may acquire the lock without
1322 // any danger (but only if we don't already have it)
1323 if ( !wxGuiOwnedByMainThread() )
1325 gs_critsectGui
->Enter();
1327 gs_bGuiOwnedByMainThread
= TRUE
;
1329 //else: already have it, nothing to do
1333 // some threads are waiting, release the GUI lock if we have it
1334 if ( wxGuiOwnedByMainThread() )
1338 //else: some other worker thread is doing GUI
1342 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1344 return gs_bGuiOwnedByMainThread
;
1347 // wake up the main thread if it's in ::GetMessage()
1348 void WXDLLEXPORT
wxWakeUpMainThread()
1350 // sending any message would do - hopefully WM_NULL is harmless enough
1351 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1353 // should never happen
1354 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1358 bool WXDLLEXPORT
wxIsWaitingForThread()
1360 return gs_waitingForThread
;
1363 // ----------------------------------------------------------------------------
1364 // include common implementation code
1365 // ----------------------------------------------------------------------------
1367 #include "wx/thrimpl.cpp"
1369 #endif // wxUSE_THREADS