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 // it looks that sometimes WAIT_OBJECT_0 + 1 is
741 // returned but there are no messages in the thread
742 // queue -- prevent DoMessageFromThreadWait() from
743 // blocking inside ::GetMessage() forever in this case
744 ::PostMessage(NULL
, WM_NULL
, 0, 0);
746 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
749 if ( traits
&& !traits
->DoMessageFromThreadWait() )
751 // WM_QUIT received: kill the thread
754 return wxTHREAD_KILLED
;
760 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
762 } while ( result
!= WAIT_OBJECT_0
);
764 if ( wxThread::IsMain() )
766 gs_waitingForThread
= false;
770 // although the thread might be already in the EXITED state it might not
771 // have terminated yet and so we are not sure that it has actually
772 // terminated if the "if" above hadn't been taken
775 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
777 wxLogLastError(wxT("GetExitCodeThread"));
779 rc
= (wxThread::ExitCode
)-1;
784 if ( (DWORD
)rc
!= STILL_ACTIVE
)
787 // give the other thread some time to terminate, otherwise we may be
795 // we don't need the thread handle any more in any case
799 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
803 bool wxThreadInternal::Suspend()
805 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
806 if ( nSuspendCount
== (DWORD
)-1 )
808 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
813 m_state
= STATE_PAUSED
;
818 bool wxThreadInternal::Resume()
820 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
821 if ( nSuspendCount
== (DWORD
)-1 )
823 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
828 // don't change the state from STATE_EXITED because it's special and means
829 // we are going to terminate without running any user code - if we did it,
830 // the code in WaitForTerminate() wouldn't work
831 if ( m_state
!= STATE_EXITED
)
833 m_state
= STATE_RUNNING
;
842 wxThread
*wxThread::This()
844 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
846 // be careful, 0 may be a valid return value as well
847 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
849 wxLogSysError(_("Couldn't get the current thread pointer"));
857 bool wxThread::IsMain()
859 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
862 void wxThread::Yield()
864 // 0 argument to Sleep() is special and means to just give away the rest of
869 void wxThread::Sleep(unsigned long milliseconds
)
871 ::Sleep(milliseconds
);
874 int wxThread::GetCPUCount()
879 return si
.dwNumberOfProcessors
;
882 unsigned long wxThread::GetCurrentId()
884 return (unsigned long)::GetCurrentThreadId();
887 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
892 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
894 // ok only for the default one
898 // get system affinity mask first
899 HANDLE hProcess
= ::GetCurrentProcess();
900 DWORD_PTR dwProcMask
, dwSysMask
;
901 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
903 wxLogLastError(_T("GetProcessAffinityMask"));
908 // how many CPUs have we got?
909 if ( dwSysMask
== 1 )
911 // don't bother with all this complicated stuff - on a single
912 // processor system it doesn't make much sense anyhow
916 // calculate the process mask: it's a bit vector with one bit per
917 // processor; we want to schedule the process to run on first level
922 if ( dwSysMask
& bit
)
924 // ok, we can set this bit
927 // another process added
939 // could we set all bits?
942 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
947 // set it: we can't link to SetProcessAffinityMask() because it doesn't
948 // exist in Win9x, use RT binding instead
950 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
952 // can use static var because we're always in the main thread here
953 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
955 if ( !pfnSetProcessAffinityMask
)
957 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
960 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
961 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
964 // we've discovered a MT version of Win9x!
965 wxASSERT_MSG( pfnSetProcessAffinityMask
,
966 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
969 if ( !pfnSetProcessAffinityMask
)
971 // msg given above - do it only once
975 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
977 wxLogLastError(_T("SetProcessAffinityMask"));
983 #endif // __WXWINCE__/!__WXWINCE__
989 wxThread::wxThread(wxThreadKind kind
)
991 m_internal
= new wxThreadInternal(this);
993 m_isDetached
= kind
== wxTHREAD_DETACHED
;
996 wxThread::~wxThread()
1001 // create/start thread
1002 // -------------------
1004 wxThreadError
wxThread::Create(unsigned int stackSize
)
1006 wxCriticalSectionLocker
lock(m_critsect
);
1008 if ( !m_internal
->Create(this, stackSize
) )
1009 return wxTHREAD_NO_RESOURCE
;
1011 return wxTHREAD_NO_ERROR
;
1014 wxThreadError
wxThread::Run()
1016 wxCriticalSectionLocker
lock(m_critsect
);
1018 if ( m_internal
->GetState() != STATE_NEW
)
1020 // actually, it may be almost any state at all, not only STATE_RUNNING
1021 return wxTHREAD_RUNNING
;
1024 // the thread has just been created and is still suspended - let it run
1028 // suspend/resume thread
1029 // ---------------------
1031 wxThreadError
wxThread::Pause()
1033 wxCriticalSectionLocker
lock(m_critsect
);
1035 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1038 wxThreadError
wxThread::Resume()
1040 wxCriticalSectionLocker
lock(m_critsect
);
1042 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1048 wxThread::ExitCode
wxThread::Wait()
1050 // although under Windows we can wait for any thread, it's an error to
1051 // wait for a detached one in wxWin API
1052 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1053 _T("wxThread::Wait(): can't wait for detached thread") );
1055 ExitCode rc
= (ExitCode
)-1;
1057 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1062 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1064 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1067 wxThreadError
wxThread::Kill()
1070 return wxTHREAD_NOT_RUNNING
;
1072 wxThreadError rc
= m_internal
->Kill();
1080 // update the status of the joinable thread
1081 wxCriticalSectionLocker
lock(m_critsect
);
1082 m_internal
->SetState(STATE_EXITED
);
1088 void wxThread::Exit(ExitCode status
)
1098 // update the status of the joinable thread
1099 wxCriticalSectionLocker
lock(m_critsect
);
1100 m_internal
->SetState(STATE_EXITED
);
1103 #ifdef wxUSE_BEGIN_THREAD
1104 _endthreadex((unsigned)status
);
1106 ::ExitThread((DWORD
)status
);
1107 #endif // VC++/!VC++
1109 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1115 void wxThread::SetPriority(unsigned int prio
)
1117 wxCriticalSectionLocker
lock(m_critsect
);
1119 m_internal
->SetPriority(prio
);
1122 unsigned int wxThread::GetPriority() const
1124 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1126 return m_internal
->GetPriority();
1129 unsigned long wxThread::GetId() const
1131 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1133 return (unsigned long)m_internal
->GetId();
1136 bool wxThread::IsRunning() const
1138 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1140 return m_internal
->GetState() == STATE_RUNNING
;
1143 bool wxThread::IsAlive() const
1145 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1147 return (m_internal
->GetState() == STATE_RUNNING
) ||
1148 (m_internal
->GetState() == STATE_PAUSED
);
1151 bool wxThread::IsPaused() const
1153 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1155 return m_internal
->GetState() == STATE_PAUSED
;
1158 bool wxThread::TestDestroy()
1160 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1162 return m_internal
->GetState() == STATE_CANCELED
;
1165 // ----------------------------------------------------------------------------
1166 // Automatic initialization for thread module
1167 // ----------------------------------------------------------------------------
1169 class wxThreadModule
: public wxModule
1172 virtual bool OnInit();
1173 virtual void OnExit();
1176 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1179 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1181 bool wxThreadModule::OnInit()
1183 // allocate TLS index for storing the pointer to the current thread
1184 gs_tlsThisThread
= ::TlsAlloc();
1185 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1187 // in normal circumstances it will only happen if all other
1188 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1189 // words, this should never happen
1190 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1195 // main thread doesn't have associated wxThread object, so store 0 in the
1197 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1199 ::TlsFree(gs_tlsThisThread
);
1200 gs_tlsThisThread
= 0xFFFFFFFF;
1202 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1207 gs_critsectWaitingForGui
= new wxCriticalSection();
1209 gs_critsectGui
= new wxCriticalSection();
1210 gs_critsectGui
->Enter();
1212 gs_critsectThreadDelete
= new wxCriticalSection
;
1214 // no error return for GetCurrentThreadId()
1215 gs_idMainThread
= ::GetCurrentThreadId();
1220 void wxThreadModule::OnExit()
1222 if ( !::TlsFree(gs_tlsThisThread
) )
1224 wxLogLastError(wxT("TlsFree failed."));
1227 delete gs_critsectThreadDelete
;
1228 gs_critsectThreadDelete
= NULL
;
1230 if ( gs_critsectGui
)
1232 gs_critsectGui
->Leave();
1233 delete gs_critsectGui
;
1234 gs_critsectGui
= NULL
;
1237 delete gs_critsectWaitingForGui
;
1238 gs_critsectWaitingForGui
= NULL
;
1241 // ----------------------------------------------------------------------------
1242 // under Windows, these functions are implemented using a critical section and
1243 // not a mutex, so the names are a bit confusing
1244 // ----------------------------------------------------------------------------
1246 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1248 // this would dead lock everything...
1249 wxASSERT_MSG( !wxThread::IsMain(),
1250 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1252 // the order in which we enter the critical sections here is crucial!!
1254 // set the flag telling to the main thread that we want to do some GUI
1256 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1258 gs_nWaitingForGui
++;
1261 wxWakeUpMainThread();
1263 // now we may block here because the main thread will soon let us in
1264 // (during the next iteration of OnIdle())
1265 gs_critsectGui
->Enter();
1268 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1270 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1272 if ( wxThread::IsMain() )
1274 gs_bGuiOwnedByMainThread
= false;
1278 // decrement the number of threads waiting for GUI access now
1279 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1280 wxT("calling wxMutexGuiLeave() without entering it first?") );
1282 gs_nWaitingForGui
--;
1284 wxWakeUpMainThread();
1287 gs_critsectGui
->Leave();
1290 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1292 wxASSERT_MSG( wxThread::IsMain(),
1293 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1295 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1297 if ( gs_nWaitingForGui
== 0 )
1299 // no threads are waiting for GUI - so we may acquire the lock without
1300 // any danger (but only if we don't already have it)
1301 if ( !wxGuiOwnedByMainThread() )
1303 gs_critsectGui
->Enter();
1305 gs_bGuiOwnedByMainThread
= true;
1307 //else: already have it, nothing to do
1311 // some threads are waiting, release the GUI lock if we have it
1312 if ( wxGuiOwnedByMainThread() )
1316 //else: some other worker thread is doing GUI
1320 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1322 return gs_bGuiOwnedByMainThread
;
1325 // wake up the main thread if it's in ::GetMessage()
1326 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1328 // sending any message would do - hopefully WM_NULL is harmless enough
1329 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1331 // should never happen
1332 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1336 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1338 return gs_waitingForThread
;
1341 // ----------------------------------------------------------------------------
1342 // include common implementation code
1343 // ----------------------------------------------------------------------------
1345 #include "wx/thrimpl.cpp"
1347 #endif // wxUSE_THREADS