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__)
26 #include "wx/thread.h"
31 #include "wx/module.h"
34 #include "wx/apptrait.h"
35 #include "wx/scopeguard.h"
37 #include "wx/msw/private.h"
38 #include "wx/msw/missing.h"
39 #include "wx/msw/seh.h"
41 #include "wx/except.h"
43 // must have this symbol defined to get _beginthread/_endthread declarations
48 #if defined(__BORLANDC__)
50 // I can't set -tWM in the IDE (anyone?) so have to do this
54 #if !defined(__MFC_COMPAT__)
55 // Needed to know about _beginthreadex etc..
56 #define __MFC_COMPAT__
60 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
61 // which should be used instead of Win32 ::CreateThread() if possible
62 #if defined(__VISUALC__) || \
63 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
64 (defined(__GNUG__) && defined(__MSVCRT__)) || \
65 defined(__WATCOMC__) || defined(__MWERKS__)
68 #undef wxUSE_BEGIN_THREAD
69 #define wxUSE_BEGIN_THREAD
74 #ifdef wxUSE_BEGIN_THREAD
75 // this is where _beginthreadex() is declared
78 // the return type of the thread function entry point: notice that this
79 // type can't hold a pointer under Win64
80 typedef unsigned THREAD_RETVAL
;
82 // the calling convention of the thread function entry point
83 #define THREAD_CALLCONV __stdcall
85 // the settings for CreateThread()
86 typedef DWORD THREAD_RETVAL
;
87 #define THREAD_CALLCONV WINAPI
90 static const THREAD_RETVAL THREAD_ERROR_EXIT
= (THREAD_RETVAL
)-1;
92 // ----------------------------------------------------------------------------
94 // ----------------------------------------------------------------------------
96 // the possible states of the thread ("=>" shows all possible transitions from
100 STATE_NEW
, // didn't start execution yet (=> RUNNING)
101 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
102 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
103 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
104 STATE_EXITED
// thread is terminating
107 // ----------------------------------------------------------------------------
108 // this module globals
109 // ----------------------------------------------------------------------------
111 // TLS index of the slot where we store the pointer to the current thread
112 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
114 // id of the main thread - the one which can call GUI functions without first
115 // calling wxMutexGuiEnter()
116 static DWORD gs_idMainThread
= 0;
118 // if it's false, some secondary thread is holding the GUI lock
119 static bool gs_bGuiOwnedByMainThread
= true;
121 // critical section which controls access to all GUI functions: any secondary
122 // thread (i.e. except the main one) must enter this crit section before doing
124 static wxCriticalSection
*gs_critsectGui
= NULL
;
126 // critical section which protects gs_nWaitingForGui variable
127 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
129 // critical section which serializes WinThreadStart() and WaitForTerminate()
130 // (this is a potential bottleneck, we use a single crit sect for all threads
131 // in the system, but normally time spent inside it should be quite short)
132 static wxCriticalSection
*gs_critsectThreadDelete
= NULL
;
134 // number of threads waiting for GUI in wxMutexGuiEnter()
135 static size_t gs_nWaitingForGui
= 0;
137 // are we waiting for a thread termination?
138 static bool gs_waitingForThread
= false;
140 // ============================================================================
141 // Windows implementation of thread and related classes
142 // ============================================================================
144 // ----------------------------------------------------------------------------
146 // ----------------------------------------------------------------------------
148 wxCriticalSection::wxCriticalSection()
150 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
151 wxCriticalSectionBufferTooSmall
);
153 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
156 wxCriticalSection::~wxCriticalSection()
158 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
161 void wxCriticalSection::Enter()
163 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
166 void wxCriticalSection::Leave()
168 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
171 // ----------------------------------------------------------------------------
173 // ----------------------------------------------------------------------------
175 class wxMutexInternal
178 wxMutexInternal(wxMutexType mutexType
);
181 bool IsOk() const { return m_mutex
!= NULL
; }
183 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
184 wxMutexError
Lock(unsigned long ms
) { return LockTimeout(ms
); }
185 wxMutexError
TryLock();
186 wxMutexError
Unlock();
189 wxMutexError
LockTimeout(DWORD milliseconds
);
193 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
196 // all mutexes are recursive under Win32 so we don't use mutexType
197 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
199 // create a nameless (hence intra process and always private) mutex
200 m_mutex
= ::CreateMutex
202 NULL
, // default secutiry attributes
203 FALSE
, // not initially locked
209 wxLogLastError(_T("CreateMutex()"));
213 wxMutexInternal::~wxMutexInternal()
217 if ( !::CloseHandle(m_mutex
) )
219 wxLogLastError(_T("CloseHandle(mutex)"));
224 wxMutexError
wxMutexInternal::TryLock()
226 const wxMutexError rc
= LockTimeout(0);
228 // we have a special return code for timeout in this case
229 return rc
== wxMUTEX_TIMEOUT
? wxMUTEX_BUSY
: rc
;
232 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
234 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
235 if ( rc
== WAIT_ABANDONED
)
237 // the previous caller died without releasing the mutex, but now we can
239 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
241 // use 0 timeout, normally we should always get it
242 rc
= ::WaitForSingleObject(m_mutex
, 0);
252 return wxMUTEX_TIMEOUT
;
254 case WAIT_ABANDONED
: // checked for above
256 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
260 wxLogLastError(_T("WaitForSingleObject(mutex)"));
261 return wxMUTEX_MISC_ERROR
;
264 return wxMUTEX_NO_ERROR
;
267 wxMutexError
wxMutexInternal::Unlock()
269 if ( !::ReleaseMutex(m_mutex
) )
271 wxLogLastError(_T("ReleaseMutex()"));
273 return wxMUTEX_MISC_ERROR
;
276 return wxMUTEX_NO_ERROR
;
279 // --------------------------------------------------------------------------
281 // --------------------------------------------------------------------------
283 // a trivial wrapper around Win32 semaphore
284 class wxSemaphoreInternal
287 wxSemaphoreInternal(int initialcount
, int maxcount
);
288 ~wxSemaphoreInternal();
290 bool IsOk() const { return m_semaphore
!= NULL
; }
292 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
294 wxSemaError
TryWait()
296 wxSemaError rc
= WaitTimeout(0);
297 if ( rc
== wxSEMA_TIMEOUT
)
303 wxSemaError
WaitTimeout(unsigned long milliseconds
);
310 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
313 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
315 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
318 // make it practically infinite
322 m_semaphore
= ::CreateSemaphore
324 NULL
, // default security attributes
332 wxLogLastError(_T("CreateSemaphore()"));
336 wxSemaphoreInternal::~wxSemaphoreInternal()
340 if ( !::CloseHandle(m_semaphore
) )
342 wxLogLastError(_T("CloseHandle(semaphore)"));
347 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
349 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
354 return wxSEMA_NO_ERROR
;
357 return wxSEMA_TIMEOUT
;
360 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
363 return wxSEMA_MISC_ERROR
;
366 wxSemaError
wxSemaphoreInternal::Post()
368 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
369 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
371 if ( GetLastError() == ERROR_TOO_MANY_POSTS
)
373 return wxSEMA_OVERFLOW
;
377 wxLogLastError(_T("ReleaseSemaphore"));
378 return wxSEMA_MISC_ERROR
;
382 return wxSEMA_NO_ERROR
;
384 return wxSEMA_MISC_ERROR
;
388 // ----------------------------------------------------------------------------
389 // wxThread implementation
390 // ----------------------------------------------------------------------------
392 // wxThreadInternal class
393 // ----------------------
395 class wxThreadInternal
398 wxThreadInternal(wxThread
*thread
)
403 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
416 if ( !::CloseHandle(m_hThread
) )
418 wxLogLastError(wxT("CloseHandle(thread)"));
425 // create a new (suspended) thread (for the given thread object)
426 bool Create(wxThread
*thread
, unsigned int stackSize
);
428 // wait for the thread to terminate, either by itself, or by asking it
429 // (politely, this is not Kill()!) to do it
430 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
431 wxThread::ExitCode
*pRc
,
432 wxThread
*threadToDelete
= NULL
);
434 // kill the thread unconditionally
435 wxThreadError
Kill();
437 // suspend/resume/terminate
440 void Cancel() { m_state
= STATE_CANCELED
; }
443 void SetState(wxThreadState state
) { m_state
= state
; }
444 wxThreadState
GetState() const { return m_state
; }
447 void SetPriority(unsigned int priority
);
448 unsigned int GetPriority() const { return m_priority
; }
450 // thread handle and id
451 HANDLE
GetHandle() const { return m_hThread
; }
452 DWORD
GetId() const { return m_tid
; }
454 // the thread function forwarding to DoThreadStart
455 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
457 // really start the thread (if it's not already dead)
458 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
460 // call OnExit() on the thread
461 static void DoThreadOnExit(wxThread
*thread
);
466 if ( m_thread
->IsDetached() )
467 ::InterlockedIncrement(&m_nRef
);
472 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
477 // the thread we're associated with
480 HANDLE m_hThread
; // handle of the thread
481 wxThreadState m_state
; // state, see wxThreadState enum
482 unsigned int m_priority
; // thread priority in "wx" units
483 DWORD m_tid
; // thread id
485 // number of threads which need this thread to remain alive, when the count
486 // reaches 0 we kill the owning wxThread -- and die ourselves with it
489 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
492 // small class which keeps a thread alive during its lifetime
493 class wxThreadKeepAlive
496 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
497 { m_thrImpl
.KeepAlive(); }
499 { m_thrImpl
.LetDie(); }
502 wxThreadInternal
& m_thrImpl
;
506 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
512 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
516 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
518 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
520 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
524 // store the thread object in the TLS
525 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
527 wxLogSysError(_("Can not start thread: error writing TLS."));
529 return THREAD_ERROR_EXIT
;
532 rc
= wxPtrToUInt(thread
->Entry());
534 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
540 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
542 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
544 wxThread
* const thread
= (wxThread
*)param
;
546 // each thread has its own SEH translator so install our own a.s.a.p.
547 DisableAutomaticSETranslator();
549 // first of all, check whether we hadn't been cancelled already and don't
550 // start the user code at all then
551 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
553 // run the thread function itself inside a SEH try/except block
557 DoThreadOnExit(thread
);
559 rc
= DoThreadStart(thread
);
561 wxSEH_HANDLE(THREAD_ERROR_EXIT
)
564 // save IsDetached because thread object can be deleted by joinable
565 // threads after state is changed to STATE_EXITED.
566 const bool isDetached
= thread
->IsDetached();
569 // enter m_critsect before changing the thread state
571 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
572 // incompatible with C++ object dtors
573 thread
->m_critsect
.Enter();
574 thread
->m_internal
->SetState(STATE_EXITED
);
575 thread
->m_critsect
.Leave();
578 // the thread may delete itself now if it wants, we don't need it any more
580 thread
->m_internal
->LetDie();
585 void wxThreadInternal::SetPriority(unsigned int priority
)
587 m_priority
= priority
;
589 // translate wxWidgets priority to the Windows one
591 if (m_priority
<= 20)
592 win_priority
= THREAD_PRIORITY_LOWEST
;
593 else if (m_priority
<= 40)
594 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
595 else if (m_priority
<= 60)
596 win_priority
= THREAD_PRIORITY_NORMAL
;
597 else if (m_priority
<= 80)
598 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
599 else if (m_priority
<= 100)
600 win_priority
= THREAD_PRIORITY_HIGHEST
;
603 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
604 win_priority
= THREAD_PRIORITY_NORMAL
;
607 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
609 wxLogSysError(_("Can't set thread priority"));
613 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
615 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
616 _T("Create()ing thread twice?") );
618 // for compilers which have it, we should use C RTL function for thread
619 // creation instead of Win32 API one because otherwise we will have memory
620 // leaks if the thread uses C RTL (and most threads do)
621 #ifdef wxUSE_BEGIN_THREAD
623 // Watcom is reported to not like 0 stack size (which means "use default"
624 // for the other compilers and is also the default value for stackSize)
628 #endif // __WATCOMC__
630 m_hThread
= (HANDLE
)_beginthreadex
632 NULL
, // default security
634 wxThreadInternal::WinThreadStart
, // entry point
637 (unsigned int *)&m_tid
639 #else // compiler doesn't have _beginthreadex
640 m_hThread
= ::CreateThread
642 NULL
, // default security
643 stackSize
, // stack size
644 wxThreadInternal::WinThreadStart
, // thread entry point
645 (LPVOID
)thread
, // parameter
646 CREATE_SUSPENDED
, // flags
647 &m_tid
// [out] thread id
649 #endif // _beginthreadex/CreateThread
651 if ( m_hThread
== NULL
)
653 wxLogSysError(_("Can't create thread"));
658 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
660 SetPriority(m_priority
);
666 wxThreadError
wxThreadInternal::Kill()
668 if ( !::TerminateThread(m_hThread
, THREAD_ERROR_EXIT
) )
670 wxLogSysError(_("Couldn't terminate thread"));
672 return wxTHREAD_MISC_ERROR
;
677 return wxTHREAD_NO_ERROR
;
681 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
682 wxThread::ExitCode
*pRc
,
683 wxThread
*threadToDelete
)
685 // prevent the thread C++ object from disappearing as long as we are using
687 wxThreadKeepAlive
keepAlive(*this);
690 // we may either wait passively for the thread to terminate (when called
691 // from Wait()) or ask it to terminate (when called from Delete())
692 bool shouldDelete
= threadToDelete
!= NULL
;
696 // we might need to resume the thread if it's currently stopped
697 bool shouldResume
= false;
699 // as Delete() (which calls us) is always safe to call we need to consider
700 // all possible states
702 wxCriticalSectionLocker
lock(cs
);
704 if ( m_state
== STATE_NEW
)
708 // WinThreadStart() will see it and terminate immediately, no
709 // need to cancel the thread -- but we still need to resume it
711 m_state
= STATE_EXITED
;
713 // we must call Resume() as the thread hasn't been initially
714 // resumed yet (and as Resume() it knows about STATE_EXITED
715 // special case, it won't touch it and WinThreadStart() will
716 // just exit immediately)
718 shouldDelete
= false;
720 //else: shouldResume is correctly set to false here, wait until
721 // someone else runs the thread and it finishes
723 else // running, paused, cancelled or even exited
725 shouldResume
= m_state
== STATE_PAUSED
;
729 // resume the thread if it is paused
733 // ask the thread to terminate
736 wxCriticalSectionLocker
lock(cs
);
742 // now wait for thread to finish
743 if ( wxThread::IsMain() )
745 // set flag for wxIsWaitingForThread()
746 gs_waitingForThread
= true;
749 // we can't just wait for the thread to terminate because it might be
750 // calling some GUI functions and so it will never terminate before we
751 // process the Windows messages that result from these functions
752 // (note that even in console applications we might have to process
753 // messages if we use wxExecute() or timers or ...)
754 DWORD result
wxDUMMY_INITIALIZE(0);
757 if ( wxThread::IsMain() )
759 // give the thread we're waiting for chance to do the GUI call
761 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
767 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
770 result
= traits
->WaitForThread(m_hThread
);
772 else // can't wait for the thread
782 wxLogSysError(_("Can not wait for thread termination"));
784 return wxTHREAD_KILLED
;
787 // thread we're waiting for terminated
790 case WAIT_OBJECT_0
+ 1:
791 // new message arrived, process it -- but only if we're the
792 // main thread as we don't support processing messages in
795 // NB: we still must include QS_ALLINPUT even when waiting
796 // in a secondary thread because if it had created some
797 // window somehow (possible not even using wxWidgets)
798 // the system might dead lock then
799 if ( wxThread::IsMain() )
801 if ( traits
&& !traits
->DoMessageFromThreadWait() )
803 // WM_QUIT received: kill the thread
806 return wxTHREAD_KILLED
;
812 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
814 } while ( result
!= WAIT_OBJECT_0
);
816 if ( wxThread::IsMain() )
818 gs_waitingForThread
= false;
822 // although the thread might be already in the EXITED state it might not
823 // have terminated yet and so we are not sure that it has actually
824 // terminated if the "if" above hadn't been taken
827 if ( !::GetExitCodeThread(m_hThread
, &rc
) )
829 wxLogLastError(wxT("GetExitCodeThread"));
831 rc
= THREAD_ERROR_EXIT
;
836 if ( rc
!= STILL_ACTIVE
)
839 // give the other thread some time to terminate, otherwise we may be
845 *pRc
= wxUIntToPtr(rc
);
847 // we don't need the thread handle any more in any case
851 return rc
== THREAD_ERROR_EXIT
? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
854 bool wxThreadInternal::Suspend()
856 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
857 if ( nSuspendCount
== (DWORD
)-1 )
859 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
864 m_state
= STATE_PAUSED
;
869 bool wxThreadInternal::Resume()
871 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
872 if ( nSuspendCount
== (DWORD
)-1 )
874 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
879 // don't change the state from STATE_EXITED because it's special and means
880 // we are going to terminate without running any user code - if we did it,
881 // the code in WaitForTerminate() wouldn't work
882 if ( m_state
!= STATE_EXITED
)
884 m_state
= STATE_RUNNING
;
893 wxThread
*wxThread::This()
895 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
897 // be careful, 0 may be a valid return value as well
898 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
900 wxLogSysError(_("Couldn't get the current thread pointer"));
908 bool wxThread::IsMain()
910 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
913 void wxThread::Yield()
915 // 0 argument to Sleep() is special and means to just give away the rest of
920 int wxThread::GetCPUCount()
925 return si
.dwNumberOfProcessors
;
928 unsigned long wxThread::GetCurrentId()
930 return (unsigned long)::GetCurrentThreadId();
933 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
938 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
940 // ok only for the default one
944 // get system affinity mask first
945 HANDLE hProcess
= ::GetCurrentProcess();
946 DWORD_PTR dwProcMask
, dwSysMask
;
947 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
949 wxLogLastError(_T("GetProcessAffinityMask"));
954 // how many CPUs have we got?
955 if ( dwSysMask
== 1 )
957 // don't bother with all this complicated stuff - on a single
958 // processor system it doesn't make much sense anyhow
962 // calculate the process mask: it's a bit vector with one bit per
963 // processor; we want to schedule the process to run on first level
968 if ( dwSysMask
& bit
)
970 // ok, we can set this bit
973 // another process added
985 // could we set all bits?
988 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
993 // set it: we can't link to SetProcessAffinityMask() because it doesn't
994 // exist in Win9x, use RT binding instead
996 typedef BOOL (WINAPI
*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD_PTR
);
998 // can use static var because we're always in the main thread here
999 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1001 if ( !pfnSetProcessAffinityMask
)
1003 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
1006 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1007 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1010 // we've discovered a MT version of Win9x!
1011 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1012 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1015 if ( !pfnSetProcessAffinityMask
)
1017 // msg given above - do it only once
1021 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1023 wxLogLastError(_T("SetProcessAffinityMask"));
1029 #endif // __WXWINCE__/!__WXWINCE__
1035 wxThread::wxThread(wxThreadKind kind
)
1037 m_internal
= new wxThreadInternal(this);
1039 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1042 wxThread::~wxThread()
1047 // create/start thread
1048 // -------------------
1050 wxThreadError
wxThread::Create(unsigned int stackSize
)
1052 wxCriticalSectionLocker
lock(m_critsect
);
1054 if ( !m_internal
->Create(this, stackSize
) )
1055 return wxTHREAD_NO_RESOURCE
;
1057 return wxTHREAD_NO_ERROR
;
1060 wxThreadError
wxThread::Run()
1062 wxCriticalSectionLocker
lock(m_critsect
);
1064 if ( m_internal
->GetState() != STATE_NEW
)
1066 // actually, it may be almost any state at all, not only STATE_RUNNING
1067 return wxTHREAD_RUNNING
;
1070 // the thread has just been created and is still suspended - let it run
1074 // suspend/resume thread
1075 // ---------------------
1077 wxThreadError
wxThread::Pause()
1079 wxCriticalSectionLocker
lock(m_critsect
);
1081 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1084 wxThreadError
wxThread::Resume()
1086 wxCriticalSectionLocker
lock(m_critsect
);
1088 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1094 wxThread::ExitCode
wxThread::Wait()
1096 ExitCode rc
= wxUIntToPtr(THREAD_ERROR_EXIT
);
1098 // although under Windows we can wait for any thread, it's an error to
1099 // wait for a detached one in wxWin API
1100 wxCHECK_MSG( !IsDetached(), rc
,
1101 _T("wxThread::Wait(): can't wait for detached thread") );
1103 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1108 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1110 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1113 wxThreadError
wxThread::Kill()
1116 return wxTHREAD_NOT_RUNNING
;
1118 wxThreadError rc
= m_internal
->Kill();
1126 // update the status of the joinable thread
1127 wxCriticalSectionLocker
lock(m_critsect
);
1128 m_internal
->SetState(STATE_EXITED
);
1134 void wxThread::Exit(ExitCode status
)
1144 // update the status of the joinable thread
1145 wxCriticalSectionLocker
lock(m_critsect
);
1146 m_internal
->SetState(STATE_EXITED
);
1149 #ifdef wxUSE_BEGIN_THREAD
1150 _endthreadex(wxPtrToUInt(status
));
1152 ::ExitThread((DWORD
)status
);
1153 #endif // VC++/!VC++
1155 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1161 void wxThread::SetPriority(unsigned int prio
)
1163 wxCriticalSectionLocker
lock(m_critsect
);
1165 m_internal
->SetPriority(prio
);
1168 unsigned int wxThread::GetPriority() const
1170 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1172 return m_internal
->GetPriority();
1175 unsigned long wxThread::GetId() const
1177 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1179 return (unsigned long)m_internal
->GetId();
1182 bool wxThread::IsRunning() const
1184 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1186 return m_internal
->GetState() == STATE_RUNNING
;
1189 bool wxThread::IsAlive() const
1191 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1193 return (m_internal
->GetState() == STATE_RUNNING
) ||
1194 (m_internal
->GetState() == STATE_PAUSED
);
1197 bool wxThread::IsPaused() const
1199 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1201 return m_internal
->GetState() == STATE_PAUSED
;
1204 bool wxThread::TestDestroy()
1206 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1208 return m_internal
->GetState() == STATE_CANCELED
;
1211 // ----------------------------------------------------------------------------
1212 // Automatic initialization for thread module
1213 // ----------------------------------------------------------------------------
1215 class wxThreadModule
: public wxModule
1218 virtual bool OnInit();
1219 virtual void OnExit();
1222 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1225 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1227 bool wxThreadModule::OnInit()
1229 // allocate TLS index for storing the pointer to the current thread
1230 gs_tlsThisThread
= ::TlsAlloc();
1231 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1233 // in normal circumstances it will only happen if all other
1234 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1235 // words, this should never happen
1236 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1241 // main thread doesn't have associated wxThread object, so store 0 in the
1243 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1245 ::TlsFree(gs_tlsThisThread
);
1246 gs_tlsThisThread
= 0xFFFFFFFF;
1248 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1253 gs_critsectWaitingForGui
= new wxCriticalSection();
1255 gs_critsectGui
= new wxCriticalSection();
1256 gs_critsectGui
->Enter();
1258 gs_critsectThreadDelete
= new wxCriticalSection
;
1260 // no error return for GetCurrentThreadId()
1261 gs_idMainThread
= ::GetCurrentThreadId();
1266 void wxThreadModule::OnExit()
1268 if ( !::TlsFree(gs_tlsThisThread
) )
1270 wxLogLastError(wxT("TlsFree failed."));
1273 delete gs_critsectThreadDelete
;
1274 gs_critsectThreadDelete
= NULL
;
1276 if ( gs_critsectGui
)
1278 gs_critsectGui
->Leave();
1279 delete gs_critsectGui
;
1280 gs_critsectGui
= NULL
;
1283 delete gs_critsectWaitingForGui
;
1284 gs_critsectWaitingForGui
= NULL
;
1287 // ----------------------------------------------------------------------------
1288 // under Windows, these functions are implemented using a critical section and
1289 // not a mutex, so the names are a bit confusing
1290 // ----------------------------------------------------------------------------
1292 void wxMutexGuiEnterImpl()
1294 // this would dead lock everything...
1295 wxASSERT_MSG( !wxThread::IsMain(),
1296 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1298 // the order in which we enter the critical sections here is crucial!!
1300 // set the flag telling to the main thread that we want to do some GUI
1302 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1304 gs_nWaitingForGui
++;
1307 wxWakeUpMainThread();
1309 // now we may block here because the main thread will soon let us in
1310 // (during the next iteration of OnIdle())
1311 gs_critsectGui
->Enter();
1314 void wxMutexGuiLeaveImpl()
1316 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1318 if ( wxThread::IsMain() )
1320 gs_bGuiOwnedByMainThread
= false;
1324 // decrement the number of threads waiting for GUI access now
1325 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1326 wxT("calling wxMutexGuiLeave() without entering it first?") );
1328 gs_nWaitingForGui
--;
1330 wxWakeUpMainThread();
1333 gs_critsectGui
->Leave();
1336 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1338 wxASSERT_MSG( wxThread::IsMain(),
1339 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1341 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1343 if ( gs_nWaitingForGui
== 0 )
1345 // no threads are waiting for GUI - so we may acquire the lock without
1346 // any danger (but only if we don't already have it)
1347 if ( !wxGuiOwnedByMainThread() )
1349 gs_critsectGui
->Enter();
1351 gs_bGuiOwnedByMainThread
= true;
1353 //else: already have it, nothing to do
1357 // some threads are waiting, release the GUI lock if we have it
1358 if ( wxGuiOwnedByMainThread() )
1362 //else: some other worker thread is doing GUI
1366 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1368 return gs_bGuiOwnedByMainThread
;
1371 // wake up the main thread if it's in ::GetMessage()
1372 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1374 // sending any message would do - hopefully WM_NULL is harmless enough
1375 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1377 // should never happen
1378 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1382 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1384 return gs_waitingForThread
;
1387 // ----------------------------------------------------------------------------
1388 // include common implementation code
1389 // ----------------------------------------------------------------------------
1391 #include "wx/thrimpl.cpp"
1393 #endif // wxUSE_THREADS