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 /////////////////////////////////////////////////////////////////////////////
13 // ----------------------------------------------------------------------------
15 // ----------------------------------------------------------------------------
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
20 #if defined(__BORLANDC__)
31 #include "wx/apptrait.h"
33 #include "wx/msw/private.h"
34 #include "wx/msw/missing.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__)
64 #undef wxUSE_BEGIN_THREAD
65 #define wxUSE_BEGIN_THREAD
70 #ifdef wxUSE_BEGIN_THREAD
71 // this is where _beginthreadex() is declared
74 // the return type of the thread function entry point
75 typedef unsigned THREAD_RETVAL
;
77 // the calling convention of the thread function entry point
78 #define THREAD_CALLCONV __stdcall
80 // the settings for CreateThread()
81 typedef DWORD THREAD_RETVAL
;
82 #define THREAD_CALLCONV WINAPI
85 // ----------------------------------------------------------------------------
87 // ----------------------------------------------------------------------------
89 // the possible states of the thread ("=>" shows all possible transitions from
93 STATE_NEW
, // didn't start execution yet (=> RUNNING)
94 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
95 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
96 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
97 STATE_EXITED
// thread is terminating
100 // ----------------------------------------------------------------------------
101 // this module globals
102 // ----------------------------------------------------------------------------
104 // TLS index of the slot where we store the pointer to the current thread
105 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
107 // id of the main thread - the one which can call GUI functions without first
108 // calling wxMutexGuiEnter()
109 static DWORD gs_idMainThread
= 0;
111 // if it's false, some secondary thread is holding the GUI lock
112 static bool gs_bGuiOwnedByMainThread
= true;
114 // critical section which controls access to all GUI functions: any secondary
115 // thread (i.e. except the main one) must enter this crit section before doing
117 static wxCriticalSection
*gs_critsectGui
= NULL
;
119 // critical section which protects gs_nWaitingForGui variable
120 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
122 // critical section which serializes WinThreadStart() and WaitForTerminate()
123 // (this is a potential bottleneck, we use a single crit sect for all threads
124 // in the system, but normally time spent inside it should be quite short)
125 static wxCriticalSection
*gs_critsectThreadDelete
= NULL
;
127 // number of threads waiting for GUI in wxMutexGuiEnter()
128 static size_t gs_nWaitingForGui
= 0;
130 // are we waiting for a thread termination?
131 static bool gs_waitingForThread
= false;
133 // ============================================================================
134 // Windows implementation of thread and related classes
135 // ============================================================================
137 // ----------------------------------------------------------------------------
139 // ----------------------------------------------------------------------------
141 wxCriticalSection::wxCriticalSection()
143 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
144 wxCriticalSectionBufferTooSmall
);
146 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
149 wxCriticalSection::~wxCriticalSection()
151 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
154 void wxCriticalSection::Enter()
156 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
159 void wxCriticalSection::Leave()
161 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
164 // ----------------------------------------------------------------------------
166 // ----------------------------------------------------------------------------
168 class wxMutexInternal
171 wxMutexInternal(wxMutexType mutexType
);
174 bool IsOk() const { return m_mutex
!= NULL
; }
176 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
177 wxMutexError
TryLock() { return LockTimeout(0); }
178 wxMutexError
Unlock();
181 wxMutexError
LockTimeout(DWORD milliseconds
);
185 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
188 // all mutexes are recursive under Win32 so we don't use mutexType
189 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
191 // create a nameless (hence intra process and always private) mutex
192 m_mutex
= ::CreateMutex
194 NULL
, // default secutiry attributes
195 false, // not initially locked
201 wxLogLastError(_T("CreateMutex()"));
205 wxMutexInternal::~wxMutexInternal()
209 if ( !::CloseHandle(m_mutex
) )
211 wxLogLastError(_T("CloseHandle(mutex)"));
216 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
218 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
219 if ( rc
== WAIT_ABANDONED
)
221 // the previous caller died without releasing the mutex, but now we can
223 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
225 // use 0 timeout, normally we should always get it
226 rc
= ::WaitForSingleObject(m_mutex
, 0);
238 case WAIT_ABANDONED
: // checked for above
240 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
244 wxLogLastError(_T("WaitForSingleObject(mutex)"));
245 return wxMUTEX_MISC_ERROR
;
248 return wxMUTEX_NO_ERROR
;
251 wxMutexError
wxMutexInternal::Unlock()
253 if ( !::ReleaseMutex(m_mutex
) )
255 wxLogLastError(_T("ReleaseMutex()"));
257 return wxMUTEX_MISC_ERROR
;
260 return wxMUTEX_NO_ERROR
;
263 // --------------------------------------------------------------------------
265 // --------------------------------------------------------------------------
267 // a trivial wrapper around Win32 semaphore
268 class wxSemaphoreInternal
271 wxSemaphoreInternal(int initialcount
, int maxcount
);
272 ~wxSemaphoreInternal();
274 bool IsOk() const { return m_semaphore
!= NULL
; }
276 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
278 wxSemaError
TryWait()
280 wxSemaError rc
= WaitTimeout(0);
281 if ( rc
== wxSEMA_TIMEOUT
)
287 wxSemaError
WaitTimeout(unsigned long milliseconds
);
294 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
297 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
299 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
302 // make it practically infinite
306 m_semaphore
= ::CreateSemaphore
308 NULL
, // default security attributes
316 wxLogLastError(_T("CreateSemaphore()"));
320 wxSemaphoreInternal::~wxSemaphoreInternal()
324 if ( !::CloseHandle(m_semaphore
) )
326 wxLogLastError(_T("CloseHandle(semaphore)"));
331 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
333 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
338 return wxSEMA_NO_ERROR
;
341 return wxSEMA_TIMEOUT
;
344 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
347 return wxSEMA_MISC_ERROR
;
350 wxSemaError
wxSemaphoreInternal::Post()
352 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
353 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
356 wxLogLastError(_T("ReleaseSemaphore"));
358 return wxSEMA_MISC_ERROR
;
361 return wxSEMA_NO_ERROR
;
364 // ----------------------------------------------------------------------------
365 // wxThread implementation
366 // ----------------------------------------------------------------------------
368 // wxThreadInternal class
369 // ----------------------
371 class wxThreadInternal
374 wxThreadInternal(wxThread
*thread
)
379 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
392 if ( !::CloseHandle(m_hThread
) )
394 wxLogLastError(wxT("CloseHandle(thread)"));
401 // create a new (suspended) thread (for the given thread object)
402 bool Create(wxThread
*thread
, unsigned int stackSize
);
404 // wait for the thread to terminate, either by itself, or by asking it
405 // (politely, this is not Kill()!) to do it
406 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
407 wxThread::ExitCode
*pRc
,
408 wxThread
*threadToDelete
= NULL
);
410 // kill the thread unconditionally
411 wxThreadError
Kill();
413 // suspend/resume/terminate
416 void Cancel() { m_state
= STATE_CANCELED
; }
419 void SetState(wxThreadState state
) { m_state
= state
; }
420 wxThreadState
GetState() const { return m_state
; }
423 void SetPriority(unsigned int priority
);
424 unsigned int GetPriority() const { return m_priority
; }
426 // thread handle and id
427 HANDLE
GetHandle() const { return m_hThread
; }
428 DWORD
GetId() const { return m_tid
; }
431 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
435 if ( m_thread
->IsDetached() )
436 ::InterlockedIncrement(&m_nRef
);
441 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
446 // the thread we're associated with
449 HANDLE m_hThread
; // handle of the thread
450 wxThreadState m_state
; // state, see wxThreadState enum
451 unsigned int m_priority
; // thread priority in "wx" units
452 DWORD m_tid
; // thread id
454 // number of threads which need this thread to remain alive, when the count
455 // reaches 0 we kill the owning wxThread -- and die ourselves with it
458 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
461 // small class which keeps a thread alive during its lifetime
462 class wxThreadKeepAlive
465 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
466 { m_thrImpl
.KeepAlive(); }
468 { m_thrImpl
.LetDie(); }
471 wxThreadInternal
& m_thrImpl
;
475 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
479 wxThread
* const thread
= (wxThread
*)param
;
481 // first of all, check whether we hadn't been cancelled already and don't
482 // start the user code at all then
483 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
487 rc
= (THREAD_RETVAL
)-1;
489 else // do run thread
491 // store the thread object in the TLS
492 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
494 wxLogSysError(_("Can not start thread: error writing TLS."));
499 rc
= (THREAD_RETVAL
)thread
->Entry();
504 // save IsDetached because thread object can be deleted by joinable
505 // threads after state is changed to STATE_EXITED.
506 bool isDetached
= thread
->IsDetached();
510 // enter m_critsect before changing the thread state
511 wxCriticalSectionLocker
lock(thread
->m_critsect
);
512 thread
->m_internal
->SetState(STATE_EXITED
);
515 // the thread may delete itself now if it wants, we don't need it any more
517 thread
->m_internal
->LetDie();
522 void wxThreadInternal::SetPriority(unsigned int priority
)
524 m_priority
= priority
;
526 // translate wxWidgets priority to the Windows one
528 if (m_priority
<= 20)
529 win_priority
= THREAD_PRIORITY_LOWEST
;
530 else if (m_priority
<= 40)
531 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
532 else if (m_priority
<= 60)
533 win_priority
= THREAD_PRIORITY_NORMAL
;
534 else if (m_priority
<= 80)
535 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
536 else if (m_priority
<= 100)
537 win_priority
= THREAD_PRIORITY_HIGHEST
;
540 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
541 win_priority
= THREAD_PRIORITY_NORMAL
;
544 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
546 wxLogSysError(_("Can't set thread priority"));
550 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
552 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
553 _T("Create()ing thread twice?") );
555 // for compilers which have it, we should use C RTL function for thread
556 // creation instead of Win32 API one because otherwise we will have memory
557 // leaks if the thread uses C RTL (and most threads do)
558 #ifdef wxUSE_BEGIN_THREAD
560 // Watcom is reported to not like 0 stack size (which means "use default"
561 // for the other compilers and is also the default value for stackSize)
565 #endif // __WATCOMC__
567 m_hThread
= (HANDLE
)_beginthreadex
569 NULL
, // default security
571 wxThreadInternal::WinThreadStart
, // entry point
574 (unsigned int *)&m_tid
576 #else // compiler doesn't have _beginthreadex
577 m_hThread
= ::CreateThread
579 NULL
, // default security
580 stackSize
, // stack size
581 wxThreadInternal::WinThreadStart
, // thread entry point
582 (LPVOID
)thread
, // parameter
583 CREATE_SUSPENDED
, // flags
584 &m_tid
// [out] thread id
586 #endif // _beginthreadex/CreateThread
588 if ( m_hThread
== NULL
)
590 wxLogSysError(_("Can't create thread"));
595 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
597 SetPriority(m_priority
);
603 wxThreadError
wxThreadInternal::Kill()
605 if ( !::TerminateThread(m_hThread
, (DWORD
)-1) )
607 wxLogSysError(_("Couldn't terminate thread"));
609 return wxTHREAD_MISC_ERROR
;
614 return wxTHREAD_NO_ERROR
;
618 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
619 wxThread::ExitCode
*pRc
,
620 wxThread
*threadToDelete
)
622 // prevent the thread C++ object from disappearing as long as we are using
624 wxThreadKeepAlive
keepAlive(*this);
627 // we may either wait passively for the thread to terminate (when called
628 // from Wait()) or ask it to terminate (when called from Delete())
629 bool shouldDelete
= threadToDelete
!= NULL
;
631 wxThread::ExitCode rc
= 0;
633 // we might need to resume the thread if it's currently stopped
634 bool shouldResume
= false;
636 // as Delete() (which calls us) is always safe to call we need to consider
637 // all possible states
639 wxCriticalSectionLocker
lock(cs
);
641 if ( m_state
== STATE_NEW
)
645 // WinThreadStart() will see it and terminate immediately, no
646 // need to cancel the thread -- but we still need to resume it
648 m_state
= STATE_EXITED
;
650 // we must call Resume() as the thread hasn't been initially
651 // resumed yet (and as Resume() it knows about STATE_EXITED
652 // special case, it won't touch it and WinThreadStart() will
653 // just exit immediately)
655 shouldDelete
= false;
657 //else: shouldResume is correctly set to false here, wait until
658 // someone else runs the thread and it finishes
660 else // running, paused, cancelled or even exited
662 shouldResume
= m_state
== STATE_PAUSED
;
666 // resume the thread if it is paused
670 // ask the thread to terminate
673 wxCriticalSectionLocker
lock(cs
);
679 // now wait for thread to finish
680 if ( wxThread::IsMain() )
682 // set flag for wxIsWaitingForThread()
683 gs_waitingForThread
= true;
686 // we can't just wait for the thread to terminate because it might be
687 // calling some GUI functions and so it will never terminate before we
688 // process the Windows messages that result from these functions
689 // (note that even in console applications we might have to process
690 // messages if we use wxExecute() or timers or ...)
691 DWORD result
wxDUMMY_INITIALIZE(0);
694 if ( wxThread::IsMain() )
696 // give the thread we're waiting for chance to do the GUI call
698 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
704 #if !defined(QS_ALLPOSTMESSAGE)
705 #define QS_ALLPOSTMESSAGE 0
708 result
= ::MsgWaitForMultipleObjects
710 1, // number of objects to wait for
711 &m_hThread
, // the objects
712 false, // don't wait for all objects
713 INFINITE
, // no timeout
714 QS_ALLINPUT
|QS_ALLPOSTMESSAGE
// return as soon as there are any events
721 wxLogSysError(_("Can not wait for thread termination"));
723 return wxTHREAD_KILLED
;
726 // thread we're waiting for terminated
729 case WAIT_OBJECT_0
+ 1:
730 // new message arrived, process it -- but only if we're the
731 // main thread as we don't support processing messages in
734 // NB: we still must include QS_ALLINPUT even when waiting
735 // in a secondary thread because if it had created some
736 // window somehow (possible not even using wxWidgets)
737 // the system might dead lock then
738 if ( wxThread::IsMain() )
740 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
743 if ( traits
&& !traits
->DoMessageFromThreadWait() )
745 // WM_QUIT received: kill the thread
748 return wxTHREAD_KILLED
;
754 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
756 } while ( result
!= WAIT_OBJECT_0
);
758 if ( wxThread::IsMain() )
760 gs_waitingForThread
= false;
764 // although the thread might be already in the EXITED state it might not
765 // have terminated yet and so we are not sure that it has actually
766 // terminated if the "if" above hadn't been taken
769 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
771 wxLogLastError(wxT("GetExitCodeThread"));
773 rc
= (wxThread::ExitCode
)-1;
778 if ( (DWORD
)rc
!= STILL_ACTIVE
)
781 // give the other thread some time to terminate, otherwise we may be
789 // we don't need the thread handle any more in any case
793 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
797 bool wxThreadInternal::Suspend()
799 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
800 if ( nSuspendCount
== (DWORD
)-1 )
802 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
807 m_state
= STATE_PAUSED
;
812 bool wxThreadInternal::Resume()
814 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
815 if ( nSuspendCount
== (DWORD
)-1 )
817 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
822 // don't change the state from STATE_EXITED because it's special and means
823 // we are going to terminate without running any user code - if we did it,
824 // the code in WaitForTerminate() wouldn't work
825 if ( m_state
!= STATE_EXITED
)
827 m_state
= STATE_RUNNING
;
836 wxThread
*wxThread::This()
838 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
840 // be careful, 0 may be a valid return value as well
841 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
843 wxLogSysError(_("Couldn't get the current thread pointer"));
851 bool wxThread::IsMain()
853 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
856 void wxThread::Yield()
858 // 0 argument to Sleep() is special and means to just give away the rest of
863 void wxThread::Sleep(unsigned long milliseconds
)
865 ::Sleep(milliseconds
);
868 int wxThread::GetCPUCount()
873 return si
.dwNumberOfProcessors
;
876 unsigned long wxThread::GetCurrentId()
878 return (unsigned long)::GetCurrentThreadId();
881 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
886 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
888 // ok only for the default one
892 // get system affinity mask first
893 HANDLE hProcess
= ::GetCurrentProcess();
894 DWORD_PTR dwProcMask
, dwSysMask
;
895 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
897 wxLogLastError(_T("GetProcessAffinityMask"));
902 // how many CPUs have we got?
903 if ( dwSysMask
== 1 )
905 // don't bother with all this complicated stuff - on a single
906 // processor system it doesn't make much sense anyhow
910 // calculate the process mask: it's a bit vector with one bit per
911 // processor; we want to schedule the process to run on first level
916 if ( dwSysMask
& bit
)
918 // ok, we can set this bit
921 // another process added
933 // could we set all bits?
936 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
941 // set it: we can't link to SetProcessAffinityMask() because it doesn't
942 // exist in Win9x, use RT binding instead
944 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
946 // can use static var because we're always in the main thread here
947 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
949 if ( !pfnSetProcessAffinityMask
)
951 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
954 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
955 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
958 // we've discovered a MT version of Win9x!
959 wxASSERT_MSG( pfnSetProcessAffinityMask
,
960 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
963 if ( !pfnSetProcessAffinityMask
)
965 // msg given above - do it only once
969 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
971 wxLogLastError(_T("SetProcessAffinityMask"));
977 #endif // __WXWINCE__/!__WXWINCE__
983 wxThread::wxThread(wxThreadKind kind
)
985 m_internal
= new wxThreadInternal(this);
987 m_isDetached
= kind
== wxTHREAD_DETACHED
;
990 wxThread::~wxThread()
995 // create/start thread
996 // -------------------
998 wxThreadError
wxThread::Create(unsigned int stackSize
)
1000 wxCriticalSectionLocker
lock(m_critsect
);
1002 if ( !m_internal
->Create(this, stackSize
) )
1003 return wxTHREAD_NO_RESOURCE
;
1005 return wxTHREAD_NO_ERROR
;
1008 wxThreadError
wxThread::Run()
1010 wxCriticalSectionLocker
lock(m_critsect
);
1012 if ( m_internal
->GetState() != STATE_NEW
)
1014 // actually, it may be almost any state at all, not only STATE_RUNNING
1015 return wxTHREAD_RUNNING
;
1018 // the thread has just been created and is still suspended - let it run
1022 // suspend/resume thread
1023 // ---------------------
1025 wxThreadError
wxThread::Pause()
1027 wxCriticalSectionLocker
lock(m_critsect
);
1029 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1032 wxThreadError
wxThread::Resume()
1034 wxCriticalSectionLocker
lock(m_critsect
);
1036 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1042 wxThread::ExitCode
wxThread::Wait()
1044 // although under Windows we can wait for any thread, it's an error to
1045 // wait for a detached one in wxWin API
1046 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1047 _T("wxThread::Wait(): can't wait for detached thread") );
1049 ExitCode rc
= (ExitCode
)-1;
1051 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1056 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1058 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1061 wxThreadError
wxThread::Kill()
1064 return wxTHREAD_NOT_RUNNING
;
1066 wxThreadError rc
= m_internal
->Kill();
1074 // update the status of the joinable thread
1075 wxCriticalSectionLocker
lock(m_critsect
);
1076 m_internal
->SetState(STATE_EXITED
);
1082 void wxThread::Exit(ExitCode status
)
1092 // update the status of the joinable thread
1093 wxCriticalSectionLocker
lock(m_critsect
);
1094 m_internal
->SetState(STATE_EXITED
);
1097 #ifdef wxUSE_BEGIN_THREAD
1098 _endthreadex((unsigned)status
);
1100 ::ExitThread((DWORD
)status
);
1101 #endif // VC++/!VC++
1103 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1109 void wxThread::SetPriority(unsigned int prio
)
1111 wxCriticalSectionLocker
lock(m_critsect
);
1113 m_internal
->SetPriority(prio
);
1116 unsigned int wxThread::GetPriority() const
1118 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1120 return m_internal
->GetPriority();
1123 unsigned long wxThread::GetId() const
1125 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1127 return (unsigned long)m_internal
->GetId();
1130 bool wxThread::IsRunning() const
1132 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1134 return m_internal
->GetState() == STATE_RUNNING
;
1137 bool wxThread::IsAlive() const
1139 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1141 return (m_internal
->GetState() == STATE_RUNNING
) ||
1142 (m_internal
->GetState() == STATE_PAUSED
);
1145 bool wxThread::IsPaused() const
1147 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1149 return m_internal
->GetState() == STATE_PAUSED
;
1152 bool wxThread::TestDestroy()
1154 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1156 return m_internal
->GetState() == STATE_CANCELED
;
1159 // ----------------------------------------------------------------------------
1160 // Automatic initialization for thread module
1161 // ----------------------------------------------------------------------------
1163 class wxThreadModule
: public wxModule
1166 virtual bool OnInit();
1167 virtual void OnExit();
1170 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1173 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1175 bool wxThreadModule::OnInit()
1177 // allocate TLS index for storing the pointer to the current thread
1178 gs_tlsThisThread
= ::TlsAlloc();
1179 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1181 // in normal circumstances it will only happen if all other
1182 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1183 // words, this should never happen
1184 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1189 // main thread doesn't have associated wxThread object, so store 0 in the
1191 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1193 ::TlsFree(gs_tlsThisThread
);
1194 gs_tlsThisThread
= 0xFFFFFFFF;
1196 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1201 gs_critsectWaitingForGui
= new wxCriticalSection();
1203 gs_critsectGui
= new wxCriticalSection();
1204 gs_critsectGui
->Enter();
1206 gs_critsectThreadDelete
= new wxCriticalSection
;
1208 // no error return for GetCurrentThreadId()
1209 gs_idMainThread
= ::GetCurrentThreadId();
1214 void wxThreadModule::OnExit()
1216 if ( !::TlsFree(gs_tlsThisThread
) )
1218 wxLogLastError(wxT("TlsFree failed."));
1221 delete gs_critsectThreadDelete
;
1222 gs_critsectThreadDelete
= NULL
;
1224 if ( gs_critsectGui
)
1226 gs_critsectGui
->Leave();
1227 delete gs_critsectGui
;
1228 gs_critsectGui
= NULL
;
1231 delete gs_critsectWaitingForGui
;
1232 gs_critsectWaitingForGui
= NULL
;
1235 // ----------------------------------------------------------------------------
1236 // under Windows, these functions are implemented using a critical section and
1237 // not a mutex, so the names are a bit confusing
1238 // ----------------------------------------------------------------------------
1240 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1242 // this would dead lock everything...
1243 wxASSERT_MSG( !wxThread::IsMain(),
1244 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1246 // the order in which we enter the critical sections here is crucial!!
1248 // set the flag telling to the main thread that we want to do some GUI
1250 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1252 gs_nWaitingForGui
++;
1255 wxWakeUpMainThread();
1257 // now we may block here because the main thread will soon let us in
1258 // (during the next iteration of OnIdle())
1259 gs_critsectGui
->Enter();
1262 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1264 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1266 if ( wxThread::IsMain() )
1268 gs_bGuiOwnedByMainThread
= false;
1272 // decrement the number of threads waiting for GUI access now
1273 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1274 wxT("calling wxMutexGuiLeave() without entering it first?") );
1276 gs_nWaitingForGui
--;
1278 wxWakeUpMainThread();
1281 gs_critsectGui
->Leave();
1284 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1286 wxASSERT_MSG( wxThread::IsMain(),
1287 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1289 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1291 if ( gs_nWaitingForGui
== 0 )
1293 // no threads are waiting for GUI - so we may acquire the lock without
1294 // any danger (but only if we don't already have it)
1295 if ( !wxGuiOwnedByMainThread() )
1297 gs_critsectGui
->Enter();
1299 gs_bGuiOwnedByMainThread
= true;
1301 //else: already have it, nothing to do
1305 // some threads are waiting, release the GUI lock if we have it
1306 if ( wxGuiOwnedByMainThread() )
1310 //else: some other worker thread is doing GUI
1314 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1316 return gs_bGuiOwnedByMainThread
;
1319 // wake up the main thread if it's in ::GetMessage()
1320 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1322 // sending any message would do - hopefully WM_NULL is harmless enough
1323 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1325 // should never happen
1326 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1330 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1332 return gs_waitingForThread
;
1335 // ----------------------------------------------------------------------------
1336 // include common implementation code
1337 // ----------------------------------------------------------------------------
1339 #include "wx/thrimpl.cpp"
1341 #endif // wxUSE_THREADS