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"
32 #include "wx/scopeguard.h"
34 #include "wx/msw/private.h"
35 #include "wx/msw/missing.h"
36 #include "wx/msw/seh.h"
38 #include "wx/except.h"
39 #include "wx/module.h"
40 #include "wx/thread.h"
42 // must have this symbol defined to get _beginthread/_endthread declarations
47 #if defined(__BORLANDC__)
49 // I can't set -tWM in the IDE (anyone?) so have to do this
53 #if !defined(__MFC_COMPAT__)
54 // Needed to know about _beginthreadex etc..
55 #define __MFC_COMPAT__
59 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
60 // which should be used instead of Win32 ::CreateThread() if possible
61 #if defined(__VISUALC__) || \
62 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
63 (defined(__GNUG__) && defined(__MSVCRT__)) || \
64 defined(__WATCOMC__) || defined(__MWERKS__)
67 #undef wxUSE_BEGIN_THREAD
68 #define wxUSE_BEGIN_THREAD
73 #ifdef wxUSE_BEGIN_THREAD
74 // this is where _beginthreadex() is declared
77 // the return type of the thread function entry point
78 typedef unsigned THREAD_RETVAL
;
80 // the calling convention of the thread function entry point
81 #define THREAD_CALLCONV __stdcall
83 // the settings for CreateThread()
84 typedef DWORD THREAD_RETVAL
;
85 #define THREAD_CALLCONV WINAPI
88 // ----------------------------------------------------------------------------
90 // ----------------------------------------------------------------------------
92 // the possible states of the thread ("=>" shows all possible transitions from
96 STATE_NEW
, // didn't start execution yet (=> RUNNING)
97 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
98 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
99 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
100 STATE_EXITED
// thread is terminating
103 // ----------------------------------------------------------------------------
104 // this module globals
105 // ----------------------------------------------------------------------------
107 // TLS index of the slot where we store the pointer to the current thread
108 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
110 // id of the main thread - the one which can call GUI functions without first
111 // calling wxMutexGuiEnter()
112 static DWORD gs_idMainThread
= 0;
114 // if it's false, some secondary thread is holding the GUI lock
115 static bool gs_bGuiOwnedByMainThread
= true;
117 // critical section which controls access to all GUI functions: any secondary
118 // thread (i.e. except the main one) must enter this crit section before doing
120 static wxCriticalSection
*gs_critsectGui
= NULL
;
122 // critical section which protects gs_nWaitingForGui variable
123 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
125 // critical section which serializes WinThreadStart() and WaitForTerminate()
126 // (this is a potential bottleneck, we use a single crit sect for all threads
127 // in the system, but normally time spent inside it should be quite short)
128 static wxCriticalSection
*gs_critsectThreadDelete
= NULL
;
130 // number of threads waiting for GUI in wxMutexGuiEnter()
131 static size_t gs_nWaitingForGui
= 0;
133 // are we waiting for a thread termination?
134 static bool gs_waitingForThread
= false;
136 // ============================================================================
137 // Windows implementation of thread and related classes
138 // ============================================================================
140 // ----------------------------------------------------------------------------
142 // ----------------------------------------------------------------------------
144 wxCriticalSection::wxCriticalSection()
146 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
147 wxCriticalSectionBufferTooSmall
);
149 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
152 wxCriticalSection::~wxCriticalSection()
154 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
157 void wxCriticalSection::Enter()
159 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
162 void wxCriticalSection::Leave()
164 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
167 // ----------------------------------------------------------------------------
169 // ----------------------------------------------------------------------------
171 class wxMutexInternal
174 wxMutexInternal(wxMutexType mutexType
);
177 bool IsOk() const { return m_mutex
!= NULL
; }
179 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
180 wxMutexError
TryLock() { return LockTimeout(0); }
181 wxMutexError
Unlock();
184 wxMutexError
LockTimeout(DWORD milliseconds
);
188 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
191 // all mutexes are recursive under Win32 so we don't use mutexType
192 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
194 // create a nameless (hence intra process and always private) mutex
195 m_mutex
= ::CreateMutex
197 NULL
, // default secutiry attributes
198 false, // not initially locked
204 wxLogLastError(_T("CreateMutex()"));
208 wxMutexInternal::~wxMutexInternal()
212 if ( !::CloseHandle(m_mutex
) )
214 wxLogLastError(_T("CloseHandle(mutex)"));
219 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
221 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
222 if ( rc
== WAIT_ABANDONED
)
224 // the previous caller died without releasing the mutex, but now we can
226 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
228 // use 0 timeout, normally we should always get it
229 rc
= ::WaitForSingleObject(m_mutex
, 0);
241 case WAIT_ABANDONED
: // checked for above
243 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
247 wxLogLastError(_T("WaitForSingleObject(mutex)"));
248 return wxMUTEX_MISC_ERROR
;
251 return wxMUTEX_NO_ERROR
;
254 wxMutexError
wxMutexInternal::Unlock()
256 if ( !::ReleaseMutex(m_mutex
) )
258 wxLogLastError(_T("ReleaseMutex()"));
260 return wxMUTEX_MISC_ERROR
;
263 return wxMUTEX_NO_ERROR
;
266 // --------------------------------------------------------------------------
268 // --------------------------------------------------------------------------
270 // a trivial wrapper around Win32 semaphore
271 class wxSemaphoreInternal
274 wxSemaphoreInternal(int initialcount
, int maxcount
);
275 ~wxSemaphoreInternal();
277 bool IsOk() const { return m_semaphore
!= NULL
; }
279 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
281 wxSemaError
TryWait()
283 wxSemaError rc
= WaitTimeout(0);
284 if ( rc
== wxSEMA_TIMEOUT
)
290 wxSemaError
WaitTimeout(unsigned long milliseconds
);
297 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
300 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
302 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
305 // make it practically infinite
309 m_semaphore
= ::CreateSemaphore
311 NULL
, // default security attributes
319 wxLogLastError(_T("CreateSemaphore()"));
323 wxSemaphoreInternal::~wxSemaphoreInternal()
327 if ( !::CloseHandle(m_semaphore
) )
329 wxLogLastError(_T("CloseHandle(semaphore)"));
334 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
336 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
341 return wxSEMA_NO_ERROR
;
344 return wxSEMA_TIMEOUT
;
347 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
350 return wxSEMA_MISC_ERROR
;
353 wxSemaError
wxSemaphoreInternal::Post()
355 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
356 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
359 wxLogLastError(_T("ReleaseSemaphore"));
361 return wxSEMA_MISC_ERROR
;
364 return wxSEMA_NO_ERROR
;
367 // ----------------------------------------------------------------------------
368 // wxThread implementation
369 // ----------------------------------------------------------------------------
371 // wxThreadInternal class
372 // ----------------------
374 class wxThreadInternal
377 wxThreadInternal(wxThread
*thread
)
382 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
395 if ( !::CloseHandle(m_hThread
) )
397 wxLogLastError(wxT("CloseHandle(thread)"));
404 // create a new (suspended) thread (for the given thread object)
405 bool Create(wxThread
*thread
, unsigned int stackSize
);
407 // wait for the thread to terminate, either by itself, or by asking it
408 // (politely, this is not Kill()!) to do it
409 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
410 wxThread::ExitCode
*pRc
,
411 wxThread
*threadToDelete
= NULL
);
413 // kill the thread unconditionally
414 wxThreadError
Kill();
416 // suspend/resume/terminate
419 void Cancel() { m_state
= STATE_CANCELED
; }
422 void SetState(wxThreadState state
) { m_state
= state
; }
423 wxThreadState
GetState() const { return m_state
; }
426 void SetPriority(unsigned int priority
);
427 unsigned int GetPriority() const { return m_priority
; }
429 // thread handle and id
430 HANDLE
GetHandle() const { return m_hThread
; }
431 DWORD
GetId() const { return m_tid
; }
433 // the thread function forwarding to DoThreadStart
434 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
436 // really start the thread (if it's not already dead)
437 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
439 // call OnExit() on the thread
440 static void DoThreadOnExit(wxThread
*thread
);
445 if ( m_thread
->IsDetached() )
446 ::InterlockedIncrement(&m_nRef
);
451 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
456 // the thread we're associated with
459 HANDLE m_hThread
; // handle of the thread
460 wxThreadState m_state
; // state, see wxThreadState enum
461 unsigned int m_priority
; // thread priority in "wx" units
462 DWORD m_tid
; // thread id
464 // number of threads which need this thread to remain alive, when the count
465 // reaches 0 we kill the owning wxThread -- and die ourselves with it
468 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
471 // small class which keeps a thread alive during its lifetime
472 class wxThreadKeepAlive
475 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
476 { m_thrImpl
.KeepAlive(); }
478 { m_thrImpl
.LetDie(); }
481 wxThreadInternal
& m_thrImpl
;
485 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
491 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
495 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
497 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
499 THREAD_RETVAL rc
= (THREAD_RETVAL
)-1;
503 // store the thread object in the TLS
504 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
506 wxLogSysError(_("Can not start thread: error writing TLS."));
508 return (THREAD_RETVAL
)-1;
511 rc
= (THREAD_RETVAL
)thread
->Entry();
513 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
519 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
521 THREAD_RETVAL rc
= (THREAD_RETVAL
)-1;
523 wxThread
* const thread
= (wxThread
*)param
;
525 // each thread has its own SEH translator so install our own a.s.a.p.
526 DisableAutomaticSETranslator();
528 // first of all, check whether we hadn't been cancelled already and don't
529 // start the user code at all then
530 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
532 // run the thread function itself inside a SEH try/except block
536 DoThreadOnExit(thread
);
538 rc
= DoThreadStart(thread
);
540 wxSEH_HANDLE((THREAD_RETVAL
)-1)
543 // save IsDetached because thread object can be deleted by joinable
544 // threads after state is changed to STATE_EXITED.
545 const bool isDetached
= thread
->IsDetached();
548 // enter m_critsect before changing the thread state
550 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
551 // incompatible with C++ object dtors
552 thread
->m_critsect
.Enter();
553 thread
->m_internal
->SetState(STATE_EXITED
);
554 thread
->m_critsect
.Leave();
557 // the thread may delete itself now if it wants, we don't need it any more
559 thread
->m_internal
->LetDie();
564 void wxThreadInternal::SetPriority(unsigned int priority
)
566 m_priority
= priority
;
568 // translate wxWidgets priority to the Windows one
570 if (m_priority
<= 20)
571 win_priority
= THREAD_PRIORITY_LOWEST
;
572 else if (m_priority
<= 40)
573 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
574 else if (m_priority
<= 60)
575 win_priority
= THREAD_PRIORITY_NORMAL
;
576 else if (m_priority
<= 80)
577 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
578 else if (m_priority
<= 100)
579 win_priority
= THREAD_PRIORITY_HIGHEST
;
582 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
583 win_priority
= THREAD_PRIORITY_NORMAL
;
586 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
588 wxLogSysError(_("Can't set thread priority"));
592 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
594 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
595 _T("Create()ing thread twice?") );
597 // for compilers which have it, we should use C RTL function for thread
598 // creation instead of Win32 API one because otherwise we will have memory
599 // leaks if the thread uses C RTL (and most threads do)
600 #ifdef wxUSE_BEGIN_THREAD
602 // Watcom is reported to not like 0 stack size (which means "use default"
603 // for the other compilers and is also the default value for stackSize)
607 #endif // __WATCOMC__
609 m_hThread
= (HANDLE
)_beginthreadex
611 NULL
, // default security
613 wxThreadInternal::WinThreadStart
, // entry point
616 (unsigned int *)&m_tid
618 #else // compiler doesn't have _beginthreadex
619 m_hThread
= ::CreateThread
621 NULL
, // default security
622 stackSize
, // stack size
623 wxThreadInternal::WinThreadStart
, // thread entry point
624 (LPVOID
)thread
, // parameter
625 CREATE_SUSPENDED
, // flags
626 &m_tid
// [out] thread id
628 #endif // _beginthreadex/CreateThread
630 if ( m_hThread
== NULL
)
632 wxLogSysError(_("Can't create thread"));
637 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
639 SetPriority(m_priority
);
645 wxThreadError
wxThreadInternal::Kill()
647 if ( !::TerminateThread(m_hThread
, (DWORD
)-1) )
649 wxLogSysError(_("Couldn't terminate thread"));
651 return wxTHREAD_MISC_ERROR
;
656 return wxTHREAD_NO_ERROR
;
660 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
661 wxThread::ExitCode
*pRc
,
662 wxThread
*threadToDelete
)
664 // prevent the thread C++ object from disappearing as long as we are using
666 wxThreadKeepAlive
keepAlive(*this);
669 // we may either wait passively for the thread to terminate (when called
670 // from Wait()) or ask it to terminate (when called from Delete())
671 bool shouldDelete
= threadToDelete
!= NULL
;
673 wxThread::ExitCode rc
= 0;
675 // we might need to resume the thread if it's currently stopped
676 bool shouldResume
= false;
678 // as Delete() (which calls us) is always safe to call we need to consider
679 // all possible states
681 wxCriticalSectionLocker
lock(cs
);
683 if ( m_state
== STATE_NEW
)
687 // WinThreadStart() will see it and terminate immediately, no
688 // need to cancel the thread -- but we still need to resume it
690 m_state
= STATE_EXITED
;
692 // we must call Resume() as the thread hasn't been initially
693 // resumed yet (and as Resume() it knows about STATE_EXITED
694 // special case, it won't touch it and WinThreadStart() will
695 // just exit immediately)
697 shouldDelete
= false;
699 //else: shouldResume is correctly set to false here, wait until
700 // someone else runs the thread and it finishes
702 else // running, paused, cancelled or even exited
704 shouldResume
= m_state
== STATE_PAUSED
;
708 // resume the thread if it is paused
712 // ask the thread to terminate
715 wxCriticalSectionLocker
lock(cs
);
721 // now wait for thread to finish
722 if ( wxThread::IsMain() )
724 // set flag for wxIsWaitingForThread()
725 gs_waitingForThread
= true;
728 // we can't just wait for the thread to terminate because it might be
729 // calling some GUI functions and so it will never terminate before we
730 // process the Windows messages that result from these functions
731 // (note that even in console applications we might have to process
732 // messages if we use wxExecute() or timers or ...)
733 DWORD result
wxDUMMY_INITIALIZE(0);
736 if ( wxThread::IsMain() )
738 // give the thread we're waiting for chance to do the GUI call
740 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
746 #if !defined(QS_ALLPOSTMESSAGE)
747 #define QS_ALLPOSTMESSAGE 0
750 result
= ::MsgWaitForMultipleObjects
752 1, // number of objects to wait for
753 &m_hThread
, // the objects
754 false, // don't wait for all objects
755 INFINITE
, // no timeout
756 QS_ALLINPUT
|QS_ALLPOSTMESSAGE
// return as soon as there are any events
763 wxLogSysError(_("Can not wait for thread termination"));
765 return wxTHREAD_KILLED
;
768 // thread we're waiting for terminated
771 case WAIT_OBJECT_0
+ 1:
772 // new message arrived, process it -- but only if we're the
773 // main thread as we don't support processing messages in
776 // NB: we still must include QS_ALLINPUT even when waiting
777 // in a secondary thread because if it had created some
778 // window somehow (possible not even using wxWidgets)
779 // the system might dead lock then
780 if ( wxThread::IsMain() )
782 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
785 if ( traits
&& !traits
->DoMessageFromThreadWait() )
787 // WM_QUIT received: kill the thread
790 return wxTHREAD_KILLED
;
796 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
798 } while ( result
!= WAIT_OBJECT_0
);
800 if ( wxThread::IsMain() )
802 gs_waitingForThread
= false;
806 // although the thread might be already in the EXITED state it might not
807 // have terminated yet and so we are not sure that it has actually
808 // terminated if the "if" above hadn't been taken
811 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
813 wxLogLastError(wxT("GetExitCodeThread"));
815 rc
= (wxThread::ExitCode
)-1;
820 if ( (DWORD
)rc
!= STILL_ACTIVE
)
823 // give the other thread some time to terminate, otherwise we may be
831 // we don't need the thread handle any more in any case
835 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
839 bool wxThreadInternal::Suspend()
841 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
842 if ( nSuspendCount
== (DWORD
)-1 )
844 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
849 m_state
= STATE_PAUSED
;
854 bool wxThreadInternal::Resume()
856 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
857 if ( nSuspendCount
== (DWORD
)-1 )
859 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
864 // don't change the state from STATE_EXITED because it's special and means
865 // we are going to terminate without running any user code - if we did it,
866 // the code in WaitForTerminate() wouldn't work
867 if ( m_state
!= STATE_EXITED
)
869 m_state
= STATE_RUNNING
;
878 wxThread
*wxThread::This()
880 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
882 // be careful, 0 may be a valid return value as well
883 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
885 wxLogSysError(_("Couldn't get the current thread pointer"));
893 bool wxThread::IsMain()
895 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
898 void wxThread::Yield()
900 // 0 argument to Sleep() is special and means to just give away the rest of
905 void wxThread::Sleep(unsigned long milliseconds
)
907 ::Sleep(milliseconds
);
910 int wxThread::GetCPUCount()
915 return si
.dwNumberOfProcessors
;
918 unsigned long wxThread::GetCurrentId()
920 return (unsigned long)::GetCurrentThreadId();
923 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
928 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
930 // ok only for the default one
934 // get system affinity mask first
935 HANDLE hProcess
= ::GetCurrentProcess();
936 DWORD_PTR dwProcMask
, dwSysMask
;
937 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
939 wxLogLastError(_T("GetProcessAffinityMask"));
944 // how many CPUs have we got?
945 if ( dwSysMask
== 1 )
947 // don't bother with all this complicated stuff - on a single
948 // processor system it doesn't make much sense anyhow
952 // calculate the process mask: it's a bit vector with one bit per
953 // processor; we want to schedule the process to run on first level
958 if ( dwSysMask
& bit
)
960 // ok, we can set this bit
963 // another process added
975 // could we set all bits?
978 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
983 // set it: we can't link to SetProcessAffinityMask() because it doesn't
984 // exist in Win9x, use RT binding instead
986 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
988 // can use static var because we're always in the main thread here
989 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
991 if ( !pfnSetProcessAffinityMask
)
993 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
996 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
997 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1000 // we've discovered a MT version of Win9x!
1001 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1002 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1005 if ( !pfnSetProcessAffinityMask
)
1007 // msg given above - do it only once
1011 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1013 wxLogLastError(_T("SetProcessAffinityMask"));
1019 #endif // __WXWINCE__/!__WXWINCE__
1025 wxThread::wxThread(wxThreadKind kind
)
1027 m_internal
= new wxThreadInternal(this);
1029 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1032 wxThread::~wxThread()
1037 // create/start thread
1038 // -------------------
1040 wxThreadError
wxThread::Create(unsigned int stackSize
)
1042 wxCriticalSectionLocker
lock(m_critsect
);
1044 if ( !m_internal
->Create(this, stackSize
) )
1045 return wxTHREAD_NO_RESOURCE
;
1047 return wxTHREAD_NO_ERROR
;
1050 wxThreadError
wxThread::Run()
1052 wxCriticalSectionLocker
lock(m_critsect
);
1054 if ( m_internal
->GetState() != STATE_NEW
)
1056 // actually, it may be almost any state at all, not only STATE_RUNNING
1057 return wxTHREAD_RUNNING
;
1060 // the thread has just been created and is still suspended - let it run
1064 // suspend/resume thread
1065 // ---------------------
1067 wxThreadError
wxThread::Pause()
1069 wxCriticalSectionLocker
lock(m_critsect
);
1071 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1074 wxThreadError
wxThread::Resume()
1076 wxCriticalSectionLocker
lock(m_critsect
);
1078 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1084 wxThread::ExitCode
wxThread::Wait()
1086 // although under Windows we can wait for any thread, it's an error to
1087 // wait for a detached one in wxWin API
1088 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1089 _T("wxThread::Wait(): can't wait for detached thread") );
1091 ExitCode rc
= (ExitCode
)-1;
1093 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1098 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1100 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1103 wxThreadError
wxThread::Kill()
1106 return wxTHREAD_NOT_RUNNING
;
1108 wxThreadError rc
= m_internal
->Kill();
1116 // update the status of the joinable thread
1117 wxCriticalSectionLocker
lock(m_critsect
);
1118 m_internal
->SetState(STATE_EXITED
);
1124 void wxThread::Exit(ExitCode status
)
1134 // update the status of the joinable thread
1135 wxCriticalSectionLocker
lock(m_critsect
);
1136 m_internal
->SetState(STATE_EXITED
);
1139 #ifdef wxUSE_BEGIN_THREAD
1140 _endthreadex((unsigned)status
);
1142 ::ExitThread((DWORD
)status
);
1143 #endif // VC++/!VC++
1145 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1151 void wxThread::SetPriority(unsigned int prio
)
1153 wxCriticalSectionLocker
lock(m_critsect
);
1155 m_internal
->SetPriority(prio
);
1158 unsigned int wxThread::GetPriority() const
1160 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1162 return m_internal
->GetPriority();
1165 unsigned long wxThread::GetId() const
1167 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1169 return (unsigned long)m_internal
->GetId();
1172 bool wxThread::IsRunning() const
1174 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1176 return m_internal
->GetState() == STATE_RUNNING
;
1179 bool wxThread::IsAlive() const
1181 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1183 return (m_internal
->GetState() == STATE_RUNNING
) ||
1184 (m_internal
->GetState() == STATE_PAUSED
);
1187 bool wxThread::IsPaused() const
1189 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1191 return m_internal
->GetState() == STATE_PAUSED
;
1194 bool wxThread::TestDestroy()
1196 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1198 return m_internal
->GetState() == STATE_CANCELED
;
1201 // ----------------------------------------------------------------------------
1202 // Automatic initialization for thread module
1203 // ----------------------------------------------------------------------------
1205 class wxThreadModule
: public wxModule
1208 virtual bool OnInit();
1209 virtual void OnExit();
1212 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1215 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1217 bool wxThreadModule::OnInit()
1219 // allocate TLS index for storing the pointer to the current thread
1220 gs_tlsThisThread
= ::TlsAlloc();
1221 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1223 // in normal circumstances it will only happen if all other
1224 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1225 // words, this should never happen
1226 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1231 // main thread doesn't have associated wxThread object, so store 0 in the
1233 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1235 ::TlsFree(gs_tlsThisThread
);
1236 gs_tlsThisThread
= 0xFFFFFFFF;
1238 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1243 gs_critsectWaitingForGui
= new wxCriticalSection();
1245 gs_critsectGui
= new wxCriticalSection();
1246 gs_critsectGui
->Enter();
1248 gs_critsectThreadDelete
= new wxCriticalSection
;
1250 // no error return for GetCurrentThreadId()
1251 gs_idMainThread
= ::GetCurrentThreadId();
1256 void wxThreadModule::OnExit()
1258 if ( !::TlsFree(gs_tlsThisThread
) )
1260 wxLogLastError(wxT("TlsFree failed."));
1263 delete gs_critsectThreadDelete
;
1264 gs_critsectThreadDelete
= NULL
;
1266 if ( gs_critsectGui
)
1268 gs_critsectGui
->Leave();
1269 delete gs_critsectGui
;
1270 gs_critsectGui
= NULL
;
1273 delete gs_critsectWaitingForGui
;
1274 gs_critsectWaitingForGui
= NULL
;
1277 // ----------------------------------------------------------------------------
1278 // under Windows, these functions are implemented using a critical section and
1279 // not a mutex, so the names are a bit confusing
1280 // ----------------------------------------------------------------------------
1282 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1284 // this would dead lock everything...
1285 wxASSERT_MSG( !wxThread::IsMain(),
1286 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1288 // the order in which we enter the critical sections here is crucial!!
1290 // set the flag telling to the main thread that we want to do some GUI
1292 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1294 gs_nWaitingForGui
++;
1297 wxWakeUpMainThread();
1299 // now we may block here because the main thread will soon let us in
1300 // (during the next iteration of OnIdle())
1301 gs_critsectGui
->Enter();
1304 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1306 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1308 if ( wxThread::IsMain() )
1310 gs_bGuiOwnedByMainThread
= false;
1314 // decrement the number of threads waiting for GUI access now
1315 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1316 wxT("calling wxMutexGuiLeave() without entering it first?") );
1318 gs_nWaitingForGui
--;
1320 wxWakeUpMainThread();
1323 gs_critsectGui
->Leave();
1326 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1328 wxASSERT_MSG( wxThread::IsMain(),
1329 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1331 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1333 if ( gs_nWaitingForGui
== 0 )
1335 // no threads are waiting for GUI - so we may acquire the lock without
1336 // any danger (but only if we don't already have it)
1337 if ( !wxGuiOwnedByMainThread() )
1339 gs_critsectGui
->Enter();
1341 gs_bGuiOwnedByMainThread
= true;
1343 //else: already have it, nothing to do
1347 // some threads are waiting, release the GUI lock if we have it
1348 if ( wxGuiOwnedByMainThread() )
1352 //else: some other worker thread is doing GUI
1356 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1358 return gs_bGuiOwnedByMainThread
;
1361 // wake up the main thread if it's in ::GetMessage()
1362 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1364 // sending any message would do - hopefully WM_NULL is harmless enough
1365 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1367 // should never happen
1368 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1372 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1374 return gs_waitingForThread
;
1377 // ----------------------------------------------------------------------------
1378 // include common implementation code
1379 // ----------------------------------------------------------------------------
1381 #include "wx/thrimpl.cpp"
1383 #endif // wxUSE_THREADS