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
79 typedef wxUIntPtr THREAD_RETVAL
;
81 // the calling convention of the thread function entry point
82 #define THREAD_CALLCONV __stdcall
84 // the settings for CreateThread()
85 typedef DWORD THREAD_RETVAL
;
86 #define THREAD_CALLCONV WINAPI
89 static const THREAD_RETVAL THREAD_ERROR_EXIT
= (THREAD_RETVAL
)-1;
91 // ----------------------------------------------------------------------------
93 // ----------------------------------------------------------------------------
95 // the possible states of the thread ("=>" shows all possible transitions from
99 STATE_NEW
, // didn't start execution yet (=> RUNNING)
100 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
101 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
102 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
103 STATE_EXITED
// thread is terminating
106 // ----------------------------------------------------------------------------
107 // this module globals
108 // ----------------------------------------------------------------------------
110 // TLS index of the slot where we store the pointer to the current thread
111 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
113 // id of the main thread - the one which can call GUI functions without first
114 // calling wxMutexGuiEnter()
115 static DWORD gs_idMainThread
= 0;
117 // if it's false, some secondary thread is holding the GUI lock
118 static bool gs_bGuiOwnedByMainThread
= true;
120 // critical section which controls access to all GUI functions: any secondary
121 // thread (i.e. except the main one) must enter this crit section before doing
123 static wxCriticalSection
*gs_critsectGui
= NULL
;
125 // critical section which protects gs_nWaitingForGui variable
126 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
128 // critical section which serializes WinThreadStart() and WaitForTerminate()
129 // (this is a potential bottleneck, we use a single crit sect for all threads
130 // in the system, but normally time spent inside it should be quite short)
131 static wxCriticalSection
*gs_critsectThreadDelete
= NULL
;
133 // number of threads waiting for GUI in wxMutexGuiEnter()
134 static size_t gs_nWaitingForGui
= 0;
136 // are we waiting for a thread termination?
137 static bool gs_waitingForThread
= false;
139 // ============================================================================
140 // Windows implementation of thread and related classes
141 // ============================================================================
143 // ----------------------------------------------------------------------------
145 // ----------------------------------------------------------------------------
147 wxCriticalSection::wxCriticalSection()
149 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
150 wxCriticalSectionBufferTooSmall
);
152 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
155 wxCriticalSection::~wxCriticalSection()
157 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
160 void wxCriticalSection::Enter()
162 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
165 void wxCriticalSection::Leave()
167 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
170 // ----------------------------------------------------------------------------
172 // ----------------------------------------------------------------------------
174 class wxMutexInternal
177 wxMutexInternal(wxMutexType mutexType
);
180 bool IsOk() const { return m_mutex
!= NULL
; }
182 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
183 wxMutexError
Lock(unsigned long ms
) { return LockTimeout(ms
); }
184 wxMutexError
TryLock();
185 wxMutexError
Unlock();
188 wxMutexError
LockTimeout(DWORD milliseconds
);
192 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
195 // all mutexes are recursive under Win32 so we don't use mutexType
196 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
198 // create a nameless (hence intra process and always private) mutex
199 m_mutex
= ::CreateMutex
201 NULL
, // default secutiry attributes
202 FALSE
, // not initially locked
208 wxLogLastError(_T("CreateMutex()"));
212 wxMutexInternal::~wxMutexInternal()
216 if ( !::CloseHandle(m_mutex
) )
218 wxLogLastError(_T("CloseHandle(mutex)"));
223 wxMutexError
wxMutexInternal::TryLock()
225 const wxMutexError rc
= LockTimeout(0);
227 // we have a special return code for timeout in this case
228 return rc
== wxMUTEX_TIMEOUT
? wxMUTEX_BUSY
: rc
;
231 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
233 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
234 if ( rc
== WAIT_ABANDONED
)
236 // the previous caller died without releasing the mutex, but now we can
238 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
240 // use 0 timeout, normally we should always get it
241 rc
= ::WaitForSingleObject(m_mutex
, 0);
251 return wxMUTEX_TIMEOUT
;
253 case WAIT_ABANDONED
: // checked for above
255 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
259 wxLogLastError(_T("WaitForSingleObject(mutex)"));
260 return wxMUTEX_MISC_ERROR
;
263 return wxMUTEX_NO_ERROR
;
266 wxMutexError
wxMutexInternal::Unlock()
268 if ( !::ReleaseMutex(m_mutex
) )
270 wxLogLastError(_T("ReleaseMutex()"));
272 return wxMUTEX_MISC_ERROR
;
275 return wxMUTEX_NO_ERROR
;
278 // --------------------------------------------------------------------------
280 // --------------------------------------------------------------------------
282 // a trivial wrapper around Win32 semaphore
283 class wxSemaphoreInternal
286 wxSemaphoreInternal(int initialcount
, int maxcount
);
287 ~wxSemaphoreInternal();
289 bool IsOk() const { return m_semaphore
!= NULL
; }
291 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
293 wxSemaError
TryWait()
295 wxSemaError rc
= WaitTimeout(0);
296 if ( rc
== wxSEMA_TIMEOUT
)
302 wxSemaError
WaitTimeout(unsigned long milliseconds
);
309 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
312 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
314 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
317 // make it practically infinite
321 m_semaphore
= ::CreateSemaphore
323 NULL
, // default security attributes
331 wxLogLastError(_T("CreateSemaphore()"));
335 wxSemaphoreInternal::~wxSemaphoreInternal()
339 if ( !::CloseHandle(m_semaphore
) )
341 wxLogLastError(_T("CloseHandle(semaphore)"));
346 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
348 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
353 return wxSEMA_NO_ERROR
;
356 return wxSEMA_TIMEOUT
;
359 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
362 return wxSEMA_MISC_ERROR
;
365 wxSemaError
wxSemaphoreInternal::Post()
367 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
368 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
370 if ( GetLastError() == ERROR_TOO_MANY_POSTS
)
372 return wxSEMA_OVERFLOW
;
376 wxLogLastError(_T("ReleaseSemaphore"));
377 return wxSEMA_MISC_ERROR
;
381 return wxSEMA_NO_ERROR
;
383 return wxSEMA_MISC_ERROR
;
387 // ----------------------------------------------------------------------------
388 // wxThread implementation
389 // ----------------------------------------------------------------------------
391 // wxThreadInternal class
392 // ----------------------
394 class wxThreadInternal
397 wxThreadInternal(wxThread
*thread
)
402 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
415 if ( !::CloseHandle(m_hThread
) )
417 wxLogLastError(wxT("CloseHandle(thread)"));
424 // create a new (suspended) thread (for the given thread object)
425 bool Create(wxThread
*thread
, unsigned int stackSize
);
427 // wait for the thread to terminate, either by itself, or by asking it
428 // (politely, this is not Kill()!) to do it
429 wxThreadError
WaitForTerminate(wxCriticalSection
& cs
,
430 wxThread::ExitCode
*pRc
,
431 wxThread
*threadToDelete
= NULL
);
433 // kill the thread unconditionally
434 wxThreadError
Kill();
436 // suspend/resume/terminate
439 void Cancel() { m_state
= STATE_CANCELED
; }
442 void SetState(wxThreadState state
) { m_state
= state
; }
443 wxThreadState
GetState() const { return m_state
; }
446 void SetPriority(unsigned int priority
);
447 unsigned int GetPriority() const { return m_priority
; }
449 // thread handle and id
450 HANDLE
GetHandle() const { return m_hThread
; }
451 DWORD
GetId() const { return m_tid
; }
453 // the thread function forwarding to DoThreadStart
454 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
456 // really start the thread (if it's not already dead)
457 static THREAD_RETVAL
DoThreadStart(wxThread
*thread
);
459 // call OnExit() on the thread
460 static void DoThreadOnExit(wxThread
*thread
);
465 if ( m_thread
->IsDetached() )
466 ::InterlockedIncrement(&m_nRef
);
471 if ( m_thread
->IsDetached() && !::InterlockedDecrement(&m_nRef
) )
476 // the thread we're associated with
479 HANDLE m_hThread
; // handle of the thread
480 wxThreadState m_state
; // state, see wxThreadState enum
481 unsigned int m_priority
; // thread priority in "wx" units
482 DWORD m_tid
; // thread id
484 // number of threads which need this thread to remain alive, when the count
485 // reaches 0 we kill the owning wxThread -- and die ourselves with it
488 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
491 // small class which keeps a thread alive during its lifetime
492 class wxThreadKeepAlive
495 wxThreadKeepAlive(wxThreadInternal
& thrImpl
) : m_thrImpl(thrImpl
)
496 { m_thrImpl
.KeepAlive(); }
498 { m_thrImpl
.LetDie(); }
501 wxThreadInternal
& m_thrImpl
;
505 void wxThreadInternal::DoThreadOnExit(wxThread
*thread
)
511 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
515 THREAD_RETVAL
wxThreadInternal::DoThreadStart(wxThread
*thread
)
517 wxON_BLOCK_EXIT1(DoThreadOnExit
, thread
);
519 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
523 // store the thread object in the TLS
524 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
526 wxLogSysError(_("Can not start thread: error writing TLS."));
528 return THREAD_ERROR_EXIT
;
531 rc
= (THREAD_RETVAL
)thread
->Entry();
533 wxCATCH_ALL( wxTheApp
->OnUnhandledException(); )
539 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
541 THREAD_RETVAL rc
= THREAD_ERROR_EXIT
;
543 wxThread
* const thread
= (wxThread
*)param
;
545 // each thread has its own SEH translator so install our own a.s.a.p.
546 DisableAutomaticSETranslator();
548 // first of all, check whether we hadn't been cancelled already and don't
549 // start the user code at all then
550 const bool hasExited
= thread
->m_internal
->GetState() == STATE_EXITED
;
552 // run the thread function itself inside a SEH try/except block
556 DoThreadOnExit(thread
);
558 rc
= DoThreadStart(thread
);
560 wxSEH_HANDLE(THREAD_ERROR_EXIT
)
563 // save IsDetached because thread object can be deleted by joinable
564 // threads after state is changed to STATE_EXITED.
565 const bool isDetached
= thread
->IsDetached();
568 // enter m_critsect before changing the thread state
570 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
571 // incompatible with C++ object dtors
572 thread
->m_critsect
.Enter();
573 thread
->m_internal
->SetState(STATE_EXITED
);
574 thread
->m_critsect
.Leave();
577 // the thread may delete itself now if it wants, we don't need it any more
579 thread
->m_internal
->LetDie();
584 void wxThreadInternal::SetPriority(unsigned int priority
)
586 m_priority
= priority
;
588 // translate wxWidgets priority to the Windows one
590 if (m_priority
<= 20)
591 win_priority
= THREAD_PRIORITY_LOWEST
;
592 else if (m_priority
<= 40)
593 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
594 else if (m_priority
<= 60)
595 win_priority
= THREAD_PRIORITY_NORMAL
;
596 else if (m_priority
<= 80)
597 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
598 else if (m_priority
<= 100)
599 win_priority
= THREAD_PRIORITY_HIGHEST
;
602 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
603 win_priority
= THREAD_PRIORITY_NORMAL
;
606 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
608 wxLogSysError(_("Can't set thread priority"));
612 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
614 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
615 _T("Create()ing thread twice?") );
617 // for compilers which have it, we should use C RTL function for thread
618 // creation instead of Win32 API one because otherwise we will have memory
619 // leaks if the thread uses C RTL (and most threads do)
620 #ifdef wxUSE_BEGIN_THREAD
622 // Watcom is reported to not like 0 stack size (which means "use default"
623 // for the other compilers and is also the default value for stackSize)
627 #endif // __WATCOMC__
629 m_hThread
= (HANDLE
)_beginthreadex
631 NULL
, // default security
633 wxThreadInternal::WinThreadStart
, // entry point
636 (unsigned int *)&m_tid
638 #else // compiler doesn't have _beginthreadex
639 m_hThread
= ::CreateThread
641 NULL
, // default security
642 stackSize
, // stack size
643 wxThreadInternal::WinThreadStart
, // thread entry point
644 (LPVOID
)thread
, // parameter
645 CREATE_SUSPENDED
, // flags
646 &m_tid
// [out] thread id
648 #endif // _beginthreadex/CreateThread
650 if ( m_hThread
== NULL
)
652 wxLogSysError(_("Can't create thread"));
657 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
659 SetPriority(m_priority
);
665 wxThreadError
wxThreadInternal::Kill()
667 if ( !::TerminateThread(m_hThread
, THREAD_ERROR_EXIT
) )
669 wxLogSysError(_("Couldn't terminate thread"));
671 return wxTHREAD_MISC_ERROR
;
676 return wxTHREAD_NO_ERROR
;
680 wxThreadInternal::WaitForTerminate(wxCriticalSection
& cs
,
681 wxThread::ExitCode
*pRc
,
682 wxThread
*threadToDelete
)
684 // prevent the thread C++ object from disappearing as long as we are using
686 wxThreadKeepAlive
keepAlive(*this);
689 // we may either wait passively for the thread to terminate (when called
690 // from Wait()) or ask it to terminate (when called from Delete())
691 bool shouldDelete
= threadToDelete
!= NULL
;
695 // we might need to resume the thread if it's currently stopped
696 bool shouldResume
= false;
698 // as Delete() (which calls us) is always safe to call we need to consider
699 // all possible states
701 wxCriticalSectionLocker
lock(cs
);
703 if ( m_state
== STATE_NEW
)
707 // WinThreadStart() will see it and terminate immediately, no
708 // need to cancel the thread -- but we still need to resume it
710 m_state
= STATE_EXITED
;
712 // we must call Resume() as the thread hasn't been initially
713 // resumed yet (and as Resume() it knows about STATE_EXITED
714 // special case, it won't touch it and WinThreadStart() will
715 // just exit immediately)
717 shouldDelete
= false;
719 //else: shouldResume is correctly set to false here, wait until
720 // someone else runs the thread and it finishes
722 else // running, paused, cancelled or even exited
724 shouldResume
= m_state
== STATE_PAUSED
;
728 // resume the thread if it is paused
732 // ask the thread to terminate
735 wxCriticalSectionLocker
lock(cs
);
741 // now wait for thread to finish
742 if ( wxThread::IsMain() )
744 // set flag for wxIsWaitingForThread()
745 gs_waitingForThread
= true;
748 // we can't just wait for the thread to terminate because it might be
749 // calling some GUI functions and so it will never terminate before we
750 // process the Windows messages that result from these functions
751 // (note that even in console applications we might have to process
752 // messages if we use wxExecute() or timers or ...)
753 DWORD result
wxDUMMY_INITIALIZE(0);
756 if ( wxThread::IsMain() )
758 // give the thread we're waiting for chance to do the GUI call
760 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
766 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits() : NULL
;
769 result
= traits
->WaitForThread(m_hThread
);
771 else // can't wait for the thread
781 wxLogSysError(_("Can not wait for thread termination"));
783 return wxTHREAD_KILLED
;
786 // thread we're waiting for terminated
789 case WAIT_OBJECT_0
+ 1:
790 // new message arrived, process it -- but only if we're the
791 // main thread as we don't support processing messages in
794 // NB: we still must include QS_ALLINPUT even when waiting
795 // in a secondary thread because if it had created some
796 // window somehow (possible not even using wxWidgets)
797 // the system might dead lock then
798 if ( wxThread::IsMain() )
800 if ( traits
&& !traits
->DoMessageFromThreadWait() )
802 // WM_QUIT received: kill the thread
805 return wxTHREAD_KILLED
;
811 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
813 } while ( result
!= WAIT_OBJECT_0
);
815 if ( wxThread::IsMain() )
817 gs_waitingForThread
= false;
821 // although the thread might be already in the EXITED state it might not
822 // have terminated yet and so we are not sure that it has actually
823 // terminated if the "if" above hadn't been taken
826 if ( !::GetExitCodeThread(m_hThread
, &rc
) )
828 wxLogLastError(wxT("GetExitCodeThread"));
830 rc
= THREAD_ERROR_EXIT
;
835 if ( rc
!= STILL_ACTIVE
)
838 // give the other thread some time to terminate, otherwise we may be
844 *pRc
= wxUIntToPtr(rc
);
846 // we don't need the thread handle any more in any case
850 return rc
== THREAD_ERROR_EXIT
? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
853 bool wxThreadInternal::Suspend()
855 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
856 if ( nSuspendCount
== (DWORD
)-1 )
858 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
863 m_state
= STATE_PAUSED
;
868 bool wxThreadInternal::Resume()
870 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
871 if ( nSuspendCount
== (DWORD
)-1 )
873 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
878 // don't change the state from STATE_EXITED because it's special and means
879 // we are going to terminate without running any user code - if we did it,
880 // the code in WaitForTerminate() wouldn't work
881 if ( m_state
!= STATE_EXITED
)
883 m_state
= STATE_RUNNING
;
892 wxThread
*wxThread::This()
894 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
896 // be careful, 0 may be a valid return value as well
897 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
899 wxLogSysError(_("Couldn't get the current thread pointer"));
907 bool wxThread::IsMain()
909 return ::GetCurrentThreadId() == gs_idMainThread
|| gs_idMainThread
== 0;
912 void wxThread::Yield()
914 // 0 argument to Sleep() is special and means to just give away the rest of
919 void wxThread::Sleep(unsigned long milliseconds
)
921 ::Sleep(milliseconds
);
924 int wxThread::GetCPUCount()
929 return si
.dwNumberOfProcessors
;
932 unsigned long wxThread::GetCurrentId()
934 return (unsigned long)::GetCurrentThreadId();
937 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level
))
942 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
944 // ok only for the default one
948 // get system affinity mask first
949 HANDLE hProcess
= ::GetCurrentProcess();
950 DWORD_PTR dwProcMask
, dwSysMask
;
951 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
953 wxLogLastError(_T("GetProcessAffinityMask"));
958 // how many CPUs have we got?
959 if ( dwSysMask
== 1 )
961 // don't bother with all this complicated stuff - on a single
962 // processor system it doesn't make much sense anyhow
966 // calculate the process mask: it's a bit vector with one bit per
967 // processor; we want to schedule the process to run on first level
972 if ( dwSysMask
& bit
)
974 // ok, we can set this bit
977 // another process added
989 // could we set all bits?
992 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
997 // set it: we can't link to SetProcessAffinityMask() because it doesn't
998 // exist in Win9x, use RT binding instead
1000 typedef BOOL (WINAPI
*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD_PTR
);
1002 // can use static var because we're always in the main thread here
1003 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1005 if ( !pfnSetProcessAffinityMask
)
1007 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
1010 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1011 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1014 // we've discovered a MT version of Win9x!
1015 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1016 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1019 if ( !pfnSetProcessAffinityMask
)
1021 // msg given above - do it only once
1025 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1027 wxLogLastError(_T("SetProcessAffinityMask"));
1033 #endif // __WXWINCE__/!__WXWINCE__
1039 wxThread::wxThread(wxThreadKind kind
)
1041 m_internal
= new wxThreadInternal(this);
1043 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1046 wxThread::~wxThread()
1051 // create/start thread
1052 // -------------------
1054 wxThreadError
wxThread::Create(unsigned int stackSize
)
1056 wxCriticalSectionLocker
lock(m_critsect
);
1058 if ( !m_internal
->Create(this, stackSize
) )
1059 return wxTHREAD_NO_RESOURCE
;
1061 return wxTHREAD_NO_ERROR
;
1064 wxThreadError
wxThread::Run()
1066 wxCriticalSectionLocker
lock(m_critsect
);
1068 if ( m_internal
->GetState() != STATE_NEW
)
1070 // actually, it may be almost any state at all, not only STATE_RUNNING
1071 return wxTHREAD_RUNNING
;
1074 // the thread has just been created and is still suspended - let it run
1078 // suspend/resume thread
1079 // ---------------------
1081 wxThreadError
wxThread::Pause()
1083 wxCriticalSectionLocker
lock(m_critsect
);
1085 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1088 wxThreadError
wxThread::Resume()
1090 wxCriticalSectionLocker
lock(m_critsect
);
1092 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1098 wxThread::ExitCode
wxThread::Wait()
1100 ExitCode rc
= (ExitCode
)THREAD_ERROR_EXIT
;
1102 // although under Windows we can wait for any thread, it's an error to
1103 // wait for a detached one in wxWin API
1104 wxCHECK_MSG( !IsDetached(), rc
,
1105 _T("wxThread::Wait(): can't wait for detached thread") );
1107 (void)m_internal
->WaitForTerminate(m_critsect
, &rc
);
1112 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1114 return m_internal
->WaitForTerminate(m_critsect
, pRc
, this);
1117 wxThreadError
wxThread::Kill()
1120 return wxTHREAD_NOT_RUNNING
;
1122 wxThreadError rc
= m_internal
->Kill();
1130 // update the status of the joinable thread
1131 wxCriticalSectionLocker
lock(m_critsect
);
1132 m_internal
->SetState(STATE_EXITED
);
1138 void wxThread::Exit(ExitCode status
)
1148 // update the status of the joinable thread
1149 wxCriticalSectionLocker
lock(m_critsect
);
1150 m_internal
->SetState(STATE_EXITED
);
1153 #ifdef wxUSE_BEGIN_THREAD
1154 _endthreadex(wxPtrToUInt(status
));
1156 ::ExitThread((DWORD
)status
);
1157 #endif // VC++/!VC++
1159 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1165 void wxThread::SetPriority(unsigned int prio
)
1167 wxCriticalSectionLocker
lock(m_critsect
);
1169 m_internal
->SetPriority(prio
);
1172 unsigned int wxThread::GetPriority() const
1174 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1176 return m_internal
->GetPriority();
1179 unsigned long wxThread::GetId() const
1181 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1183 return (unsigned long)m_internal
->GetId();
1186 bool wxThread::IsRunning() const
1188 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1190 return m_internal
->GetState() == STATE_RUNNING
;
1193 bool wxThread::IsAlive() const
1195 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1197 return (m_internal
->GetState() == STATE_RUNNING
) ||
1198 (m_internal
->GetState() == STATE_PAUSED
);
1201 bool wxThread::IsPaused() const
1203 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1205 return m_internal
->GetState() == STATE_PAUSED
;
1208 bool wxThread::TestDestroy()
1210 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1212 return m_internal
->GetState() == STATE_CANCELED
;
1215 // ----------------------------------------------------------------------------
1216 // Automatic initialization for thread module
1217 // ----------------------------------------------------------------------------
1219 class wxThreadModule
: public wxModule
1222 virtual bool OnInit();
1223 virtual void OnExit();
1226 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1229 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1231 bool wxThreadModule::OnInit()
1233 // allocate TLS index for storing the pointer to the current thread
1234 gs_tlsThisThread
= ::TlsAlloc();
1235 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1237 // in normal circumstances it will only happen if all other
1238 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1239 // words, this should never happen
1240 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1245 // main thread doesn't have associated wxThread object, so store 0 in the
1247 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1249 ::TlsFree(gs_tlsThisThread
);
1250 gs_tlsThisThread
= 0xFFFFFFFF;
1252 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1257 gs_critsectWaitingForGui
= new wxCriticalSection();
1259 gs_critsectGui
= new wxCriticalSection();
1260 gs_critsectGui
->Enter();
1262 gs_critsectThreadDelete
= new wxCriticalSection
;
1264 // no error return for GetCurrentThreadId()
1265 gs_idMainThread
= ::GetCurrentThreadId();
1270 void wxThreadModule::OnExit()
1272 if ( !::TlsFree(gs_tlsThisThread
) )
1274 wxLogLastError(wxT("TlsFree failed."));
1277 delete gs_critsectThreadDelete
;
1278 gs_critsectThreadDelete
= NULL
;
1280 if ( gs_critsectGui
)
1282 gs_critsectGui
->Leave();
1283 delete gs_critsectGui
;
1284 gs_critsectGui
= NULL
;
1287 delete gs_critsectWaitingForGui
;
1288 gs_critsectWaitingForGui
= NULL
;
1291 // ----------------------------------------------------------------------------
1292 // under Windows, these functions are implemented using a critical section and
1293 // not a mutex, so the names are a bit confusing
1294 // ----------------------------------------------------------------------------
1296 void wxMutexGuiEnterImpl()
1298 // this would dead lock everything...
1299 wxASSERT_MSG( !wxThread::IsMain(),
1300 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1302 // the order in which we enter the critical sections here is crucial!!
1304 // set the flag telling to the main thread that we want to do some GUI
1306 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1308 gs_nWaitingForGui
++;
1311 wxWakeUpMainThread();
1313 // now we may block here because the main thread will soon let us in
1314 // (during the next iteration of OnIdle())
1315 gs_critsectGui
->Enter();
1318 void wxMutexGuiLeaveImpl()
1320 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1322 if ( wxThread::IsMain() )
1324 gs_bGuiOwnedByMainThread
= false;
1328 // decrement the number of threads waiting for GUI access now
1329 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1330 wxT("calling wxMutexGuiLeave() without entering it first?") );
1332 gs_nWaitingForGui
--;
1334 wxWakeUpMainThread();
1337 gs_critsectGui
->Leave();
1340 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1342 wxASSERT_MSG( wxThread::IsMain(),
1343 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1345 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1347 if ( gs_nWaitingForGui
== 0 )
1349 // no threads are waiting for GUI - so we may acquire the lock without
1350 // any danger (but only if we don't already have it)
1351 if ( !wxGuiOwnedByMainThread() )
1353 gs_critsectGui
->Enter();
1355 gs_bGuiOwnedByMainThread
= true;
1357 //else: already have it, nothing to do
1361 // some threads are waiting, release the GUI lock if we have it
1362 if ( wxGuiOwnedByMainThread() )
1366 //else: some other worker thread is doing GUI
1370 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1372 return gs_bGuiOwnedByMainThread
;
1375 // wake up the main thread if it's in ::GetMessage()
1376 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1378 // sending any message would do - hopefully WM_NULL is harmless enough
1379 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1381 // should never happen
1382 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1386 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1388 return gs_waitingForThread
;
1391 // ----------------------------------------------------------------------------
1392 // include common implementation code
1393 // ----------------------------------------------------------------------------
1395 #include "wx/thrimpl.cpp"
1397 #endif // wxUSE_THREADS