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 :-)
7 // Copyright: (c) Wolfram Gloger (1996, 1997), Guilhem Lavaux (1998);
8 // Vadim Zeitlin (1999-2002)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ----------------------------------------------------------------------------
14 // ----------------------------------------------------------------------------
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
19 #if defined(__BORLANDC__)
25 #include "wx/thread.h"
30 #include "wx/module.h"
33 #include "wx/apptrait.h"
34 #include "wx/scopeguard.h"
36 #include "wx/msw/private.h"
37 #include "wx/msw/missing.h"
38 #include "wx/msw/seh.h"
40 #include "wx/except.h"
42 #include "wx/dynlib.h"
44 // must have this symbol defined to get _beginthread/_endthread declarations
49 #if defined(__BORLANDC__)
51 // I can't set -tWM in the IDE (anyone?) so have to do this
55 #if !defined(__MFC_COMPAT__)
56 // Needed to know about _beginthreadex etc..
57 #define __MFC_COMPAT__
61 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
62 // which should be used instead of Win32 ::CreateThread() if possible
63 #if defined(__VISUALC__) || \
64 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
65 (defined(__GNUG__) && defined(__MSVCRT__)) || \
69 #undef wxUSE_BEGIN_THREAD
70 #define wxUSE_BEGIN_THREAD
75 #ifdef wxUSE_BEGIN_THREAD
76 // this is where _beginthreadex() is declared
79 // the return type of the thread function entry point: notice that this
80 // type can't hold a pointer under Win64
81 typedef unsigned THREAD_RETVAL
;
83 // the calling convention of the thread function entry point
84 #define THREAD_CALLCONV __stdcall
86 // the settings for CreateThread()
87 typedef DWORD THREAD_RETVAL
;
88 #define THREAD_CALLCONV WINAPI
91 static const THREAD_RETVAL THREAD_ERROR_EXIT
= (THREAD_RETVAL
)-1;
93 // ----------------------------------------------------------------------------
95 // ----------------------------------------------------------------------------
97 // the possible states of the thread ("=>" shows all possible transitions from
101 STATE_NEW
, // didn't start execution yet (=> RUNNING)
102 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
103 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
104 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
105 STATE_EXITED
// thread is terminating
108 // ----------------------------------------------------------------------------
109 // this module globals
110 // ----------------------------------------------------------------------------
112 // TLS index of the slot where we store the pointer to the current thread
113 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
115 // id of the main thread - the one which can call GUI functions without first
116 // calling wxMutexGuiEnter()
117 wxThreadIdType
wxThread::ms_idMainThread
= 0;
119 // if it's false, some secondary thread is holding the GUI lock
120 static bool gs_bGuiOwnedByMainThread
= true;
122 // critical section which controls access to all GUI functions: any secondary
123 // thread (i.e. except the main one) must enter this crit section before doing
125 static wxCriticalSection
*gs_critsectGui
= NULL
;
127 // critical section which protects gs_nWaitingForGui variable
128 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
130 // critical section which serializes WinThreadStart() and WaitForTerminate()
131 // (this is a potential bottleneck, we use a single crit sect for all threads
132 // in the system, but normally time spent inside it should be quite short)
133 static wxCriticalSection
*gs_critsectThreadDelete
= NULL
;
135 // number of threads waiting for GUI in wxMutexGuiEnter()
136 static size_t gs_nWaitingForGui
= 0;
138 // are we waiting for a thread termination?
139 static bool gs_waitingForThread
= false;
141 // ============================================================================
142 // Windows implementation of thread and related classes
143 // ============================================================================
145 // ----------------------------------------------------------------------------
147 // ----------------------------------------------------------------------------
149 wxCriticalSection::wxCriticalSection( wxCriticalSectionType
WXUNUSED(critSecType
) )
151 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
152 wxCriticalSectionBufferTooSmall
);
154 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
157 wxCriticalSection::~wxCriticalSection()
159 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
162 void wxCriticalSection::Enter()
164 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
167 bool wxCriticalSection::TryEnter()
169 #if wxUSE_DYNLIB_CLASS
171 (WINAPI
*TryEnterCriticalSection_t
)(LPCRITICAL_SECTION lpCriticalSection
);
173 static TryEnterCriticalSection_t
174 pfnTryEnterCriticalSection
= (TryEnterCriticalSection_t
)
175 wxDynamicLibrary(wxT("kernel32.dll")).
176 GetSymbol(wxT("TryEnterCriticalSection"));
178 return pfnTryEnterCriticalSection
179 ? (*pfnTryEnterCriticalSection
)((CRITICAL_SECTION
*)m_buffer
) != 0
186 void wxCriticalSection::Leave()
188 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
191 // ----------------------------------------------------------------------------
193 // ----------------------------------------------------------------------------
195 class wxMutexInternal
198 wxMutexInternal(wxMutexType mutexType
);
201 bool IsOk() const { return m_mutex
!= NULL
; }
203 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
204 wxMutexError
Lock(unsigned long ms
) { return LockTimeout(ms
); }
205 wxMutexError
TryLock();
206 wxMutexError
Unlock();
209 wxMutexError
LockTimeout(DWORD milliseconds
);
213 unsigned long m_owningThread
;
216 wxDECLARE_NO_COPY_CLASS(wxMutexInternal
);
219 // all mutexes are recursive under Win32 so we don't use mutexType
220 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
222 // create a nameless (hence intra process and always private) mutex
223 m_mutex
= ::CreateMutex
225 NULL
, // default secutiry attributes
226 FALSE
, // not initially locked
235 wxLogLastError(wxT("CreateMutex()"));
240 wxMutexInternal::~wxMutexInternal()
244 if ( !::CloseHandle(m_mutex
) )
246 wxLogLastError(wxT("CloseHandle(mutex)"));
251 wxMutexError
wxMutexInternal::TryLock()
253 const wxMutexError rc
= LockTimeout(0);
255 // we have a special return code for timeout in this case
256 return rc
== wxMUTEX_TIMEOUT
? wxMUTEX_BUSY
: rc
;
259 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
261 if (m_type
== wxMUTEX_DEFAULT
)
263 // Don't allow recursive
264 if (m_owningThread
!= 0)
266 if (m_owningThread
== wxThread::GetCurrentId())
267 return wxMUTEX_DEAD_LOCK
;
271 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
275 // the previous caller died without releasing the mutex, so even
276 // though we did get it, log a message about this
277 wxLogDebug(wxT("WaitForSingleObject() returned WAIT_ABANDONED"));
285 return wxMUTEX_TIMEOUT
;
288 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
292 wxLogLastError(wxT("WaitForSingleObject(mutex)"));
293 return wxMUTEX_MISC_ERROR
;
296 if (m_type
== wxMUTEX_DEFAULT
)
298 // required for checking recursiveness
299 m_owningThread
= wxThread::GetCurrentId();
302 return wxMUTEX_NO_ERROR
;
305 wxMutexError
wxMutexInternal::Unlock()
307 // required for checking recursiveness
310 if ( !::ReleaseMutex(m_mutex
) )
312 wxLogLastError(wxT("ReleaseMutex()"));
314 return wxMUTEX_MISC_ERROR
;
317 return wxMUTEX_NO_ERROR
;
320 // --------------------------------------------------------------------------
322 // --------------------------------------------------------------------------
324 // a trivial wrapper around Win32 semaphore
325 class wxSemaphoreInternal
328 wxSemaphoreInternal(int initialcount
, int maxcount
);
329 ~wxSemaphoreInternal();
331 bool IsOk() const { return m_semaphore
!= NULL
; }
333 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
335 wxSemaError
TryWait()
337 wxSemaError rc
= WaitTimeout(0);
338 if ( rc
== wxSEMA_TIMEOUT
)
344 wxSemaError
WaitTimeout(unsigned long milliseconds
);
351 wxDECLARE_NO_COPY_CLASS(wxSemaphoreInternal
);
354 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
356 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
359 // make it practically infinite
363 m_semaphore
= ::CreateSemaphore
365 NULL
, // default security attributes
373 wxLogLastError(wxT("CreateSemaphore()"));
377 wxSemaphoreInternal::~wxSemaphoreInternal()
381 if ( !::CloseHandle(m_semaphore
) )
383 wxLogLastError(wxT("CloseHandle(semaphore)"));
388 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
390 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
395 return wxSEMA_NO_ERROR
;
398 return wxSEMA_TIMEOUT
;
401 wxLogLastError(wxT("WaitForSingleObject(semaphore)"));
404 return wxSEMA_MISC_ERROR
;
407 wxSemaError
wxSemaphoreInternal::Post()
409 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
410 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
412 if ( GetLastError() == ERROR_TOO_MANY_POSTS
)
414 return wxSEMA_OVERFLOW
;
418 wxLogLastError(wxT("ReleaseSemaphore"));
419 return wxSEMA_MISC_ERROR
;
423 return wxSEMA_NO_ERROR
;
425 return wxSEMA_MISC_ERROR
;
429 // ----------------------------------------------------------------------------
430 // wxThread implementation
431 // ----------------------------------------------------------------------------
433 // wxThreadInternal class
434 // ----------------------
436 class wxThreadInternal
439 wxThreadInternal(wxThread
*thread
)
444 m_priority
= wxPRIORITY_DEFAULT
;
457 if ( !::CloseHandle(m_hThread
) )
459 wxLogLastError(wxT("CloseHandle(thread)"));
466 // create a new (suspended) thread (for the given thread object)
467 bool Create(wxThread
*thread
, unsigned int stackSize
);
469 // wait for the thread to terminate, either by itself, or by asking it
470 // (politely, this is not Kill()!) to do it
471 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
472 wxThread::ExitCode
*pRc
,
473 wxThreadWait waitMode
,
474 wxThread
*threadToDelete
= NULL
);
476 // kill the thread unconditionally
477 wxThreadError
Kill();
479 // suspend/resume/terminate
482 void Cancel() { m_state
= STATE_CANCELED
; }
485 void SetState(wxThreadState state
) { m_state
= state
; }
486 wxThreadState
GetState() const { return m_state
; }
489 void SetPriority(unsigned int priority
);
490 unsigned int GetPriority() const { return m_priority
; }
492 // thread handle and id
493 HANDLE
GetHandle() const { return m_hThread
; }
494 DWORD
GetId() const { return m_tid
; }
496 // the thread function forwarding to DoThreadStart
497 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
499 // really start the thread (if it's not already dead)
500 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
502 // call OnExit() on the thread
503 static void DoThreadOnExit(wxThread
*thread
);
508 if ( m_thread
->IsDetached() )
509 ::InterlockedIncrement(&m_nRef
);
514 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
519 // the thread we're associated with
522 HANDLE m_hThread
; // handle of the thread
523 wxThreadState m_state
; // state, see wxThreadState enum
524 unsigned int m_priority
; // thread priority in "wx" units
525 DWORD m_tid
; // thread id
527 // number of threads which need this thread to remain alive, when the count
528 // reaches 0 we kill the owning wxThread -- and die ourselves with it
531 wxDECLARE_NO_COPY_CLASS(wxThreadInternal
);
534 // small class which keeps a thread alive during its lifetime
535 class wxThreadKeepAlive
538 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
539 { m_thrImpl
.KeepAlive(); }
541 { m_thrImpl
.LetDie(); }
544 wxThreadInternal
& m_thrImpl
;
548 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
554 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
558 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
560 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
562 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
566 // store the thread object in the TLS
567 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
569 wxLogSysError(_("Cannot start thread: error writing TLS."));
571 return THREAD_ERROR_EXIT
;
574 rc
= wxPtrToUInt(thread
->CallEntry());
576 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
582 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
584 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
586 wxThread
* const thread
= (wxThread
*)param
;
588 // each thread has its own SEH translator so install our own a.s.a.p.
589 DisableAutomaticSETranslator();
591 // NB: Notice that we can't use wxCriticalSectionLocker in this function as
592 // we use SEH and it's incompatible with C++ object dtors.
594 // first of all, check whether we hadn't been cancelled already and don't
595 // start the user code at all then
596 thread
->m_critsect
.Enter();
597 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
598 thread
->m_critsect
.Leave();
600 // run the thread function itself inside a SEH try/except block
604 DoThreadOnExit(thread
);
606 rc
= DoThreadStart(thread
);
608 wxSEH_HANDLE(THREAD_ERROR_EXIT
)
611 // save IsDetached because thread object can be deleted by joinable
612 // threads after state is changed to STATE_EXITED.
613 const bool isDetached
= thread
->IsDetached();
616 thread
->m_critsect
.Enter();
617 thread
->m_internal
->SetState(STATE_EXITED
);
618 thread
->m_critsect
.Leave();
621 // the thread may delete itself now if it wants, we don't need it any more
623 thread
->m_internal
->LetDie();
628 void wxThreadInternal::SetPriority(unsigned int priority
)
630 m_priority
= priority
;
632 // translate wxWidgets priority to the Windows one
634 if (m_priority
<= 20)
635 win_priority
= THREAD_PRIORITY_LOWEST
;
636 else if (m_priority
<= 40)
637 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
638 else if (m_priority
<= 60)
639 win_priority
= THREAD_PRIORITY_NORMAL
;
640 else if (m_priority
<= 80)
641 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
642 else if (m_priority
<= 100)
643 win_priority
= THREAD_PRIORITY_HIGHEST
;
646 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
647 win_priority
= THREAD_PRIORITY_NORMAL
;
650 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
652 wxLogSysError(_("Can't set thread priority"));
656 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
658 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
659 wxT("Create()ing thread twice?") );
661 // for compilers which have it, we should use C RTL function for thread
662 // creation instead of Win32 API one because otherwise we will have memory
663 // leaks if the thread uses C RTL (and most threads do)
664 #ifdef wxUSE_BEGIN_THREAD
666 // Watcom is reported to not like 0 stack size (which means "use default"
667 // for the other compilers and is also the default value for stackSize)
671 #endif // __WATCOMC__
673 m_hThread
= (HANDLE
)_beginthreadex
675 NULL
, // default security
677 wxThreadInternal::WinThreadStart
, // entry point
680 (unsigned int *)&m_tid
682 #else // compiler doesn't have _beginthreadex
683 m_hThread
= ::CreateThread
685 NULL
, // default security
686 stackSize
, // stack size
687 wxThreadInternal::WinThreadStart
, // thread entry point
688 (LPVOID
)thread
, // parameter
689 CREATE_SUSPENDED
, // flags
690 &m_tid
// [out] thread id
692 #endif // _beginthreadex/CreateThread
694 if ( m_hThread
== NULL
)
696 wxLogSysError(_("Can't create thread"));
701 if ( m_priority
!= wxPRIORITY_DEFAULT
)
703 SetPriority(m_priority
);
709 wxThreadError
wxThreadInternal::Kill()
713 if ( !::TerminateThread(m_hThread
, THREAD_ERROR_EXIT
) )
715 wxLogSysError(_("Couldn't terminate thread"));
717 return wxTHREAD_MISC_ERROR
;
722 return wxTHREAD_NO_ERROR
;
726 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
727 wxThread::ExitCode
*pRc
,
728 wxThreadWait waitMode
,
729 wxThread
*threadToDelete
)
731 // prevent the thread C++ object from disappearing as long as we are using
733 wxThreadKeepAlive
keepAlive(*this);
736 // we may either wait passively for the thread to terminate (when called
737 // from Wait()) or ask it to terminate (when called from Delete())
738 bool shouldDelete
= threadToDelete
!= NULL
;
742 // we might need to resume the thread if it's currently stopped
743 bool shouldResume
= false;
745 // as Delete() (which calls us) is always safe to call we need to consider
746 // all possible states
748 wxCriticalSectionLocker
lock(cs
);
750 if ( m_state
== STATE_NEW
)
754 // WinThreadStart() will see it and terminate immediately, no
755 // need to cancel the thread -- but we still need to resume it
757 m_state
= STATE_EXITED
;
759 // we must call Resume() as the thread hasn't been initially
760 // resumed yet (and as Resume() it knows about STATE_EXITED
761 // special case, it won't touch it and WinThreadStart() will
762 // just exit immediately)
764 shouldDelete
= false;
766 //else: shouldResume is correctly set to false here, wait until
767 // someone else runs the thread and it finishes
769 else // running, paused, cancelled or even exited
771 shouldResume
= m_state
== STATE_PAUSED
;
775 // resume the thread if it is paused
779 // ask the thread to terminate
782 wxCriticalSectionLocker
lock(cs
);
787 if ( threadToDelete
)
788 threadToDelete
->OnDelete();
790 // now wait for thread to finish
791 if ( wxThread::IsMain() )
793 // set flag for wxIsWaitingForThread()
794 gs_waitingForThread
= true;
797 // we can't just wait for the thread to terminate because it might be
798 // calling some GUI functions and so it will never terminate before we
799 // process the Windows messages that result from these functions
800 // (note that even in console applications we might have to process
801 // messages if we use wxExecute() or timers or ...)
802 DWORD result
wxDUMMY_INITIALIZE(0);
805 if ( wxThread::IsMain() )
807 // give the thread we're waiting for chance to do the GUI call
809 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
815 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
818 result
= traits
->WaitForThread(m_hThread
, waitMode
);
820 else // can't wait for the thread
830 wxLogSysError(_("Cannot wait for thread termination"));
832 return wxTHREAD_KILLED
;
835 // thread we're waiting for terminated
838 case WAIT_OBJECT_0
+ 1:
839 // new message arrived, process it -- but only if we're the
840 // main thread as we don't support processing messages in
843 // NB: we still must include QS_ALLINPUT even when waiting
844 // in a secondary thread because if it had created some
845 // window somehow (possible not even using wxWidgets)
846 // the system might dead lock then
847 if ( wxThread::IsMain() )
849 if ( traits
&& !traits
->DoMessageFromThreadWait() )
851 // WM_QUIT received: kill the thread
854 return wxTHREAD_KILLED
;
860 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
862 } while ( result
!= WAIT_OBJECT_0
);
864 if ( wxThread::IsMain() )
866 gs_waitingForThread
= false;
870 // although the thread might be already in the EXITED state it might not
871 // have terminated yet and so we are not sure that it has actually
872 // terminated if the "if" above hadn't been taken
875 if ( !::GetExitCodeThread(m_hThread
, &rc
) )
877 wxLogLastError(wxT("GetExitCodeThread"));
879 rc
= THREAD_ERROR_EXIT
;
884 if ( rc
!= STILL_ACTIVE
)
887 // give the other thread some time to terminate, otherwise we may be
893 *pRc
= wxUIntToPtr(rc
);
895 // we don't need the thread handle any more in any case
899 return rc
== THREAD_ERROR_EXIT
? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
902 bool wxThreadInternal::Suspend()
904 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
905 if ( nSuspendCount
== (DWORD
)-1 )
907 wxLogSysError(_("Cannot suspend thread %lx"),
908 static_cast<unsigned long>(wxPtrToUInt(m_hThread
)));
913 m_state
= STATE_PAUSED
;
918 bool wxThreadInternal::Resume()
920 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
921 if ( nSuspendCount
== (DWORD
)-1 )
923 wxLogSysError(_("Cannot resume thread %lx"),
924 static_cast<unsigned long>(wxPtrToUInt(m_hThread
)));
929 // don't change the state from STATE_EXITED because it's special and means
930 // we are going to terminate without running any user code - if we did it,
931 // the code in WaitForTerminate() wouldn't work
932 if ( m_state
!= STATE_EXITED
)
934 m_state
= STATE_RUNNING
;
943 wxThread
*wxThread::This()
945 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
947 // be careful, 0 may be a valid return value as well
948 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
950 wxLogSysError(_("Couldn't get the current thread pointer"));
958 void wxThread::Yield()
960 // 0 argument to Sleep() is special and means to just give away the rest of
965 int wxThread::GetCPUCount()
970 return si
.dwNumberOfProcessors
;
973 unsigned long wxThread::GetCurrentId()
975 return (unsigned long)::GetCurrentThreadId();
978 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
983 wxASSERT_MSG( IsMain(), wxT("should only be called from the main thread") );
985 // ok only for the default one
989 // get system affinity mask first
990 HANDLE hProcess
= ::GetCurrentProcess();
991 DWORD_PTR dwProcMask
, dwSysMask
;
992 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
994 wxLogLastError(wxT("GetProcessAffinityMask"));
999 // how many CPUs have we got?
1000 if ( dwSysMask
== 1 )
1002 // don't bother with all this complicated stuff - on a single
1003 // processor system it doesn't make much sense anyhow
1007 // calculate the process mask: it's a bit vector with one bit per
1008 // processor; we want to schedule the process to run on first level
1013 if ( dwSysMask
& bit
)
1015 // ok, we can set this bit
1018 // another process added
1021 // and that's enough
1030 // could we set all bits?
1033 wxLogDebug(wxT("bad level %u in wxThread::SetConcurrency()"), level
);
1038 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1039 // exist in Win9x, use RT binding instead
1041 typedef BOOL (WINAPI
*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD_PTR
);
1043 // can use static var because we're always in the main thread here
1044 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1046 if ( !pfnSetProcessAffinityMask
)
1048 HMODULE hModKernel
= ::LoadLibrary(wxT("kernel32"));
1051 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1052 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1055 // we've discovered a MT version of Win9x!
1056 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1057 wxT("this system has several CPUs but no SetProcessAffinityMask function?") );
1060 if ( !pfnSetProcessAffinityMask
)
1062 // msg given above - do it only once
1066 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1068 wxLogLastError(wxT("SetProcessAffinityMask"));
1074 #endif // __WXWINCE__/!__WXWINCE__
1080 wxThread::wxThread(wxThreadKind kind
)
1082 m_internal
= new wxThreadInternal(this);
1084 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1087 wxThread::~wxThread()
1092 // create/start thread
1093 // -------------------
1095 wxThreadError
wxThread::Create(unsigned int stackSize
)
1097 wxCriticalSectionLocker
lock(m_critsect
);
1099 if ( !m_internal
->Create(this, stackSize
) )
1100 return wxTHREAD_NO_RESOURCE
;
1102 return wxTHREAD_NO_ERROR
;
1105 wxThreadError
wxThread::Run()
1107 wxCriticalSectionLocker
lock(m_critsect
);
1109 // Create the thread if it wasn't created yet with an explicit
1111 if ( !m_internal
->GetHandle() )
1113 if ( !m_internal
->Create(this, 0) )
1114 return wxTHREAD_NO_RESOURCE
;
1117 wxCHECK_MSG( m_internal
->GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
1118 wxT("thread may only be started once after Create()") );
1120 // the thread has just been created and is still suspended - let it run
1124 // suspend/resume thread
1125 // ---------------------
1127 wxThreadError
wxThread::Pause()
1129 wxCriticalSectionLocker
lock(m_critsect
);
1131 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1134 wxThreadError
wxThread::Resume()
1136 wxCriticalSectionLocker
lock(m_critsect
);
1138 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1144 wxThread::ExitCode
wxThread::Wait(wxThreadWait waitMode
)
1146 ExitCode rc
= wxUIntToPtr(THREAD_ERROR_EXIT
);
1148 // although under Windows we can wait for any thread, it's an error to
1149 // wait for a detached one in wxWin API
1150 wxCHECK_MSG( !IsDetached(), rc
,
1151 wxT("wxThread::Wait(): can't wait for detached thread") );
1153 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
, waitMode
);
1158 wxThreadError
wxThread::Delete(ExitCode
*pRc
, wxThreadWait waitMode
)
1160 return m_internal
->WaitForTerminate(m_critsect
, pRc
, waitMode
, this);
1163 wxThreadError
wxThread::Kill()
1166 return wxTHREAD_NOT_RUNNING
;
1168 wxThreadError rc
= m_internal
->Kill();
1176 // update the status of the joinable thread
1177 wxCriticalSectionLocker
lock(m_critsect
);
1178 m_internal
->SetState(STATE_EXITED
);
1184 void wxThread::Exit(ExitCode status
)
1186 wxThreadInternal::DoThreadOnExit(this);
1196 // update the status of the joinable thread
1197 wxCriticalSectionLocker
lock(m_critsect
);
1198 m_internal
->SetState(STATE_EXITED
);
1201 #ifdef wxUSE_BEGIN_THREAD
1202 _endthreadex(wxPtrToUInt(status
));
1204 ::ExitThread((DWORD
)status
);
1205 #endif // VC++/!VC++
1207 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1213 void wxThread::SetPriority(unsigned int prio
)
1215 wxCriticalSectionLocker
lock(m_critsect
);
1217 m_internal
->SetPriority(prio
);
1220 unsigned int wxThread::GetPriority() const
1222 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1224 return m_internal
->GetPriority();
1227 unsigned long wxThread::GetId() const
1229 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1231 return (unsigned long)m_internal
->GetId();
1234 bool wxThread::IsRunning() const
1236 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1238 return m_internal
->GetState() == STATE_RUNNING
;
1241 bool wxThread::IsAlive() const
1243 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1245 return (m_internal
->GetState() == STATE_RUNNING
) ||
1246 (m_internal
->GetState() == STATE_PAUSED
);
1249 bool wxThread::IsPaused() const
1251 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1253 return m_internal
->GetState() == STATE_PAUSED
;
1256 bool wxThread::TestDestroy()
1258 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1260 return m_internal
->GetState() == STATE_CANCELED
;
1263 // ----------------------------------------------------------------------------
1264 // Automatic initialization for thread module
1265 // ----------------------------------------------------------------------------
1267 class wxThreadModule
: public wxModule
1270 virtual bool OnInit();
1271 virtual void OnExit();
1274 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1277 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1279 bool wxThreadModule::OnInit()
1281 // allocate TLS index for storing the pointer to the current thread
1282 gs_tlsThisThread
= ::TlsAlloc();
1283 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1285 // in normal circumstances it will only happen if all other
1286 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1287 // words, this should never happen
1288 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1293 // main thread doesn't have associated wxThread object, so store 0 in the
1295 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1297 ::TlsFree(gs_tlsThisThread
);
1298 gs_tlsThisThread
= 0xFFFFFFFF;
1300 wxLogSysError(_("Thread module initialization failed: cannot store value in thread local storage"));
1305 gs_critsectWaitingForGui
= new wxCriticalSection();
1307 gs_critsectGui
= new wxCriticalSection();
1308 gs_critsectGui
->Enter();
1310 gs_critsectThreadDelete
= new wxCriticalSection
;
1312 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1317 void wxThreadModule::OnExit()
1319 if ( !::TlsFree(gs_tlsThisThread
) )
1321 wxLogLastError(wxT("TlsFree failed."));
1324 wxDELETE(gs_critsectThreadDelete
);
1326 if ( gs_critsectGui
)
1328 gs_critsectGui
->Leave();
1329 wxDELETE(gs_critsectGui
);
1332 wxDELETE(gs_critsectWaitingForGui
);
1335 // ----------------------------------------------------------------------------
1336 // under Windows, these functions are implemented using a critical section and
1337 // not a mutex, so the names are a bit confusing
1338 // ----------------------------------------------------------------------------
1340 void wxMutexGuiEnterImpl()
1342 // this would dead lock everything...
1343 wxASSERT_MSG( !wxThread::IsMain(),
1344 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1346 // the order in which we enter the critical sections here is crucial!!
1348 // set the flag telling to the main thread that we want to do some GUI
1350 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1352 gs_nWaitingForGui
++;
1355 wxWakeUpMainThread();
1357 // now we may block here because the main thread will soon let us in
1358 // (during the next iteration of OnIdle())
1359 gs_critsectGui
->Enter();
1362 void wxMutexGuiLeaveImpl()
1364 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1366 if ( wxThread::IsMain() )
1368 gs_bGuiOwnedByMainThread
= false;
1372 // decrement the number of threads waiting for GUI access now
1373 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1374 wxT("calling wxMutexGuiLeave() without entering it first?") );
1376 gs_nWaitingForGui
--;
1378 wxWakeUpMainThread();
1381 gs_critsectGui
->Leave();
1384 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1386 wxASSERT_MSG( wxThread::IsMain(),
1387 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1389 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1391 if ( gs_nWaitingForGui
== 0 )
1393 // no threads are waiting for GUI - so we may acquire the lock without
1394 // any danger (but only if we don't already have it)
1395 if ( !wxGuiOwnedByMainThread() )
1397 gs_critsectGui
->Enter();
1399 gs_bGuiOwnedByMainThread
= true;
1401 //else: already have it, nothing to do
1405 // some threads are waiting, release the GUI lock if we have it
1406 if ( wxGuiOwnedByMainThread() )
1410 //else: some other worker thread is doing GUI
1414 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1416 return gs_bGuiOwnedByMainThread
;
1419 // wake up the main thread if it's in ::GetMessage()
1420 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1422 // sending any message would do - hopefully WM_NULL is harmless enough
1423 if ( !::PostThreadMessage(wxThread::GetMainId(), WM_NULL
, 0, 0) )
1425 // should never happen
1426 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1430 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1432 return gs_waitingForThread
;
1435 // ----------------------------------------------------------------------------
1436 // include common implementation code
1437 // ----------------------------------------------------------------------------
1439 #include "wx/thrimpl.cpp"
1441 #endif // wxUSE_THREADS