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 // ----------------------------------------------------------------------------
84 // ----------------------------------------------------------------------------
86 // the possible states of the thread ("=>" shows all possible transitions from
90 STATE_NEW
, // didn't start execution yet (=> RUNNING)
91 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
92 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
93 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
94 STATE_EXITED
// thread is terminating
97 // ----------------------------------------------------------------------------
98 // this module globals
99 // ----------------------------------------------------------------------------
101 // TLS index of the slot where we store the pointer to the current thread
102 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
104 // id of the main thread - the one which can call GUI functions without first
105 // calling wxMutexGuiEnter()
106 static DWORD gs_idMainThread
= 0;
108 // if it's FALSE, some secondary thread is holding the GUI lock
109 static bool gs_bGuiOwnedByMainThread
= TRUE
;
111 // critical section which controls access to all GUI functions: any secondary
112 // thread (i.e. except the main one) must enter this crit section before doing
114 static wxCriticalSection
*gs_critsectGui
= NULL
;
116 // critical section which protects gs_nWaitingForGui variable
117 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
119 // number of threads waiting for GUI in wxMutexGuiEnter()
120 static size_t gs_nWaitingForGui
= 0;
122 // are we waiting for a thread termination?
123 static bool gs_waitingForThread
= FALSE
;
125 // ============================================================================
126 // Windows implementation of thread and related classes
127 // ============================================================================
129 // ----------------------------------------------------------------------------
131 // ----------------------------------------------------------------------------
133 wxCriticalSection::wxCriticalSection()
135 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(m_buffer
),
136 wxCriticalSectionBufferTooSmall
);
138 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
141 wxCriticalSection::~wxCriticalSection()
143 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
146 void wxCriticalSection::Enter()
148 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
151 void wxCriticalSection::Leave()
153 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
156 // ----------------------------------------------------------------------------
158 // ----------------------------------------------------------------------------
160 class wxMutexInternal
163 wxMutexInternal(wxMutexType mutexType
);
166 bool IsOk() const { return m_mutex
!= NULL
; }
168 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
169 wxMutexError
TryLock() { return LockTimeout(0); }
170 wxMutexError
Unlock();
173 wxMutexError
LockTimeout(DWORD milliseconds
);
178 // all mutexes are recursive under Win32 so we don't use mutexType
179 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
181 // create a nameless (hence intra process and always private) mutex
182 m_mutex
= ::CreateMutex
184 NULL
, // default secutiry attributes
185 FALSE
, // not initially locked
191 wxLogLastError(_T("CreateMutex()"));
195 wxMutexInternal::~wxMutexInternal()
199 if ( !::CloseHandle(m_mutex
) )
201 wxLogLastError(_T("CloseHandle(mutex)"));
206 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
208 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
209 if ( rc
== WAIT_ABANDONED
)
211 // the previous caller died without releasing the mutex, but now we can
213 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
215 // use 0 timeout, normally we should always get it
216 rc
= ::WaitForSingleObject(m_mutex
, 0);
228 case WAIT_ABANDONED
: // checked for above
230 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
234 wxLogLastError(_T("WaitForSingleObject(mutex)"));
235 return wxMUTEX_MISC_ERROR
;
238 return wxMUTEX_NO_ERROR
;
241 wxMutexError
wxMutexInternal::Unlock()
243 if ( !::ReleaseMutex(m_mutex
) )
245 wxLogLastError(_("ReleaseMutex()"));
247 return wxMUTEX_MISC_ERROR
;
250 return wxMUTEX_NO_ERROR
;
253 // --------------------------------------------------------------------------
255 // --------------------------------------------------------------------------
257 // a trivial wrapper around Win32 semaphore
258 class wxSemaphoreInternal
261 wxSemaphoreInternal(int initialcount
, int maxcount
);
262 ~wxSemaphoreInternal();
264 bool IsOk() const { return m_semaphore
!= NULL
; }
266 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
267 wxSemaError
TryWait() { return WaitTimeout(0); }
268 wxSemaError
WaitTimeout(unsigned long milliseconds
);
276 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
280 // make it practically infinite
284 m_semaphore
= ::CreateSemaphore
286 NULL
, // default security attributes
294 wxLogLastError(_T("CreateSemaphore()"));
298 wxSemaphoreInternal::~wxSemaphoreInternal()
302 if ( !::CloseHandle(m_semaphore
) )
304 wxLogLastError(_T("CloseHandle(semaphore)"));
309 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
311 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
316 return wxSEMA_NO_ERROR
;
322 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
325 return wxSEMA_MISC_ERROR
;
328 wxSemaError
wxSemaphoreInternal::Post()
330 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
332 wxLogLastError(_T("ReleaseSemaphore"));
334 return wxSEMA_MISC_ERROR
;
337 return wxSEMA_NO_ERROR
;
340 // --------------------------------------------------------------------------
342 // --------------------------------------------------------------------------
344 // Win32 doesn't have explicit support for the POSIX condition variables and
345 // the Win32 events have quite different semantics, so we reimplement the
346 // conditions from scratch using the mutexes and semaphores
347 class wxConditionInternal
350 wxConditionInternal(wxMutex
& mutex
);
352 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
355 wxCondError
WaitTimeout(unsigned long milliseconds
);
357 wxCondError
Signal();
358 wxCondError
Broadcast();
361 // the number of threads currently waiting for this condition
364 // the critical section protecting m_numWaiters
365 wxCriticalSection m_csWaiters
;
368 wxSemaphore m_semaphore
;
371 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
374 // another thread can't access it until we return from ctor, so no need to
375 // protect access to m_numWaiters here
379 wxCondError
wxConditionInternal::Wait()
381 // increment the number of waiters
382 ::InterlockedIncrement(&m_numWaiters
);
386 // a potential race condition can occur here
388 // after a thread increments nwaiters, and unlocks the mutex and before the
389 // semaphore.Wait() is called, if another thread can cause a signal to be
392 // this race condition is handled by using a semaphore and incrementing the
393 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
394 // can 'remember' signals the race condition will not occur
396 // wait ( if necessary ) and decrement semaphore
397 wxSemaError err
= m_semaphore
.Wait();
400 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
403 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
405 ::InterlockedIncrement(&m_numWaiters
);
409 // a race condition can occur at this point in the code
411 // please see the comments in Wait(), for details
413 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
415 if ( err
== wxSEMA_BUSY
)
417 // another potential race condition exists here it is caused when a
418 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
419 // has not yet decremented 'nwaiters'.
421 // at this point if another thread calls signal() then the semaphore
422 // will be incremented, but the waiting thread will miss it.
424 // to handle this particular case, the waiting thread calls
425 // WaitForSingleObject again with a timeout of 0, after locking
426 // 'nwaiters_mutex'. this call does not block because of the zero
427 // timeout, but will allow the waiting thread to catch the missed
429 wxCriticalSectionLocker
lock(m_csWaiters
);
431 err
= m_semaphore
.WaitTimeout(0);
433 if ( err
!= wxSEMA_NO_ERROR
)
441 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
444 wxCondError
wxConditionInternal::Signal()
446 wxCriticalSectionLocker
lock(m_csWaiters
);
448 if ( m_numWaiters
> 0 )
450 // increment the semaphore by 1
451 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
452 return wxCOND_MISC_ERROR
;
457 return wxCOND_NO_ERROR
;
460 wxCondError
wxConditionInternal::Broadcast()
462 wxCriticalSectionLocker
lock(m_csWaiters
);
464 while ( m_numWaiters
> 0 )
466 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
467 return wxCOND_MISC_ERROR
;
472 return wxCOND_NO_ERROR
;
475 // ----------------------------------------------------------------------------
476 // wxThread implementation
477 // ----------------------------------------------------------------------------
479 // wxThreadInternal class
480 // ----------------------
482 class wxThreadInternal
489 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
501 if ( !::CloseHandle(m_hThread
) )
503 wxLogLastError(wxT("CloseHandle(thread)"));
510 // create a new (suspended) thread (for the given thread object)
511 bool Create(wxThread
*thread
, unsigned int stackSize
);
513 // suspend/resume/terminate
516 void Cancel() { m_state
= STATE_CANCELED
; }
519 void SetState(wxThreadState state
) { m_state
= state
; }
520 wxThreadState
GetState() const { return m_state
; }
523 void SetPriority(unsigned int priority
);
524 unsigned int GetPriority() const { return m_priority
; }
526 // thread handle and id
527 HANDLE
GetHandle() const { return m_hThread
; }
528 DWORD
GetId() const { return m_tid
; }
531 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
534 HANDLE m_hThread
; // handle of the thread
535 wxThreadState m_state
; // state, see wxThreadState enum
536 unsigned int m_priority
; // thread priority in "wx" units
537 DWORD m_tid
; // thread id
540 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
545 // first of all, check whether we hadn't been cancelled already and don't
546 // start the user code at all then
547 wxThread
*thread
= (wxThread
*)param
;
548 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
550 rc
= (THREAD_RETVAL
)-1;
553 else // do run thread
555 // store the thread object in the TLS
556 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
558 wxLogSysError(_("Can not start thread: error writing TLS."));
563 rc
= (THREAD_RETVAL
)thread
->Entry();
565 // enter m_critsect before changing the thread state
566 thread
->m_critsect
.Enter();
567 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
568 thread
->m_internal
->SetState(STATE_EXITED
);
569 thread
->m_critsect
.Leave();
574 // if the thread was cancelled (from Delete()), then its handle is still
576 if ( thread
->IsDetached() && !wasCancelled
)
581 //else: the joinable threads handle will be closed when Wait() is done
586 void wxThreadInternal::SetPriority(unsigned int priority
)
588 m_priority
= priority
;
590 // translate wxWindows priority to the Windows one
592 if (m_priority
<= 20)
593 win_priority
= THREAD_PRIORITY_LOWEST
;
594 else if (m_priority
<= 40)
595 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
596 else if (m_priority
<= 60)
597 win_priority
= THREAD_PRIORITY_NORMAL
;
598 else if (m_priority
<= 80)
599 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
600 else if (m_priority
<= 100)
601 win_priority
= THREAD_PRIORITY_HIGHEST
;
604 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
605 win_priority
= THREAD_PRIORITY_NORMAL
;
608 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
610 wxLogSysError(_("Can't set thread priority"));
614 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
616 // for compilers which have it, we should use C RTL function for thread
617 // creation instead of Win32 API one because otherwise we will have memory
618 // leaks if the thread uses C RTL (and most threads do)
619 #ifdef wxUSE_BEGIN_THREAD
621 // Watcom is reported to not like 0 stack size (which means "use default"
622 // for the other compilers and is also the default value for stackSize)
626 #endif // __WATCOMC__
628 m_hThread
= (HANDLE
)_beginthreadex
630 NULL
, // default security
632 wxThreadInternal::WinThreadStart
, // entry point
635 (unsigned int *)&m_tid
637 #else // compiler doesn't have _beginthreadex
638 m_hThread
= ::CreateThread
640 NULL
, // default security
641 stackSize
, // stack size
642 wxThreadInternal::WinThreadStart
, // thread entry point
643 (LPVOID
)thread
, // parameter
644 CREATE_SUSPENDED
, // flags
645 &m_tid
// [out] thread id
647 #endif // _beginthreadex/CreateThread
649 if ( m_hThread
== NULL
)
651 wxLogSysError(_("Can't create thread"));
656 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
658 SetPriority(m_priority
);
664 bool wxThreadInternal::Suspend()
666 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
667 if ( nSuspendCount
== (DWORD
)-1 )
669 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
674 m_state
= STATE_PAUSED
;
679 bool wxThreadInternal::Resume()
681 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
682 if ( nSuspendCount
== (DWORD
)-1 )
684 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
689 // don't change the state from STATE_EXITED because it's special and means
690 // we are going to terminate without running any user code - if we did it,
691 // the codei n Delete() wouldn't work
692 if ( m_state
!= STATE_EXITED
)
694 m_state
= STATE_RUNNING
;
703 wxThread
*wxThread::This()
705 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
707 // be careful, 0 may be a valid return value as well
708 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
710 wxLogSysError(_("Couldn't get the current thread pointer"));
718 bool wxThread::IsMain()
720 return ::GetCurrentThreadId() == gs_idMainThread
;
727 void wxThread::Yield()
729 // 0 argument to Sleep() is special and means to just give away the rest of
734 void wxThread::Sleep(unsigned long milliseconds
)
736 ::Sleep(milliseconds
);
739 int wxThread::GetCPUCount()
744 return si
.dwNumberOfProcessors
;
747 unsigned long wxThread::GetCurrentId()
749 return (unsigned long)::GetCurrentThreadId();
752 bool wxThread::SetConcurrency(size_t level
)
754 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
756 // ok only for the default one
760 // get system affinity mask first
761 HANDLE hProcess
= ::GetCurrentProcess();
762 DWORD dwProcMask
, dwSysMask
;
763 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
765 wxLogLastError(_T("GetProcessAffinityMask"));
770 // how many CPUs have we got?
771 if ( dwSysMask
== 1 )
773 // don't bother with all this complicated stuff - on a single
774 // processor system it doesn't make much sense anyhow
778 // calculate the process mask: it's a bit vector with one bit per
779 // processor; we want to schedule the process to run on first level
784 if ( dwSysMask
& bit
)
786 // ok, we can set this bit
789 // another process added
801 // could we set all bits?
804 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
809 // set it: we can't link to SetProcessAffinityMask() because it doesn't
810 // exist in Win9x, use RT binding instead
812 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
814 // can use static var because we're always in the main thread here
815 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
817 if ( !pfnSetProcessAffinityMask
)
819 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
822 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
823 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
826 // we've discovered a MT version of Win9x!
827 wxASSERT_MSG( pfnSetProcessAffinityMask
,
828 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
831 if ( !pfnSetProcessAffinityMask
)
833 // msg given above - do it only once
837 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
839 wxLogLastError(_T("SetProcessAffinityMask"));
850 wxThread::wxThread(wxThreadKind kind
)
852 m_internal
= new wxThreadInternal();
854 m_isDetached
= kind
== wxTHREAD_DETACHED
;
857 wxThread::~wxThread()
862 // create/start thread
863 // -------------------
865 wxThreadError
wxThread::Create(unsigned int stackSize
)
867 wxCriticalSectionLocker
lock(m_critsect
);
869 if ( !m_internal
->Create(this, stackSize
) )
870 return wxTHREAD_NO_RESOURCE
;
872 return wxTHREAD_NO_ERROR
;
875 wxThreadError
wxThread::Run()
877 wxCriticalSectionLocker
lock(m_critsect
);
879 if ( m_internal
->GetState() != STATE_NEW
)
881 // actually, it may be almost any state at all, not only STATE_RUNNING
882 return wxTHREAD_RUNNING
;
885 // the thread has just been created and is still suspended - let it run
889 // suspend/resume thread
890 // ---------------------
892 wxThreadError
wxThread::Pause()
894 wxCriticalSectionLocker
lock(m_critsect
);
896 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
899 wxThreadError
wxThread::Resume()
901 wxCriticalSectionLocker
lock(m_critsect
);
903 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
909 wxThread::ExitCode
wxThread::Wait()
911 // although under Windows we can wait for any thread, it's an error to
912 // wait for a detached one in wxWin API
913 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
914 _T("can't wait for detached thread") );
916 ExitCode rc
= (ExitCode
)-1;
925 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
929 // Delete() is always safe to call, so consider all possible states
931 // we might need to resume the thread, but we might also not need to cancel
932 // it if it doesn't run yet
933 bool shouldResume
= FALSE
,
937 // check if the thread already started to run
939 wxCriticalSectionLocker
lock(m_critsect
);
941 if ( m_internal
->GetState() == STATE_NEW
)
943 // WinThreadStart() will see it and terminate immediately, no need
944 // to cancel the thread - but we still need to resume it to let it
946 m_internal
->SetState(STATE_EXITED
);
948 Resume(); // it knows about STATE_EXITED special case
950 shouldCancel
= FALSE
;
953 // shouldResume is correctly set to FALSE here
957 shouldResume
= IsPaused();
961 // resume the thread if it is paused
965 HANDLE hThread
= m_internal
->GetHandle();
967 // does is still run?
968 if ( isRunning
|| IsRunning() )
972 // set flag for wxIsWaitingForThread()
973 gs_waitingForThread
= TRUE
;
980 // ask the thread to terminate
983 wxCriticalSectionLocker
lock(m_critsect
);
985 m_internal
->Cancel();
989 // we can't just wait for the thread to terminate because it might be
990 // calling some GUI functions and so it will never terminate before we
991 // process the Windows messages that result from these functions
995 result
= ::MsgWaitForMultipleObjects
997 1, // number of objects to wait for
998 &hThread
, // the objects
999 FALSE
, // don't wait for all objects
1000 INFINITE
, // no timeout
1001 QS_ALLEVENTS
// return as soon as there are any events
1008 wxLogSysError(_("Can not wait for thread termination"));
1010 return wxTHREAD_KILLED
;
1013 // thread we're waiting for terminated
1016 case WAIT_OBJECT_0
+ 1:
1017 // new message arrived, process it
1018 if ( !wxTheApp
->DoMessage() )
1020 // WM_QUIT received: kill the thread
1023 return wxTHREAD_KILLED
;
1028 // give the thread we're waiting for chance to exit
1029 // from the GUI call it might have been in
1030 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1039 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1041 } while ( result
!= WAIT_OBJECT_0
);
1043 // simply wait for the thread to terminate
1045 // OTOH, even console apps create windows (in wxExecute, for WinSock
1046 // &c), so may be use MsgWaitForMultipleObject() too here?
1047 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1049 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1051 #endif // wxUSE_GUI/!wxUSE_GUI
1055 gs_waitingForThread
= FALSE
;
1063 // although the thread might be already in the EXITED state it might not
1064 // have terminated yet and so we are not sure that it has actually
1065 // terminated if the "if" above hadn't been taken
1068 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1070 wxLogLastError(wxT("GetExitCodeThread"));
1074 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1078 // if the thread exits normally, this is done in WinThreadStart, but in
1079 // this case it would have been too early because
1080 // MsgWaitForMultipleObject() would fail if the thread handle was
1081 // closed while we were waiting on it, so we must do it here
1088 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1091 wxThreadError
wxThread::Kill()
1094 return wxTHREAD_NOT_RUNNING
;
1096 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1098 wxLogSysError(_("Couldn't terminate thread"));
1100 return wxTHREAD_MISC_ERROR
;
1110 return wxTHREAD_NO_ERROR
;
1113 void wxThread::Exit(ExitCode status
)
1122 #ifdef wxUSE_BEGIN_THREAD
1123 _endthreadex((unsigned)status
);
1125 ::ExitThread((DWORD
)status
);
1126 #endif // VC++/!VC++
1128 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1134 void wxThread::SetPriority(unsigned int prio
)
1136 wxCriticalSectionLocker
lock(m_critsect
);
1138 m_internal
->SetPriority(prio
);
1141 unsigned int wxThread::GetPriority() const
1143 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1145 return m_internal
->GetPriority();
1148 unsigned long wxThread::GetId() const
1150 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1152 return (unsigned long)m_internal
->GetId();
1155 bool wxThread::IsRunning() const
1157 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1159 return m_internal
->GetState() == STATE_RUNNING
;
1162 bool wxThread::IsAlive() const
1164 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1166 return (m_internal
->GetState() == STATE_RUNNING
) ||
1167 (m_internal
->GetState() == STATE_PAUSED
);
1170 bool wxThread::IsPaused() const
1172 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1174 return m_internal
->GetState() == STATE_PAUSED
;
1177 bool wxThread::TestDestroy()
1179 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1181 return m_internal
->GetState() == STATE_CANCELED
;
1184 // ----------------------------------------------------------------------------
1185 // Automatic initialization for thread module
1186 // ----------------------------------------------------------------------------
1188 class wxThreadModule
: public wxModule
1191 virtual bool OnInit();
1192 virtual void OnExit();
1195 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1198 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1200 bool wxThreadModule::OnInit()
1202 // allocate TLS index for storing the pointer to the current thread
1203 gs_tlsThisThread
= ::TlsAlloc();
1204 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1206 // in normal circumstances it will only happen if all other
1207 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1208 // words, this should never happen
1209 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1214 // main thread doesn't have associated wxThread object, so store 0 in the
1216 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1218 ::TlsFree(gs_tlsThisThread
);
1219 gs_tlsThisThread
= 0xFFFFFFFF;
1221 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1226 gs_critsectWaitingForGui
= new wxCriticalSection();
1228 gs_critsectGui
= new wxCriticalSection();
1229 gs_critsectGui
->Enter();
1231 // no error return for GetCurrentThreadId()
1232 gs_idMainThread
= ::GetCurrentThreadId();
1237 void wxThreadModule::OnExit()
1239 if ( !::TlsFree(gs_tlsThisThread
) )
1241 wxLogLastError(wxT("TlsFree failed."));
1244 if ( gs_critsectGui
)
1246 gs_critsectGui
->Leave();
1247 delete gs_critsectGui
;
1248 gs_critsectGui
= NULL
;
1251 delete gs_critsectWaitingForGui
;
1252 gs_critsectWaitingForGui
= NULL
;
1255 // ----------------------------------------------------------------------------
1256 // under Windows, these functions are implemented using a critical section and
1257 // not a mutex, so the names are a bit confusing
1258 // ----------------------------------------------------------------------------
1260 void WXDLLEXPORT
wxMutexGuiEnter()
1262 // this would dead lock everything...
1263 wxASSERT_MSG( !wxThread::IsMain(),
1264 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1266 // the order in which we enter the critical sections here is crucial!!
1268 // set the flag telling to the main thread that we want to do some GUI
1270 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1272 gs_nWaitingForGui
++;
1275 wxWakeUpMainThread();
1277 // now we may block here because the main thread will soon let us in
1278 // (during the next iteration of OnIdle())
1279 gs_critsectGui
->Enter();
1282 void WXDLLEXPORT
wxMutexGuiLeave()
1284 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1286 if ( wxThread::IsMain() )
1288 gs_bGuiOwnedByMainThread
= FALSE
;
1292 // decrement the number of threads waiting for GUI access now
1293 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1294 wxT("calling wxMutexGuiLeave() without entering it first?") );
1296 gs_nWaitingForGui
--;
1298 wxWakeUpMainThread();
1301 gs_critsectGui
->Leave();
1304 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1306 wxASSERT_MSG( wxThread::IsMain(),
1307 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1309 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1311 if ( gs_nWaitingForGui
== 0 )
1313 // no threads are waiting for GUI - so we may acquire the lock without
1314 // any danger (but only if we don't already have it)
1315 if ( !wxGuiOwnedByMainThread() )
1317 gs_critsectGui
->Enter();
1319 gs_bGuiOwnedByMainThread
= TRUE
;
1321 //else: already have it, nothing to do
1325 // some threads are waiting, release the GUI lock if we have it
1326 if ( wxGuiOwnedByMainThread() )
1330 //else: some other worker thread is doing GUI
1334 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1336 return gs_bGuiOwnedByMainThread
;
1339 // wake up the main thread if it's in ::GetMessage()
1340 void WXDLLEXPORT
wxWakeUpMainThread()
1342 // sending any message would do - hopefully WM_NULL is harmless enough
1343 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1345 // should never happen
1346 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1350 bool WXDLLEXPORT
wxIsWaitingForThread()
1352 return gs_waitingForThread
;
1355 // ----------------------------------------------------------------------------
1356 // include common implementation code
1357 // ----------------------------------------------------------------------------
1359 #include "wx/thrimpl.cpp"
1361 #endif // wxUSE_THREADS