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__)
35 #include "wx/apptrait.h"
37 #include "wx/msw/private.h"
38 #include "wx/msw/missing.h"
40 #include "wx/module.h"
41 #include "wx/thread.h"
43 // must have this symbol defined to get _beginthread/_endthread declarations
48 #if defined(__BORLANDC__)
50 // I can't set -tWM in the IDE (anyone?) so have to do this
54 #if !defined(__MFC_COMPAT__)
55 // Needed to know about _beginthreadex etc..
56 #define __MFC_COMPAT__
60 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
61 // which should be used instead of Win32 ::CreateThread() if possible
62 #if defined(__VISUALC__) || \
63 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
64 (defined(__GNUG__) && defined(__MSVCRT__)) || \
65 defined(__WATCOMC__) || defined(__MWERKS__)
67 #undef wxUSE_BEGIN_THREAD
68 #define wxUSE_BEGIN_THREAD
71 #ifdef wxUSE_BEGIN_THREAD
72 // this is where _beginthreadex() is declared
75 // the return type of the thread function entry point
76 typedef unsigned THREAD_RETVAL
;
78 // the calling convention of the thread function entry point
79 #define THREAD_CALLCONV __stdcall
81 // the settings for CreateThread()
82 typedef DWORD THREAD_RETVAL
;
83 #define THREAD_CALLCONV WINAPI
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
90 // the possible states of the thread ("=>" shows all possible transitions from
94 STATE_NEW
, // didn't start execution yet (=> RUNNING)
95 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
96 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
97 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
98 STATE_EXITED
// thread is terminating
101 // ----------------------------------------------------------------------------
102 // this module globals
103 // ----------------------------------------------------------------------------
105 // TLS index of the slot where we store the pointer to the current thread
106 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
108 // id of the main thread - the one which can call GUI functions without first
109 // calling wxMutexGuiEnter()
110 static DWORD gs_idMainThread
= 0;
112 // if it's FALSE, some secondary thread is holding the GUI lock
113 static bool gs_bGuiOwnedByMainThread
= TRUE
;
115 // critical section which controls access to all GUI functions: any secondary
116 // thread (i.e. except the main one) must enter this crit section before doing
118 static wxCriticalSection
*gs_critsectGui
= NULL
;
120 // critical section which protects gs_nWaitingForGui variable
121 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
123 // number of threads waiting for GUI in wxMutexGuiEnter()
124 static size_t gs_nWaitingForGui
= 0;
126 // are we waiting for a thread termination?
127 static bool gs_waitingForThread
= FALSE
;
129 // ============================================================================
130 // Windows implementation of thread and related classes
131 // ============================================================================
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 wxCriticalSection::wxCriticalSection()
139 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
140 wxCriticalSectionBufferTooSmall
);
142 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
145 wxCriticalSection::~wxCriticalSection()
147 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
150 void wxCriticalSection::Enter()
152 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
155 void wxCriticalSection::Leave()
157 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
160 // ----------------------------------------------------------------------------
162 // ----------------------------------------------------------------------------
164 class wxMutexInternal
167 wxMutexInternal(wxMutexType mutexType
);
170 bool IsOk() const { return m_mutex
!= NULL
; }
172 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
173 wxMutexError
TryLock() { return LockTimeout(0); }
174 wxMutexError
Unlock();
177 wxMutexError
LockTimeout(DWORD milliseconds
);
181 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
184 // all mutexes are recursive under Win32 so we don't use mutexType
185 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
187 // create a nameless (hence intra process and always private) mutex
188 m_mutex
= ::CreateMutex
190 NULL
, // default secutiry attributes
191 FALSE
, // not initially locked
197 wxLogLastError(_T("CreateMutex()"));
201 wxMutexInternal::~wxMutexInternal()
205 if ( !::CloseHandle(m_mutex
) )
207 wxLogLastError(_T("CloseHandle(mutex)"));
212 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
214 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
215 if ( rc
== WAIT_ABANDONED
)
217 // the previous caller died without releasing the mutex, but now we can
219 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
221 // use 0 timeout, normally we should always get it
222 rc
= ::WaitForSingleObject(m_mutex
, 0);
234 case WAIT_ABANDONED
: // checked for above
236 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
240 wxLogLastError(_T("WaitForSingleObject(mutex)"));
241 return wxMUTEX_MISC_ERROR
;
244 return wxMUTEX_NO_ERROR
;
247 wxMutexError
wxMutexInternal::Unlock()
249 if ( !::ReleaseMutex(m_mutex
) )
251 wxLogLastError(_T("ReleaseMutex()"));
253 return wxMUTEX_MISC_ERROR
;
256 return wxMUTEX_NO_ERROR
;
259 // --------------------------------------------------------------------------
261 // --------------------------------------------------------------------------
263 // a trivial wrapper around Win32 semaphore
264 class wxSemaphoreInternal
267 wxSemaphoreInternal(int initialcount
, int maxcount
);
268 ~wxSemaphoreInternal();
270 bool IsOk() const { return m_semaphore
!= NULL
; }
272 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
274 wxSemaError
TryWait()
276 wxSemaError rc
= WaitTimeout(0);
277 if ( rc
== wxSEMA_TIMEOUT
)
283 wxSemaError
WaitTimeout(unsigned long milliseconds
);
290 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
293 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
297 // make it practically infinite
301 m_semaphore
= ::CreateSemaphore
303 NULL
, // default security attributes
311 wxLogLastError(_T("CreateSemaphore()"));
315 wxSemaphoreInternal::~wxSemaphoreInternal()
319 if ( !::CloseHandle(m_semaphore
) )
321 wxLogLastError(_T("CloseHandle(semaphore)"));
326 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
328 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
333 return wxSEMA_NO_ERROR
;
336 return wxSEMA_TIMEOUT
;
339 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
342 return wxSEMA_MISC_ERROR
;
345 wxSemaError
wxSemaphoreInternal::Post()
347 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
349 wxLogLastError(_T("ReleaseSemaphore"));
351 return wxSEMA_MISC_ERROR
;
354 return wxSEMA_NO_ERROR
;
357 // --------------------------------------------------------------------------
359 // --------------------------------------------------------------------------
361 // Win32 doesn't have explicit support for the POSIX condition variables and
362 // the Win32 events have quite different semantics, so we reimplement the
363 // conditions from scratch using the mutexes and semaphores
364 class wxConditionInternal
367 wxConditionInternal(wxMutex
& mutex
);
369 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
372 wxCondError
WaitTimeout(unsigned long milliseconds
);
374 wxCondError
Signal();
375 wxCondError
Broadcast();
378 // the number of threads currently waiting for this condition
381 // the critical section protecting m_numWaiters
382 wxCriticalSection m_csWaiters
;
385 wxSemaphore m_semaphore
;
388 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
391 // another thread can't access it until we return from ctor, so no need to
392 // protect access to m_numWaiters here
396 wxCondError
wxConditionInternal::Wait()
398 // increment the number of waiters
399 ::InterlockedIncrement(&m_numWaiters
);
403 // a potential race condition can occur here
405 // after a thread increments nwaiters, and unlocks the mutex and before the
406 // semaphore.Wait() is called, if another thread can cause a signal to be
409 // this race condition is handled by using a semaphore and incrementing the
410 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
411 // can 'remember' signals the race condition will not occur
413 // wait ( if necessary ) and decrement semaphore
414 wxSemaError err
= m_semaphore
.Wait();
417 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
420 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
422 ::InterlockedIncrement(&m_numWaiters
);
426 // a race condition can occur at this point in the code
428 // please see the comments in Wait(), for details
430 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
432 if ( err
== wxSEMA_BUSY
)
434 // another potential race condition exists here it is caused when a
435 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
436 // has not yet decremented 'nwaiters'.
438 // at this point if another thread calls signal() then the semaphore
439 // will be incremented, but the waiting thread will miss it.
441 // to handle this particular case, the waiting thread calls
442 // WaitForSingleObject again with a timeout of 0, after locking
443 // 'nwaiters_mutex'. this call does not block because of the zero
444 // timeout, but will allow the waiting thread to catch the missed
446 wxCriticalSectionLocker
lock(m_csWaiters
);
448 err
= m_semaphore
.WaitTimeout(0);
450 if ( err
!= wxSEMA_NO_ERROR
)
458 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
461 wxCondError
wxConditionInternal::Signal()
463 wxCriticalSectionLocker
lock(m_csWaiters
);
465 if ( m_numWaiters
> 0 )
467 // increment the semaphore by 1
468 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
469 return wxCOND_MISC_ERROR
;
474 return wxCOND_NO_ERROR
;
477 wxCondError
wxConditionInternal::Broadcast()
479 wxCriticalSectionLocker
lock(m_csWaiters
);
481 while ( m_numWaiters
> 0 )
483 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
484 return wxCOND_MISC_ERROR
;
489 return wxCOND_NO_ERROR
;
492 // ----------------------------------------------------------------------------
493 // wxThread implementation
494 // ----------------------------------------------------------------------------
496 // wxThreadInternal class
497 // ----------------------
499 class wxThreadInternal
506 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
518 if ( !::CloseHandle(m_hThread
) )
520 wxLogLastError(wxT("CloseHandle(thread)"));
527 // create a new (suspended) thread (for the given thread object)
528 bool Create(wxThread
*thread
, unsigned int stackSize
);
530 // suspend/resume/terminate
533 void Cancel() { m_state
= STATE_CANCELED
; }
536 void SetState(wxThreadState state
) { m_state
= state
; }
537 wxThreadState
GetState() const { return m_state
; }
540 void SetPriority(unsigned int priority
);
541 unsigned int GetPriority() const { return m_priority
; }
543 // thread handle and id
544 HANDLE
GetHandle() const { return m_hThread
; }
545 DWORD
GetId() const { return m_tid
; }
548 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
551 HANDLE m_hThread
; // handle of the thread
552 wxThreadState m_state
; // state, see wxThreadState enum
553 unsigned int m_priority
; // thread priority in "wx" units
554 DWORD m_tid
; // thread id
556 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
559 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
564 // first of all, check whether we hadn't been cancelled already and don't
565 // start the user code at all then
566 wxThread
*thread
= (wxThread
*)param
;
567 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
569 rc
= (THREAD_RETVAL
)-1;
572 else // do run thread
574 // store the thread object in the TLS
575 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
577 wxLogSysError(_("Can not start thread: error writing TLS."));
582 rc
= (THREAD_RETVAL
)thread
->Entry();
584 // enter m_critsect before changing the thread state
585 thread
->m_critsect
.Enter();
586 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
587 thread
->m_internal
->SetState(STATE_EXITED
);
588 thread
->m_critsect
.Leave();
593 // if the thread was cancelled (from Delete()), then its handle is still
595 if ( thread
->IsDetached() && !wasCancelled
)
600 //else: the joinable threads handle will be closed when Wait() is done
605 void wxThreadInternal::SetPriority(unsigned int priority
)
607 m_priority
= priority
;
609 // translate wxWindows priority to the Windows one
611 if (m_priority
<= 20)
612 win_priority
= THREAD_PRIORITY_LOWEST
;
613 else if (m_priority
<= 40)
614 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
615 else if (m_priority
<= 60)
616 win_priority
= THREAD_PRIORITY_NORMAL
;
617 else if (m_priority
<= 80)
618 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
619 else if (m_priority
<= 100)
620 win_priority
= THREAD_PRIORITY_HIGHEST
;
623 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
624 win_priority
= THREAD_PRIORITY_NORMAL
;
627 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
629 wxLogSysError(_("Can't set thread priority"));
633 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
635 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
636 _T("Create()ing thread twice?") );
638 // for compilers which have it, we should use C RTL function for thread
639 // creation instead of Win32 API one because otherwise we will have memory
640 // leaks if the thread uses C RTL (and most threads do)
641 #ifdef wxUSE_BEGIN_THREAD
643 // Watcom is reported to not like 0 stack size (which means "use default"
644 // for the other compilers and is also the default value for stackSize)
648 #endif // __WATCOMC__
650 m_hThread
= (HANDLE
)_beginthreadex
652 NULL
, // default security
654 wxThreadInternal::WinThreadStart
, // entry point
657 (unsigned int *)&m_tid
659 #else // compiler doesn't have _beginthreadex
660 m_hThread
= ::CreateThread
662 NULL
, // default security
663 stackSize
, // stack size
664 wxThreadInternal::WinThreadStart
, // thread entry point
665 (LPVOID
)thread
, // parameter
666 CREATE_SUSPENDED
, // flags
667 &m_tid
// [out] thread id
669 #endif // _beginthreadex/CreateThread
671 if ( m_hThread
== NULL
)
673 wxLogSysError(_("Can't create thread"));
678 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
680 SetPriority(m_priority
);
686 bool wxThreadInternal::Suspend()
688 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
689 if ( nSuspendCount
== (DWORD
)-1 )
691 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
696 m_state
= STATE_PAUSED
;
701 bool wxThreadInternal::Resume()
703 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
704 if ( nSuspendCount
== (DWORD
)-1 )
706 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
711 // don't change the state from STATE_EXITED because it's special and means
712 // we are going to terminate without running any user code - if we did it,
713 // the codei n Delete() wouldn't work
714 if ( m_state
!= STATE_EXITED
)
716 m_state
= STATE_RUNNING
;
725 wxThread
*wxThread::This()
727 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
729 // be careful, 0 may be a valid return value as well
730 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
732 wxLogSysError(_("Couldn't get the current thread pointer"));
740 bool wxThread::IsMain()
742 return ::GetCurrentThreadId() == gs_idMainThread
;
749 void wxThread::Yield()
751 // 0 argument to Sleep() is special and means to just give away the rest of
756 void wxThread::Sleep(unsigned long milliseconds
)
758 ::Sleep(milliseconds
);
761 int wxThread::GetCPUCount()
766 return si
.dwNumberOfProcessors
;
769 unsigned long wxThread::GetCurrentId()
771 return (unsigned long)::GetCurrentThreadId();
774 bool wxThread::SetConcurrency(size_t level
)
776 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
778 // ok only for the default one
782 // get system affinity mask first
783 HANDLE hProcess
= ::GetCurrentProcess();
784 DWORD dwProcMask
, dwSysMask
;
785 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
787 wxLogLastError(_T("GetProcessAffinityMask"));
792 // how many CPUs have we got?
793 if ( dwSysMask
== 1 )
795 // don't bother with all this complicated stuff - on a single
796 // processor system it doesn't make much sense anyhow
800 // calculate the process mask: it's a bit vector with one bit per
801 // processor; we want to schedule the process to run on first level
806 if ( dwSysMask
& bit
)
808 // ok, we can set this bit
811 // another process added
823 // could we set all bits?
826 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
831 // set it: we can't link to SetProcessAffinityMask() because it doesn't
832 // exist in Win9x, use RT binding instead
834 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
836 // can use static var because we're always in the main thread here
837 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
839 if ( !pfnSetProcessAffinityMask
)
841 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
844 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
845 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
848 // we've discovered a MT version of Win9x!
849 wxASSERT_MSG( pfnSetProcessAffinityMask
,
850 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
853 if ( !pfnSetProcessAffinityMask
)
855 // msg given above - do it only once
859 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
861 wxLogLastError(_T("SetProcessAffinityMask"));
872 wxThread::wxThread(wxThreadKind kind
)
874 m_internal
= new wxThreadInternal();
876 m_isDetached
= kind
== wxTHREAD_DETACHED
;
879 wxThread::~wxThread()
884 // create/start thread
885 // -------------------
887 wxThreadError
wxThread::Create(unsigned int stackSize
)
889 wxCriticalSectionLocker
lock(m_critsect
);
891 if ( !m_internal
->Create(this, stackSize
) )
892 return wxTHREAD_NO_RESOURCE
;
894 return wxTHREAD_NO_ERROR
;
897 wxThreadError
wxThread::Run()
899 wxCriticalSectionLocker
lock(m_critsect
);
901 if ( m_internal
->GetState() != STATE_NEW
)
903 // actually, it may be almost any state at all, not only STATE_RUNNING
904 return wxTHREAD_RUNNING
;
907 // the thread has just been created and is still suspended - let it run
911 // suspend/resume thread
912 // ---------------------
914 wxThreadError
wxThread::Pause()
916 wxCriticalSectionLocker
lock(m_critsect
);
918 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
921 wxThreadError
wxThread::Resume()
923 wxCriticalSectionLocker
lock(m_critsect
);
925 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
931 wxThread::ExitCode
wxThread::Wait()
933 // although under Windows we can wait for any thread, it's an error to
934 // wait for a detached one in wxWin API
935 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
936 _T("can't wait for detached thread") );
938 ExitCode rc
= (ExitCode
)-1;
947 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
951 // Delete() is always safe to call, so consider all possible states
953 // we might need to resume the thread, but we might also not need to cancel
954 // it if it doesn't run yet
955 bool shouldResume
= FALSE
,
959 // check if the thread already started to run
961 wxCriticalSectionLocker
lock(m_critsect
);
963 if ( m_internal
->GetState() == STATE_NEW
)
965 // WinThreadStart() will see it and terminate immediately, no need
966 // to cancel the thread - but we still need to resume it to let it
968 m_internal
->SetState(STATE_EXITED
);
970 Resume(); // it knows about STATE_EXITED special case
972 shouldCancel
= FALSE
;
975 // shouldResume is correctly set to FALSE here
979 shouldResume
= IsPaused();
983 // resume the thread if it is paused
987 HANDLE hThread
= m_internal
->GetHandle();
989 // does is still run?
990 if ( isRunning
|| IsRunning() )
994 // set flag for wxIsWaitingForThread()
995 gs_waitingForThread
= TRUE
;
998 // ask the thread to terminate
1001 wxCriticalSectionLocker
lock(m_critsect
);
1003 m_internal
->Cancel();
1006 // we can't just wait for the thread to terminate because it might be
1007 // calling some GUI functions and so it will never terminate before we
1008 // process the Windows messages that result from these functions
1009 // (note that even in console applications we might have to process
1010 // messages if we use wxExecute() or timers or ...)
1011 DWORD result
= 0; // suppress warnings from broken compilers
1016 // give the thread we're waiting for chance to do the GUI call
1018 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1024 result
= ::MsgWaitForMultipleObjects
1026 1, // number of objects to wait for
1027 &hThread
, // the objects
1028 FALSE
, // don't wait for all objects
1029 INFINITE
, // no timeout
1030 QS_ALLINPUT
| // return as soon as there are any events
1038 wxLogSysError(_("Can not wait for thread termination"));
1040 return wxTHREAD_KILLED
;
1043 // thread we're waiting for terminated
1046 case WAIT_OBJECT_0
+ 1:
1047 // new message arrived, process it
1049 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
1052 if ( traits
&& !traits
->DoMessageFromThreadWait() )
1054 // WM_QUIT received: kill the thread
1057 return wxTHREAD_KILLED
;
1063 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1065 } while ( result
!= WAIT_OBJECT_0
);
1069 gs_waitingForThread
= FALSE
;
1073 // although the thread might be already in the EXITED state it might not
1074 // have terminated yet and so we are not sure that it has actually
1075 // terminated if the "if" above hadn't been taken
1078 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1080 wxLogLastError(wxT("GetExitCodeThread"));
1084 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1088 // if the thread exits normally, this is done in WinThreadStart, but in
1089 // this case it would have been too early because
1090 // MsgWaitForMultipleObject() would fail if the thread handle was
1091 // closed while we were waiting on it, so we must do it here
1098 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1101 wxThreadError
wxThread::Kill()
1104 return wxTHREAD_NOT_RUNNING
;
1106 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1108 wxLogSysError(_("Couldn't terminate thread"));
1110 return wxTHREAD_MISC_ERROR
;
1120 return wxTHREAD_NO_ERROR
;
1123 void wxThread::Exit(ExitCode status
)
1132 #ifdef wxUSE_BEGIN_THREAD
1133 _endthreadex((unsigned)status
);
1135 ::ExitThread((DWORD
)status
);
1136 #endif // VC++/!VC++
1138 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1144 void wxThread::SetPriority(unsigned int prio
)
1146 wxCriticalSectionLocker
lock(m_critsect
);
1148 m_internal
->SetPriority(prio
);
1151 unsigned int wxThread::GetPriority() const
1153 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1155 return m_internal
->GetPriority();
1158 unsigned long wxThread::GetId() const
1160 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1162 return (unsigned long)m_internal
->GetId();
1165 bool wxThread::IsRunning() const
1167 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1169 return m_internal
->GetState() == STATE_RUNNING
;
1172 bool wxThread::IsAlive() const
1174 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1176 return (m_internal
->GetState() == STATE_RUNNING
) ||
1177 (m_internal
->GetState() == STATE_PAUSED
);
1180 bool wxThread::IsPaused() const
1182 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1184 return m_internal
->GetState() == STATE_PAUSED
;
1187 bool wxThread::TestDestroy()
1189 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1191 return m_internal
->GetState() == STATE_CANCELED
;
1194 // ----------------------------------------------------------------------------
1195 // Automatic initialization for thread module
1196 // ----------------------------------------------------------------------------
1198 class wxThreadModule
: public wxModule
1201 virtual bool OnInit();
1202 virtual void OnExit();
1205 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1208 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1210 bool wxThreadModule::OnInit()
1212 // allocate TLS index for storing the pointer to the current thread
1213 gs_tlsThisThread
= ::TlsAlloc();
1214 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1216 // in normal circumstances it will only happen if all other
1217 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1218 // words, this should never happen
1219 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1224 // main thread doesn't have associated wxThread object, so store 0 in the
1226 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1228 ::TlsFree(gs_tlsThisThread
);
1229 gs_tlsThisThread
= 0xFFFFFFFF;
1231 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1236 gs_critsectWaitingForGui
= new wxCriticalSection();
1238 gs_critsectGui
= new wxCriticalSection();
1239 gs_critsectGui
->Enter();
1241 // no error return for GetCurrentThreadId()
1242 gs_idMainThread
= ::GetCurrentThreadId();
1247 void wxThreadModule::OnExit()
1249 if ( !::TlsFree(gs_tlsThisThread
) )
1251 wxLogLastError(wxT("TlsFree failed."));
1254 if ( gs_critsectGui
)
1256 gs_critsectGui
->Leave();
1257 delete gs_critsectGui
;
1258 gs_critsectGui
= NULL
;
1261 delete gs_critsectWaitingForGui
;
1262 gs_critsectWaitingForGui
= NULL
;
1265 // ----------------------------------------------------------------------------
1266 // under Windows, these functions are implemented using a critical section and
1267 // not a mutex, so the names are a bit confusing
1268 // ----------------------------------------------------------------------------
1270 void WXDLLEXPORT
wxMutexGuiEnter()
1272 // this would dead lock everything...
1273 wxASSERT_MSG( !wxThread::IsMain(),
1274 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1276 // the order in which we enter the critical sections here is crucial!!
1278 // set the flag telling to the main thread that we want to do some GUI
1280 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1282 gs_nWaitingForGui
++;
1285 wxWakeUpMainThread();
1287 // now we may block here because the main thread will soon let us in
1288 // (during the next iteration of OnIdle())
1289 gs_critsectGui
->Enter();
1292 void WXDLLEXPORT
wxMutexGuiLeave()
1294 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1296 if ( wxThread::IsMain() )
1298 gs_bGuiOwnedByMainThread
= FALSE
;
1302 // decrement the number of threads waiting for GUI access now
1303 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1304 wxT("calling wxMutexGuiLeave() without entering it first?") );
1306 gs_nWaitingForGui
--;
1308 wxWakeUpMainThread();
1311 gs_critsectGui
->Leave();
1314 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1316 wxASSERT_MSG( wxThread::IsMain(),
1317 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1319 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1321 if ( gs_nWaitingForGui
== 0 )
1323 // no threads are waiting for GUI - so we may acquire the lock without
1324 // any danger (but only if we don't already have it)
1325 if ( !wxGuiOwnedByMainThread() )
1327 gs_critsectGui
->Enter();
1329 gs_bGuiOwnedByMainThread
= TRUE
;
1331 //else: already have it, nothing to do
1335 // some threads are waiting, release the GUI lock if we have it
1336 if ( wxGuiOwnedByMainThread() )
1340 //else: some other worker thread is doing GUI
1344 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1346 return gs_bGuiOwnedByMainThread
;
1349 // wake up the main thread if it's in ::GetMessage()
1350 void WXDLLEXPORT
wxWakeUpMainThread()
1352 // sending any message would do - hopefully WM_NULL is harmless enough
1353 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1355 // should never happen
1356 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1360 bool WXDLLEXPORT
wxIsWaitingForThread()
1362 return gs_waitingForThread
;
1365 // ----------------------------------------------------------------------------
1366 // include common implementation code
1367 // ----------------------------------------------------------------------------
1369 #include "wx/thrimpl.cpp"
1371 #endif // wxUSE_THREADS