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 wxThreadIdType
wxThread::ms_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( wxCriticalSectionType
WXUNUSED(critSecType
) )
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 unsigned long m_owningThread
;
196 wxDECLARE_NO_COPY_CLASS(wxMutexInternal
);
199 // all mutexes are recursive under Win32 so we don't use mutexType
200 wxMutexInternal::wxMutexInternal(wxMutexType mutexType
)
202 // create a nameless (hence intra process and always private) mutex
203 m_mutex
= ::CreateMutex
205 NULL
, // default secutiry attributes
206 FALSE
, // not initially locked
215 wxLogLastError(wxT("CreateMutex()"));
220 wxMutexInternal::~wxMutexInternal()
224 if ( !::CloseHandle(m_mutex
) )
226 wxLogLastError(wxT("CloseHandle(mutex)"));
231 wxMutexError
wxMutexInternal::TryLock()
233 const wxMutexError rc
= LockTimeout(0);
235 // we have a special return code for timeout in this case
236 return rc
== wxMUTEX_TIMEOUT
? wxMUTEX_BUSY
: rc
;
239 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
241 if (m_type
== wxMUTEX_DEFAULT
)
243 // Don't allow recursive
244 if (m_owningThread
!= 0)
246 if (m_owningThread
== wxThread::GetCurrentId())
247 return wxMUTEX_DEAD_LOCK
;
251 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
255 // the previous caller died without releasing the mutex, so even
256 // though we did get it, log a message about this
257 wxLogDebug(wxT("WaitForSingleObject() returned WAIT_ABANDONED"));
265 return wxMUTEX_TIMEOUT
;
268 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
272 wxLogLastError(wxT("WaitForSingleObject(mutex)"));
273 return wxMUTEX_MISC_ERROR
;
276 if (m_type
== wxMUTEX_DEFAULT
)
278 // required for checking recursiveness
279 m_owningThread
= wxThread::GetCurrentId();
282 return wxMUTEX_NO_ERROR
;
285 wxMutexError
wxMutexInternal::Unlock()
287 // required for checking recursiveness
290 if ( !::ReleaseMutex(m_mutex
) )
292 wxLogLastError(wxT("ReleaseMutex()"));
294 return wxMUTEX_MISC_ERROR
;
297 return wxMUTEX_NO_ERROR
;
300 // --------------------------------------------------------------------------
302 // --------------------------------------------------------------------------
304 // a trivial wrapper around Win32 semaphore
305 class wxSemaphoreInternal
308 wxSemaphoreInternal(int initialcount
, int maxcount
);
309 ~wxSemaphoreInternal();
311 bool IsOk() const { return m_semaphore
!= NULL
; }
313 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
315 wxSemaError
TryWait()
317 wxSemaError rc
= WaitTimeout(0);
318 if ( rc
== wxSEMA_TIMEOUT
)
324 wxSemaError
WaitTimeout(unsigned long milliseconds
);
331 wxDECLARE_NO_COPY_CLASS(wxSemaphoreInternal
);
334 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
336 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
339 // make it practically infinite
343 m_semaphore
= ::CreateSemaphore
345 NULL
, // default security attributes
353 wxLogLastError(wxT("CreateSemaphore()"));
357 wxSemaphoreInternal::~wxSemaphoreInternal()
361 if ( !::CloseHandle(m_semaphore
) )
363 wxLogLastError(wxT("CloseHandle(semaphore)"));
368 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
370 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
375 return wxSEMA_NO_ERROR
;
378 return wxSEMA_TIMEOUT
;
381 wxLogLastError(wxT("WaitForSingleObject(semaphore)"));
384 return wxSEMA_MISC_ERROR
;
387 wxSemaError
wxSemaphoreInternal::Post()
389 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
390 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
392 if ( GetLastError() == ERROR_TOO_MANY_POSTS
)
394 return wxSEMA_OVERFLOW
;
398 wxLogLastError(wxT("ReleaseSemaphore"));
399 return wxSEMA_MISC_ERROR
;
403 return wxSEMA_NO_ERROR
;
405 return wxSEMA_MISC_ERROR
;
409 // ----------------------------------------------------------------------------
410 // wxThread implementation
411 // ----------------------------------------------------------------------------
413 // wxThreadInternal class
414 // ----------------------
416 class wxThreadInternal
419 wxThreadInternal(wxThread
*thread
)
424 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
437 if ( !::CloseHandle(m_hThread
) )
439 wxLogLastError(wxT("CloseHandle(thread)"));
446 // create a new (suspended) thread (for the given thread object)
447 bool Create(wxThread
*thread
, unsigned int stackSize
);
449 // wait for the thread to terminate, either by itself, or by asking it
450 // (politely, this is not Kill()!) to do it
451 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
452 wxThread::ExitCode
*pRc
,
453 wxThreadWait waitMode
,
454 wxThread
*threadToDelete
= NULL
);
456 // kill the thread unconditionally
457 wxThreadError
Kill();
459 // suspend/resume/terminate
462 void Cancel() { m_state
= STATE_CANCELED
; }
465 void SetState(wxThreadState state
) { m_state
= state
; }
466 wxThreadState
GetState() const { return m_state
; }
469 void SetPriority(unsigned int priority
);
470 unsigned int GetPriority() const { return m_priority
; }
472 // thread handle and id
473 HANDLE
GetHandle() const { return m_hThread
; }
474 DWORD
GetId() const { return m_tid
; }
476 // the thread function forwarding to DoThreadStart
477 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
479 // really start the thread (if it's not already dead)
480 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
482 // call OnExit() on the thread
483 static void DoThreadOnExit(wxThread
*thread
);
488 if ( m_thread
->IsDetached() )
489 ::InterlockedIncrement(&m_nRef
);
494 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
499 // the thread we're associated with
502 HANDLE m_hThread
; // handle of the thread
503 wxThreadState m_state
; // state, see wxThreadState enum
504 unsigned int m_priority
; // thread priority in "wx" units
505 DWORD m_tid
; // thread id
507 // number of threads which need this thread to remain alive, when the count
508 // reaches 0 we kill the owning wxThread -- and die ourselves with it
511 wxDECLARE_NO_COPY_CLASS(wxThreadInternal
);
514 // small class which keeps a thread alive during its lifetime
515 class wxThreadKeepAlive
518 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
519 { m_thrImpl
.KeepAlive(); }
521 { m_thrImpl
.LetDie(); }
524 wxThreadInternal
& m_thrImpl
;
528 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
534 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
538 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
540 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
542 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
546 // store the thread object in the TLS
547 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
549 wxLogSysError(_("Cannot start thread: error writing TLS."));
551 return THREAD_ERROR_EXIT
;
554 rc
= wxPtrToUInt(thread
->Entry());
556 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
562 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
564 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
566 wxThread
* const thread
= (wxThread
*)param
;
568 // each thread has its own SEH translator so install our own a.s.a.p.
569 DisableAutomaticSETranslator();
571 // first of all, check whether we hadn't been cancelled already and don't
572 // start the user code at all then
573 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
575 // run the thread function itself inside a SEH try/except block
579 DoThreadOnExit(thread
);
581 rc
= DoThreadStart(thread
);
583 wxSEH_HANDLE(THREAD_ERROR_EXIT
)
586 // save IsDetached because thread object can be deleted by joinable
587 // threads after state is changed to STATE_EXITED.
588 const bool isDetached
= thread
->IsDetached();
591 // enter m_critsect before changing the thread state
593 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
594 // incompatible with C++ object dtors
595 thread
->m_critsect
.Enter();
596 thread
->m_internal
->SetState(STATE_EXITED
);
597 thread
->m_critsect
.Leave();
600 // the thread may delete itself now if it wants, we don't need it any more
602 thread
->m_internal
->LetDie();
607 void wxThreadInternal::SetPriority(unsigned int priority
)
609 m_priority
= priority
;
611 // translate wxWidgets priority to the Windows one
613 if (m_priority
<= 20)
614 win_priority
= THREAD_PRIORITY_LOWEST
;
615 else if (m_priority
<= 40)
616 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
617 else if (m_priority
<= 60)
618 win_priority
= THREAD_PRIORITY_NORMAL
;
619 else if (m_priority
<= 80)
620 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
621 else if (m_priority
<= 100)
622 win_priority
= THREAD_PRIORITY_HIGHEST
;
625 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
626 win_priority
= THREAD_PRIORITY_NORMAL
;
629 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
631 wxLogSysError(_("Can't set thread priority"));
635 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
637 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
638 wxT("Create()ing thread twice?") );
640 // for compilers which have it, we should use C RTL function for thread
641 // creation instead of Win32 API one because otherwise we will have memory
642 // leaks if the thread uses C RTL (and most threads do)
643 #ifdef wxUSE_BEGIN_THREAD
645 // Watcom is reported to not like 0 stack size (which means "use default"
646 // for the other compilers and is also the default value for stackSize)
650 #endif // __WATCOMC__
652 m_hThread
= (HANDLE
)_beginthreadex
654 NULL
, // default security
656 wxThreadInternal::WinThreadStart
, // entry point
659 (unsigned int *)&m_tid
661 #else // compiler doesn't have _beginthreadex
662 m_hThread
= ::CreateThread
664 NULL
, // default security
665 stackSize
, // stack size
666 wxThreadInternal::WinThreadStart
, // thread entry point
667 (LPVOID
)thread
, // parameter
668 CREATE_SUSPENDED
, // flags
669 &m_tid
// [out] thread id
671 #endif // _beginthreadex/CreateThread
673 if ( m_hThread
== NULL
)
675 wxLogSysError(_("Can't create thread"));
680 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
682 SetPriority(m_priority
);
688 wxThreadError
wxThreadInternal::Kill()
692 if ( !::TerminateThread(m_hThread
, THREAD_ERROR_EXIT
) )
694 wxLogSysError(_("Couldn't terminate thread"));
696 return wxTHREAD_MISC_ERROR
;
701 return wxTHREAD_NO_ERROR
;
705 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
706 wxThread::ExitCode
*pRc
,
707 wxThreadWait waitMode
,
708 wxThread
*threadToDelete
)
710 // prevent the thread C++ object from disappearing as long as we are using
712 wxThreadKeepAlive
keepAlive(*this);
715 // we may either wait passively for the thread to terminate (when called
716 // from Wait()) or ask it to terminate (when called from Delete())
717 bool shouldDelete
= threadToDelete
!= NULL
;
721 // we might need to resume the thread if it's currently stopped
722 bool shouldResume
= false;
724 // as Delete() (which calls us) is always safe to call we need to consider
725 // all possible states
727 wxCriticalSectionLocker
lock(cs
);
729 if ( m_state
== STATE_NEW
)
733 // WinThreadStart() will see it and terminate immediately, no
734 // need to cancel the thread -- but we still need to resume it
736 m_state
= STATE_EXITED
;
738 // we must call Resume() as the thread hasn't been initially
739 // resumed yet (and as Resume() it knows about STATE_EXITED
740 // special case, it won't touch it and WinThreadStart() will
741 // just exit immediately)
743 shouldDelete
= false;
745 //else: shouldResume is correctly set to false here, wait until
746 // someone else runs the thread and it finishes
748 else // running, paused, cancelled or even exited
750 shouldResume
= m_state
== STATE_PAUSED
;
754 // resume the thread if it is paused
758 // ask the thread to terminate
761 wxCriticalSectionLocker
lock(cs
);
766 if ( threadToDelete
)
767 threadToDelete
->OnDelete();
769 // now wait for thread to finish
770 if ( wxThread::IsMain() )
772 // set flag for wxIsWaitingForThread()
773 gs_waitingForThread
= true;
776 // we can't just wait for the thread to terminate because it might be
777 // calling some GUI functions and so it will never terminate before we
778 // process the Windows messages that result from these functions
779 // (note that even in console applications we might have to process
780 // messages if we use wxExecute() or timers or ...)
781 DWORD result
wxDUMMY_INITIALIZE(0);
784 if ( wxThread::IsMain() )
786 // give the thread we're waiting for chance to do the GUI call
788 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
794 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
797 result
= traits
->WaitForThread(m_hThread
, waitMode
);
799 else // can't wait for the thread
809 wxLogSysError(_("Cannot wait for thread termination"));
811 return wxTHREAD_KILLED
;
814 // thread we're waiting for terminated
817 case WAIT_OBJECT_0
+ 1:
818 // new message arrived, process it -- but only if we're the
819 // main thread as we don't support processing messages in
822 // NB: we still must include QS_ALLINPUT even when waiting
823 // in a secondary thread because if it had created some
824 // window somehow (possible not even using wxWidgets)
825 // the system might dead lock then
826 if ( wxThread::IsMain() )
828 if ( traits
&& !traits
->DoMessageFromThreadWait() )
830 // WM_QUIT received: kill the thread
833 return wxTHREAD_KILLED
;
839 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
841 } while ( result
!= WAIT_OBJECT_0
);
843 if ( wxThread::IsMain() )
845 gs_waitingForThread
= false;
849 // although the thread might be already in the EXITED state it might not
850 // have terminated yet and so we are not sure that it has actually
851 // terminated if the "if" above hadn't been taken
854 if ( !::GetExitCodeThread(m_hThread
, &rc
) )
856 wxLogLastError(wxT("GetExitCodeThread"));
858 rc
= THREAD_ERROR_EXIT
;
863 if ( rc
!= STILL_ACTIVE
)
866 // give the other thread some time to terminate, otherwise we may be
872 *pRc
= wxUIntToPtr(rc
);
874 // we don't need the thread handle any more in any case
878 return rc
== THREAD_ERROR_EXIT
? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
881 bool wxThreadInternal::Suspend()
883 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
884 if ( nSuspendCount
== (DWORD
)-1 )
886 wxLogSysError(_("Cannot suspend thread %x"), m_hThread
);
891 m_state
= STATE_PAUSED
;
896 bool wxThreadInternal::Resume()
898 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
899 if ( nSuspendCount
== (DWORD
)-1 )
901 wxLogSysError(_("Cannot resume thread %x"), m_hThread
);
906 // don't change the state from STATE_EXITED because it's special and means
907 // we are going to terminate without running any user code - if we did it,
908 // the code in WaitForTerminate() wouldn't work
909 if ( m_state
!= STATE_EXITED
)
911 m_state
= STATE_RUNNING
;
920 wxThread
*wxThread::This()
922 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
924 // be careful, 0 may be a valid return value as well
925 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
927 wxLogSysError(_("Couldn't get the current thread pointer"));
935 void wxThread::Yield()
937 // 0 argument to Sleep() is special and means to just give away the rest of
942 int wxThread::GetCPUCount()
947 return si
.dwNumberOfProcessors
;
950 unsigned long wxThread::GetCurrentId()
952 return (unsigned long)::GetCurrentThreadId();
955 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
960 wxASSERT_MSG( IsMain(), wxT("should only be called from the main thread") );
962 // ok only for the default one
966 // get system affinity mask first
967 HANDLE hProcess
= ::GetCurrentProcess();
968 DWORD_PTR dwProcMask
, dwSysMask
;
969 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
971 wxLogLastError(wxT("GetProcessAffinityMask"));
976 // how many CPUs have we got?
977 if ( dwSysMask
== 1 )
979 // don't bother with all this complicated stuff - on a single
980 // processor system it doesn't make much sense anyhow
984 // calculate the process mask: it's a bit vector with one bit per
985 // processor; we want to schedule the process to run on first level
990 if ( dwSysMask
& bit
)
992 // ok, we can set this bit
995 // another process added
1007 // could we set all bits?
1010 wxLogDebug(wxT("bad level %u in wxThread::SetConcurrency()"), level
);
1015 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1016 // exist in Win9x, use RT binding instead
1018 typedef BOOL (WINAPI
*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD_PTR
);
1020 // can use static var because we're always in the main thread here
1021 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1023 if ( !pfnSetProcessAffinityMask
)
1025 HMODULE hModKernel
= ::LoadLibrary(wxT("kernel32"));
1028 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1029 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1032 // we've discovered a MT version of Win9x!
1033 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1034 wxT("this system has several CPUs but no SetProcessAffinityMask function?") );
1037 if ( !pfnSetProcessAffinityMask
)
1039 // msg given above - do it only once
1043 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1045 wxLogLastError(wxT("SetProcessAffinityMask"));
1051 #endif // __WXWINCE__/!__WXWINCE__
1057 wxThread::wxThread(wxThreadKind kind
)
1059 m_internal
= new wxThreadInternal(this);
1061 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1064 wxThread::~wxThread()
1069 // create/start thread
1070 // -------------------
1072 wxThreadError
wxThread::Create(unsigned int stackSize
)
1074 wxCriticalSectionLocker
lock(m_critsect
);
1076 if ( !m_internal
->Create(this, stackSize
) )
1077 return wxTHREAD_NO_RESOURCE
;
1079 return wxTHREAD_NO_ERROR
;
1082 wxThreadError
wxThread::Run()
1084 wxCriticalSectionLocker
lock(m_critsect
);
1086 wxCHECK_MSG( m_internal
->GetState() == STATE_NEW
, wxTHREAD_RUNNING
,
1087 wxT("thread may only be started once after Create()") );
1089 // the thread has just been created and is still suspended - let it run
1093 // suspend/resume thread
1094 // ---------------------
1096 wxThreadError
wxThread::Pause()
1098 wxCriticalSectionLocker
lock(m_critsect
);
1100 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1103 wxThreadError
wxThread::Resume()
1105 wxCriticalSectionLocker
lock(m_critsect
);
1107 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1113 wxThread::ExitCode
wxThread::Wait(wxThreadWait waitMode
)
1115 ExitCode rc
= wxUIntToPtr(THREAD_ERROR_EXIT
);
1117 // although under Windows we can wait for any thread, it's an error to
1118 // wait for a detached one in wxWin API
1119 wxCHECK_MSG( !IsDetached(), rc
,
1120 wxT("wxThread::Wait(): can't wait for detached thread") );
1122 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
, waitMode
);
1127 wxThreadError
wxThread::Delete(ExitCode
*pRc
, wxThreadWait waitMode
)
1129 return m_internal
->WaitForTerminate(m_critsect
, pRc
, waitMode
, this);
1132 wxThreadError
wxThread::Kill()
1135 return wxTHREAD_NOT_RUNNING
;
1137 wxThreadError rc
= m_internal
->Kill();
1145 // update the status of the joinable thread
1146 wxCriticalSectionLocker
lock(m_critsect
);
1147 m_internal
->SetState(STATE_EXITED
);
1153 void wxThread::Exit(ExitCode status
)
1163 // update the status of the joinable thread
1164 wxCriticalSectionLocker
lock(m_critsect
);
1165 m_internal
->SetState(STATE_EXITED
);
1168 #ifdef wxUSE_BEGIN_THREAD
1169 _endthreadex(wxPtrToUInt(status
));
1171 ::ExitThread((DWORD
)status
);
1172 #endif // VC++/!VC++
1174 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1180 void wxThread::SetPriority(unsigned int prio
)
1182 wxCriticalSectionLocker
lock(m_critsect
);
1184 m_internal
->SetPriority(prio
);
1187 unsigned int wxThread::GetPriority() const
1189 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1191 return m_internal
->GetPriority();
1194 unsigned long wxThread::GetId() const
1196 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1198 return (unsigned long)m_internal
->GetId();
1201 bool wxThread::IsRunning() const
1203 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1205 return m_internal
->GetState() == STATE_RUNNING
;
1208 bool wxThread::IsAlive() const
1210 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1212 return (m_internal
->GetState() == STATE_RUNNING
) ||
1213 (m_internal
->GetState() == STATE_PAUSED
);
1216 bool wxThread::IsPaused() const
1218 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1220 return m_internal
->GetState() == STATE_PAUSED
;
1223 bool wxThread::TestDestroy()
1225 wxCriticalSectionLocker
lock(const_cast<wxCriticalSection
&>(m_critsect
));
1227 return m_internal
->GetState() == STATE_CANCELED
;
1230 // ----------------------------------------------------------------------------
1231 // Automatic initialization for thread module
1232 // ----------------------------------------------------------------------------
1234 class wxThreadModule
: public wxModule
1237 virtual bool OnInit();
1238 virtual void OnExit();
1241 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1244 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1246 bool wxThreadModule::OnInit()
1248 // allocate TLS index for storing the pointer to the current thread
1249 gs_tlsThisThread
= ::TlsAlloc();
1250 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1252 // in normal circumstances it will only happen if all other
1253 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1254 // words, this should never happen
1255 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1260 // main thread doesn't have associated wxThread object, so store 0 in the
1262 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1264 ::TlsFree(gs_tlsThisThread
);
1265 gs_tlsThisThread
= 0xFFFFFFFF;
1267 wxLogSysError(_("Thread module initialization failed: cannot store value in thread local storage"));
1272 gs_critsectWaitingForGui
= new wxCriticalSection();
1274 gs_critsectGui
= new wxCriticalSection();
1275 gs_critsectGui
->Enter();
1277 gs_critsectThreadDelete
= new wxCriticalSection
;
1279 wxThread::ms_idMainThread
= wxThread::GetCurrentId();
1284 void wxThreadModule::OnExit()
1286 if ( !::TlsFree(gs_tlsThisThread
) )
1288 wxLogLastError(wxT("TlsFree failed."));
1291 wxDELETE(gs_critsectThreadDelete
);
1293 if ( gs_critsectGui
)
1295 gs_critsectGui
->Leave();
1296 wxDELETE(gs_critsectGui
);
1299 wxDELETE(gs_critsectWaitingForGui
);
1302 // ----------------------------------------------------------------------------
1303 // under Windows, these functions are implemented using a critical section and
1304 // not a mutex, so the names are a bit confusing
1305 // ----------------------------------------------------------------------------
1307 void wxMutexGuiEnterImpl()
1309 // this would dead lock everything...
1310 wxASSERT_MSG( !wxThread::IsMain(),
1311 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1313 // the order in which we enter the critical sections here is crucial!!
1315 // set the flag telling to the main thread that we want to do some GUI
1317 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1319 gs_nWaitingForGui
++;
1322 wxWakeUpMainThread();
1324 // now we may block here because the main thread will soon let us in
1325 // (during the next iteration of OnIdle())
1326 gs_critsectGui
->Enter();
1329 void wxMutexGuiLeaveImpl()
1331 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1333 if ( wxThread::IsMain() )
1335 gs_bGuiOwnedByMainThread
= false;
1339 // decrement the number of threads waiting for GUI access now
1340 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1341 wxT("calling wxMutexGuiLeave() without entering it first?") );
1343 gs_nWaitingForGui
--;
1345 wxWakeUpMainThread();
1348 gs_critsectGui
->Leave();
1351 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1353 wxASSERT_MSG( wxThread::IsMain(),
1354 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1356 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1358 if ( gs_nWaitingForGui
== 0 )
1360 // no threads are waiting for GUI - so we may acquire the lock without
1361 // any danger (but only if we don't already have it)
1362 if ( !wxGuiOwnedByMainThread() )
1364 gs_critsectGui
->Enter();
1366 gs_bGuiOwnedByMainThread
= true;
1368 //else: already have it, nothing to do
1372 // some threads are waiting, release the GUI lock if we have it
1373 if ( wxGuiOwnedByMainThread() )
1377 //else: some other worker thread is doing GUI
1381 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1383 return gs_bGuiOwnedByMainThread
;
1386 // wake up the main thread if it's in ::GetMessage()
1387 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1389 // sending any message would do - hopefully WM_NULL is harmless enough
1390 if ( !::PostThreadMessage(wxThread::GetMainId(), WM_NULL
, 0, 0) )
1392 // should never happen
1393 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1397 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1399 return gs_waitingForThread
;
1402 // ----------------------------------------------------------------------------
1403 // include common implementation code
1404 // ----------------------------------------------------------------------------
1406 #include "wx/thrimpl.cpp"
1408 #endif // wxUSE_THREADS