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( 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 DECLARE_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(_T("CreateMutex()"));
220 wxMutexInternal::~wxMutexInternal()
224 if ( !::CloseHandle(m_mutex
) )
226 wxLogLastError(_T("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
);
252 if ( rc
== WAIT_ABANDONED
)
254 // the previous caller died without releasing the mutex, but now we can
256 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
258 // use 0 timeout, normally we should always get it
259 rc
= ::WaitForSingleObject(m_mutex
, 0);
269 return wxMUTEX_TIMEOUT
;
271 case WAIT_ABANDONED
: // checked for above
273 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
277 wxLogLastError(_T("WaitForSingleObject(mutex)"));
278 return wxMUTEX_MISC_ERROR
;
281 if (m_type
== wxMUTEX_DEFAULT
)
283 // required for checking recursiveness
284 m_owningThread
= wxThread::GetCurrentId();
287 return wxMUTEX_NO_ERROR
;
290 wxMutexError
wxMutexInternal::Unlock()
292 // required for checking recursiveness
295 if ( !::ReleaseMutex(m_mutex
) )
297 wxLogLastError(_T("ReleaseMutex()"));
299 return wxMUTEX_MISC_ERROR
;
302 return wxMUTEX_NO_ERROR
;
305 // --------------------------------------------------------------------------
307 // --------------------------------------------------------------------------
309 // a trivial wrapper around Win32 semaphore
310 class wxSemaphoreInternal
313 wxSemaphoreInternal(int initialcount
, int maxcount
);
314 ~wxSemaphoreInternal();
316 bool IsOk() const { return m_semaphore
!= NULL
; }
318 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
320 wxSemaError
TryWait()
322 wxSemaError rc
= WaitTimeout(0);
323 if ( rc
== wxSEMA_TIMEOUT
)
329 wxSemaError
WaitTimeout(unsigned long milliseconds
);
336 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
339 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
341 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
344 // make it practically infinite
348 m_semaphore
= ::CreateSemaphore
350 NULL
, // default security attributes
358 wxLogLastError(_T("CreateSemaphore()"));
362 wxSemaphoreInternal::~wxSemaphoreInternal()
366 if ( !::CloseHandle(m_semaphore
) )
368 wxLogLastError(_T("CloseHandle(semaphore)"));
373 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
375 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
380 return wxSEMA_NO_ERROR
;
383 return wxSEMA_TIMEOUT
;
386 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
389 return wxSEMA_MISC_ERROR
;
392 wxSemaError
wxSemaphoreInternal::Post()
394 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
395 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
397 if ( GetLastError() == ERROR_TOO_MANY_POSTS
)
399 return wxSEMA_OVERFLOW
;
403 wxLogLastError(_T("ReleaseSemaphore"));
404 return wxSEMA_MISC_ERROR
;
408 return wxSEMA_NO_ERROR
;
410 return wxSEMA_MISC_ERROR
;
414 // ----------------------------------------------------------------------------
415 // wxThread implementation
416 // ----------------------------------------------------------------------------
418 // wxThreadInternal class
419 // ----------------------
421 class wxThreadInternal
424 wxThreadInternal(wxThread
*thread
)
429 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
442 if ( !::CloseHandle(m_hThread
) )
444 wxLogLastError(wxT("CloseHandle(thread)"));
451 // create a new (suspended) thread (for the given thread object)
452 bool Create(wxThread
*thread
, unsigned int stackSize
);
454 // wait for the thread to terminate, either by itself, or by asking it
455 // (politely, this is not Kill()!) to do it
456 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
457 wxThread::ExitCode
*pRc
,
458 wxThread
*threadToDelete
= NULL
);
460 // kill the thread unconditionally
461 wxThreadError
Kill();
463 // suspend/resume/terminate
466 void Cancel() { m_state
= STATE_CANCELED
; }
469 void SetState(wxThreadState state
) { m_state
= state
; }
470 wxThreadState
GetState() const { return m_state
; }
473 void SetPriority(unsigned int priority
);
474 unsigned int GetPriority() const { return m_priority
; }
476 // thread handle and id
477 HANDLE
GetHandle() const { return m_hThread
; }
478 DWORD
GetId() const { return m_tid
; }
480 // the thread function forwarding to DoThreadStart
481 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
483 // really start the thread (if it's not already dead)
484 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
486 // call OnExit() on the thread
487 static void DoThreadOnExit(wxThread
*thread
);
492 if ( m_thread
->IsDetached() )
493 ::InterlockedIncrement(&m_nRef
);
498 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
503 // the thread we're associated with
506 HANDLE m_hThread
; // handle of the thread
507 wxThreadState m_state
; // state, see wxThreadState enum
508 unsigned int m_priority
; // thread priority in "wx" units
509 DWORD m_tid
; // thread id
511 // number of threads which need this thread to remain alive, when the count
512 // reaches 0 we kill the owning wxThread -- and die ourselves with it
515 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
518 // small class which keeps a thread alive during its lifetime
519 class wxThreadKeepAlive
522 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
523 { m_thrImpl
.KeepAlive(); }
525 { m_thrImpl
.LetDie(); }
528 wxThreadInternal
& m_thrImpl
;
532 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
538 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
542 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
544 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
546 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
550 // store the thread object in the TLS
551 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
553 wxLogSysError(_("Can not start thread: error writing TLS."));
555 return THREAD_ERROR_EXIT
;
558 rc
= wxPtrToUInt(thread
->Entry());
560 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
566 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
568 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
570 wxThread
* const thread
= (wxThread
*)param
;
572 // each thread has its own SEH translator so install our own a.s.a.p.
573 DisableAutomaticSETranslator();
575 // first of all, check whether we hadn't been cancelled already and don't
576 // start the user code at all then
577 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
579 // run the thread function itself inside a SEH try/except block
583 DoThreadOnExit(thread
);
585 rc
= DoThreadStart(thread
);
587 wxSEH_HANDLE(THREAD_ERROR_EXIT
)
590 // save IsDetached because thread object can be deleted by joinable
591 // threads after state is changed to STATE_EXITED.
592 const bool isDetached
= thread
->IsDetached();
595 // enter m_critsect before changing the thread state
597 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
598 // incompatible with C++ object dtors
599 thread
->m_critsect
.Enter();
600 thread
->m_internal
->SetState(STATE_EXITED
);
601 thread
->m_critsect
.Leave();
604 // the thread may delete itself now if it wants, we don't need it any more
606 thread
->m_internal
->LetDie();
611 void wxThreadInternal::SetPriority(unsigned int priority
)
613 m_priority
= priority
;
615 // translate wxWidgets priority to the Windows one
617 if (m_priority
<= 20)
618 win_priority
= THREAD_PRIORITY_LOWEST
;
619 else if (m_priority
<= 40)
620 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
621 else if (m_priority
<= 60)
622 win_priority
= THREAD_PRIORITY_NORMAL
;
623 else if (m_priority
<= 80)
624 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
625 else if (m_priority
<= 100)
626 win_priority
= THREAD_PRIORITY_HIGHEST
;
629 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
630 win_priority
= THREAD_PRIORITY_NORMAL
;
633 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
635 wxLogSysError(_("Can't set thread priority"));
639 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
641 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
642 _T("Create()ing thread twice?") );
644 // for compilers which have it, we should use C RTL function for thread
645 // creation instead of Win32 API one because otherwise we will have memory
646 // leaks if the thread uses C RTL (and most threads do)
647 #ifdef wxUSE_BEGIN_THREAD
649 // Watcom is reported to not like 0 stack size (which means "use default"
650 // for the other compilers and is also the default value for stackSize)
654 #endif // __WATCOMC__
656 m_hThread
= (HANDLE
)_beginthreadex
658 NULL
, // default security
660 wxThreadInternal::WinThreadStart
, // entry point
663 (unsigned int *)&m_tid
665 #else // compiler doesn't have _beginthreadex
666 m_hThread
= ::CreateThread
668 NULL
, // default security
669 stackSize
, // stack size
670 wxThreadInternal::WinThreadStart
, // thread entry point
671 (LPVOID
)thread
, // parameter
672 CREATE_SUSPENDED
, // flags
673 &m_tid
// [out] thread id
675 #endif // _beginthreadex/CreateThread
677 if ( m_hThread
== NULL
)
679 wxLogSysError(_("Can't create thread"));
684 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
686 SetPriority(m_priority
);
692 wxThreadError
wxThreadInternal::Kill()
694 if ( !::TerminateThread(m_hThread
, THREAD_ERROR_EXIT
) )
696 wxLogSysError(_("Couldn't terminate thread"));
698 return wxTHREAD_MISC_ERROR
;
703 return wxTHREAD_NO_ERROR
;
707 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
708 wxThread::ExitCode
*pRc
,
709 wxThread
*threadToDelete
)
711 // prevent the thread C++ object from disappearing as long as we are using
713 wxThreadKeepAlive
keepAlive(*this);
716 // we may either wait passively for the thread to terminate (when called
717 // from Wait()) or ask it to terminate (when called from Delete())
718 bool shouldDelete
= threadToDelete
!= NULL
;
722 // we might need to resume the thread if it's currently stopped
723 bool shouldResume
= false;
725 // as Delete() (which calls us) is always safe to call we need to consider
726 // all possible states
728 wxCriticalSectionLocker
lock(cs
);
730 if ( m_state
== STATE_NEW
)
734 // WinThreadStart() will see it and terminate immediately, no
735 // need to cancel the thread -- but we still need to resume it
737 m_state
= STATE_EXITED
;
739 // we must call Resume() as the thread hasn't been initially
740 // resumed yet (and as Resume() it knows about STATE_EXITED
741 // special case, it won't touch it and WinThreadStart() will
742 // just exit immediately)
744 shouldDelete
= false;
746 //else: shouldResume is correctly set to false here, wait until
747 // someone else runs the thread and it finishes
749 else // running, paused, cancelled or even exited
751 shouldResume
= m_state
== STATE_PAUSED
;
755 // resume the thread if it is paused
759 // ask the thread to terminate
762 wxCriticalSectionLocker
lock(cs
);
768 // now wait for thread to finish
769 if ( wxThread::IsMain() )
771 // set flag for wxIsWaitingForThread()
772 gs_waitingForThread
= true;
775 // we can't just wait for the thread to terminate because it might be
776 // calling some GUI functions and so it will never terminate before we
777 // process the Windows messages that result from these functions
778 // (note that even in console applications we might have to process
779 // messages if we use wxExecute() or timers or ...)
780 DWORD result
wxDUMMY_INITIALIZE(0);
783 if ( wxThread::IsMain() )
785 // give the thread we're waiting for chance to do the GUI call
787 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
793 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
796 result
= traits
->WaitForThread(m_hThread
);
798 else // can't wait for the thread
808 wxLogSysError(_("Can not wait for thread termination"));
810 return wxTHREAD_KILLED
;
813 // thread we're waiting for terminated
816 case WAIT_OBJECT_0
+ 1:
817 // new message arrived, process it -- but only if we're the
818 // main thread as we don't support processing messages in
821 // NB: we still must include QS_ALLINPUT even when waiting
822 // in a secondary thread because if it had created some
823 // window somehow (possible not even using wxWidgets)
824 // the system might dead lock then
825 if ( wxThread::IsMain() )
827 if ( traits
&& !traits
->DoMessageFromThreadWait() )
829 // WM_QUIT received: kill the thread
832 return wxTHREAD_KILLED
;
838 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
840 } while ( result
!= WAIT_OBJECT_0
);
842 if ( wxThread::IsMain() )
844 gs_waitingForThread
= false;
848 // although the thread might be already in the EXITED state it might not
849 // have terminated yet and so we are not sure that it has actually
850 // terminated if the "if" above hadn't been taken
853 if ( !::GetExitCodeThread(m_hThread
, &rc
) )
855 wxLogLastError(wxT("GetExitCodeThread"));
857 rc
= THREAD_ERROR_EXIT
;
862 if ( rc
!= STILL_ACTIVE
)
865 // give the other thread some time to terminate, otherwise we may be
871 *pRc
= wxUIntToPtr(rc
);
873 // we don't need the thread handle any more in any case
877 return rc
== THREAD_ERROR_EXIT
? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
880 bool wxThreadInternal::Suspend()
882 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
883 if ( nSuspendCount
== (DWORD
)-1 )
885 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
890 m_state
= STATE_PAUSED
;
895 bool wxThreadInternal::Resume()
897 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
898 if ( nSuspendCount
== (DWORD
)-1 )
900 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
905 // don't change the state from STATE_EXITED because it's special and means
906 // we are going to terminate without running any user code - if we did it,
907 // the code in WaitForTerminate() wouldn't work
908 if ( m_state
!= STATE_EXITED
)
910 m_state
= STATE_RUNNING
;
919 wxThread
*wxThread::This()
921 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
923 // be careful, 0 may be a valid return value as well
924 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
926 wxLogSysError(_("Couldn't get the current thread pointer"));
934 bool wxThread::IsMain()
936 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
939 void wxThread::Yield()
941 // 0 argument to Sleep() is special and means to just give away the rest of
946 int wxThread::GetCPUCount()
951 return si
.dwNumberOfProcessors
;
954 unsigned long wxThread::GetCurrentId()
956 return (unsigned long)::GetCurrentThreadId();
959 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
964 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
966 // ok only for the default one
970 // get system affinity mask first
971 HANDLE hProcess
= ::GetCurrentProcess();
972 DWORD_PTR dwProcMask
, dwSysMask
;
973 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
975 wxLogLastError(_T("GetProcessAffinityMask"));
980 // how many CPUs have we got?
981 if ( dwSysMask
== 1 )
983 // don't bother with all this complicated stuff - on a single
984 // processor system it doesn't make much sense anyhow
988 // calculate the process mask: it's a bit vector with one bit per
989 // processor; we want to schedule the process to run on first level
994 if ( dwSysMask
& bit
)
996 // ok, we can set this bit
999 // another process added
1002 // and that's enough
1011 // could we set all bits?
1014 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
1019 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1020 // exist in Win9x, use RT binding instead
1022 typedef BOOL (WINAPI
*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD_PTR
);
1024 // can use static var because we're always in the main thread here
1025 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1027 if ( !pfnSetProcessAffinityMask
)
1029 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
1032 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1033 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1036 // we've discovered a MT version of Win9x!
1037 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1038 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1041 if ( !pfnSetProcessAffinityMask
)
1043 // msg given above - do it only once
1047 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1049 wxLogLastError(_T("SetProcessAffinityMask"));
1055 #endif // __WXWINCE__/!__WXWINCE__
1061 wxThread::wxThread(wxThreadKind kind
)
1063 m_internal
= new wxThreadInternal(this);
1065 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1068 wxThread::~wxThread()
1073 // create/start thread
1074 // -------------------
1076 wxThreadError
wxThread::Create(unsigned int stackSize
)
1078 wxCriticalSectionLocker
lock(m_critsect
);
1080 if ( !m_internal
->Create(this, stackSize
) )
1081 return wxTHREAD_NO_RESOURCE
;
1083 return wxTHREAD_NO_ERROR
;
1086 wxThreadError
wxThread::Run()
1088 wxCriticalSectionLocker
lock(m_critsect
);
1090 if ( m_internal
->GetState() != STATE_NEW
)
1092 // actually, it may be almost any state at all, not only STATE_RUNNING
1093 return wxTHREAD_RUNNING
;
1096 // the thread has just been created and is still suspended - let it run
1100 // suspend/resume thread
1101 // ---------------------
1103 wxThreadError
wxThread::Pause()
1105 wxCriticalSectionLocker
lock(m_critsect
);
1107 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1110 wxThreadError
wxThread::Resume()
1112 wxCriticalSectionLocker
lock(m_critsect
);
1114 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1120 wxThread::ExitCode
wxThread::Wait()
1122 ExitCode rc
= wxUIntToPtr(THREAD_ERROR_EXIT
);
1124 // although under Windows we can wait for any thread, it's an error to
1125 // wait for a detached one in wxWin API
1126 wxCHECK_MSG( !IsDetached(), rc
,
1127 _T("wxThread::Wait(): can't wait for detached thread") );
1129 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1134 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1136 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1139 wxThreadError
wxThread::Kill()
1142 return wxTHREAD_NOT_RUNNING
;
1144 wxThreadError rc
= m_internal
->Kill();
1152 // update the status of the joinable thread
1153 wxCriticalSectionLocker
lock(m_critsect
);
1154 m_internal
->SetState(STATE_EXITED
);
1160 void wxThread::Exit(ExitCode status
)
1170 // update the status of the joinable thread
1171 wxCriticalSectionLocker
lock(m_critsect
);
1172 m_internal
->SetState(STATE_EXITED
);
1175 #ifdef wxUSE_BEGIN_THREAD
1176 _endthreadex(wxPtrToUInt(status
));
1178 ::ExitThread((DWORD
)status
);
1179 #endif // VC++/!VC++
1181 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1187 void wxThread::SetPriority(unsigned int prio
)
1189 wxCriticalSectionLocker
lock(m_critsect
);
1191 m_internal
->SetPriority(prio
);
1194 unsigned int wxThread::GetPriority() const
1196 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1198 return m_internal
->GetPriority();
1201 unsigned long wxThread::GetId() const
1203 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1205 return (unsigned long)m_internal
->GetId();
1208 bool wxThread::IsRunning() const
1210 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1212 return m_internal
->GetState() == STATE_RUNNING
;
1215 bool wxThread::IsAlive() const
1217 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1219 return (m_internal
->GetState() == STATE_RUNNING
) ||
1220 (m_internal
->GetState() == STATE_PAUSED
);
1223 bool wxThread::IsPaused() const
1225 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1227 return m_internal
->GetState() == STATE_PAUSED
;
1230 bool wxThread::TestDestroy()
1232 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1234 return m_internal
->GetState() == STATE_CANCELED
;
1237 // ----------------------------------------------------------------------------
1238 // Automatic initialization for thread module
1239 // ----------------------------------------------------------------------------
1241 class wxThreadModule
: public wxModule
1244 virtual bool OnInit();
1245 virtual void OnExit();
1248 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1251 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1253 bool wxThreadModule::OnInit()
1255 // allocate TLS index for storing the pointer to the current thread
1256 gs_tlsThisThread
= ::TlsAlloc();
1257 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1259 // in normal circumstances it will only happen if all other
1260 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1261 // words, this should never happen
1262 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1267 // main thread doesn't have associated wxThread object, so store 0 in the
1269 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1271 ::TlsFree(gs_tlsThisThread
);
1272 gs_tlsThisThread
= 0xFFFFFFFF;
1274 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1279 gs_critsectWaitingForGui
= new wxCriticalSection();
1281 gs_critsectGui
= new wxCriticalSection();
1282 gs_critsectGui
->Enter();
1284 gs_critsectThreadDelete
= new wxCriticalSection
;
1286 // no error return for GetCurrentThreadId()
1287 gs_idMainThread
= ::GetCurrentThreadId();
1292 void wxThreadModule::OnExit()
1294 if ( !::TlsFree(gs_tlsThisThread
) )
1296 wxLogLastError(wxT("TlsFree failed."));
1299 delete gs_critsectThreadDelete
;
1300 gs_critsectThreadDelete
= NULL
;
1302 if ( gs_critsectGui
)
1304 gs_critsectGui
->Leave();
1305 delete gs_critsectGui
;
1306 gs_critsectGui
= NULL
;
1309 delete gs_critsectWaitingForGui
;
1310 gs_critsectWaitingForGui
= NULL
;
1313 // ----------------------------------------------------------------------------
1314 // under Windows, these functions are implemented using a critical section and
1315 // not a mutex, so the names are a bit confusing
1316 // ----------------------------------------------------------------------------
1318 void wxMutexGuiEnterImpl()
1320 // this would dead lock everything...
1321 wxASSERT_MSG( !wxThread::IsMain(),
1322 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1324 // the order in which we enter the critical sections here is crucial!!
1326 // set the flag telling to the main thread that we want to do some GUI
1328 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1330 gs_nWaitingForGui
++;
1333 wxWakeUpMainThread();
1335 // now we may block here because the main thread will soon let us in
1336 // (during the next iteration of OnIdle())
1337 gs_critsectGui
->Enter();
1340 void wxMutexGuiLeaveImpl()
1342 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1344 if ( wxThread::IsMain() )
1346 gs_bGuiOwnedByMainThread
= false;
1350 // decrement the number of threads waiting for GUI access now
1351 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1352 wxT("calling wxMutexGuiLeave() without entering it first?") );
1354 gs_nWaitingForGui
--;
1356 wxWakeUpMainThread();
1359 gs_critsectGui
->Leave();
1362 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1364 wxASSERT_MSG( wxThread::IsMain(),
1365 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1367 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1369 if ( gs_nWaitingForGui
== 0 )
1371 // no threads are waiting for GUI - so we may acquire the lock without
1372 // any danger (but only if we don't already have it)
1373 if ( !wxGuiOwnedByMainThread() )
1375 gs_critsectGui
->Enter();
1377 gs_bGuiOwnedByMainThread
= true;
1379 //else: already have it, nothing to do
1383 // some threads are waiting, release the GUI lock if we have it
1384 if ( wxGuiOwnedByMainThread() )
1388 //else: some other worker thread is doing GUI
1392 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1394 return gs_bGuiOwnedByMainThread
;
1397 // wake up the main thread if it's in ::GetMessage()
1398 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1400 // sending any message would do - hopefully WM_NULL is harmless enough
1401 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1403 // should never happen
1404 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1408 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1410 return gs_waitingForThread
;
1413 // ----------------------------------------------------------------------------
1414 // include common implementation code
1415 // ----------------------------------------------------------------------------
1417 #include "wx/thrimpl.cpp"
1419 #endif // wxUSE_THREADS