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 /////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "thread.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
24 #if defined(__BORLANDC__)
35 #include "wx/apptrait.h"
37 #include "wx/msw/private.h"
38 #include "wx/msw/missing.h"
40 #include "wx/module.h"
41 #include "wx/thread.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__)
67 #undef wxUSE_BEGIN_THREAD
68 #define wxUSE_BEGIN_THREAD
71 #ifdef wxUSE_BEGIN_THREAD
72 // this is where _beginthreadex() is declared
75 // the return type of the thread function entry point
76 typedef unsigned THREAD_RETVAL
;
78 // the calling convention of the thread function entry point
79 #define THREAD_CALLCONV __stdcall
81 // the settings for CreateThread()
82 typedef DWORD THREAD_RETVAL
;
83 #define THREAD_CALLCONV WINAPI
86 // ----------------------------------------------------------------------------
88 // ----------------------------------------------------------------------------
90 // the possible states of the thread ("=>" shows all possible transitions from
94 STATE_NEW
, // didn't start execution yet (=> RUNNING)
95 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
96 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
97 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
98 STATE_EXITED
// thread is terminating
101 // ----------------------------------------------------------------------------
102 // this module globals
103 // ----------------------------------------------------------------------------
105 // TLS index of the slot where we store the pointer to the current thread
106 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
108 // id of the main thread - the one which can call GUI functions without first
109 // calling wxMutexGuiEnter()
110 static DWORD gs_idMainThread
= 0;
112 // if it's FALSE, some secondary thread is holding the GUI lock
113 static bool gs_bGuiOwnedByMainThread
= TRUE
;
115 // critical section which controls access to all GUI functions: any secondary
116 // thread (i.e. except the main one) must enter this crit section before doing
118 static wxCriticalSection
*gs_critsectGui
= NULL
;
120 // critical section which protects gs_nWaitingForGui variable
121 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
123 // number of threads waiting for GUI in wxMutexGuiEnter()
124 static size_t gs_nWaitingForGui
= 0;
126 // are we waiting for a thread termination?
127 static bool gs_waitingForThread
= FALSE
;
129 // ============================================================================
130 // Windows implementation of thread and related classes
131 // ============================================================================
133 // ----------------------------------------------------------------------------
135 // ----------------------------------------------------------------------------
137 wxCriticalSection::wxCriticalSection()
139 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
140 wxCriticalSectionBufferTooSmall
);
142 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
145 wxCriticalSection::~wxCriticalSection()
147 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
150 void wxCriticalSection::Enter()
152 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
155 void wxCriticalSection::Leave()
157 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
160 // ----------------------------------------------------------------------------
162 // ----------------------------------------------------------------------------
164 class wxMutexInternal
167 wxMutexInternal(wxMutexType mutexType
);
170 bool IsOk() const { return m_mutex
!= NULL
; }
172 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
173 wxMutexError
TryLock() { return LockTimeout(0); }
174 wxMutexError
Unlock();
177 wxMutexError
LockTimeout(DWORD milliseconds
);
181 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
184 // all mutexes are recursive under Win32 so we don't use mutexType
185 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
187 // create a nameless (hence intra process and always private) mutex
188 m_mutex
= ::CreateMutex
190 NULL
, // default secutiry attributes
191 FALSE
, // not initially locked
197 wxLogLastError(_T("CreateMutex()"));
201 wxMutexInternal::~wxMutexInternal()
205 if ( !::CloseHandle(m_mutex
) )
207 wxLogLastError(_T("CloseHandle(mutex)"));
212 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
214 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
215 if ( rc
== WAIT_ABANDONED
)
217 // the previous caller died without releasing the mutex, but now we can
219 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
221 // use 0 timeout, normally we should always get it
222 rc
= ::WaitForSingleObject(m_mutex
, 0);
234 case WAIT_ABANDONED
: // checked for above
236 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
240 wxLogLastError(_T("WaitForSingleObject(mutex)"));
241 return wxMUTEX_MISC_ERROR
;
244 return wxMUTEX_NO_ERROR
;
247 wxMutexError
wxMutexInternal::Unlock()
249 if ( !::ReleaseMutex(m_mutex
) )
251 wxLogLastError(_T("ReleaseMutex()"));
253 return wxMUTEX_MISC_ERROR
;
256 return wxMUTEX_NO_ERROR
;
259 // --------------------------------------------------------------------------
261 // --------------------------------------------------------------------------
263 // a trivial wrapper around Win32 semaphore
264 class wxSemaphoreInternal
267 wxSemaphoreInternal(int initialcount
, int maxcount
);
268 ~wxSemaphoreInternal();
270 bool IsOk() const { return m_semaphore
!= NULL
; }
272 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
274 wxSemaError
TryWait()
276 wxSemaError rc
= WaitTimeout(0);
277 if ( rc
== wxSEMA_TIMEOUT
)
283 wxSemaError
WaitTimeout(unsigned long milliseconds
);
290 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
293 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
297 // make it practically infinite
301 m_semaphore
= ::CreateSemaphore
303 NULL
, // default security attributes
311 wxLogLastError(_T("CreateSemaphore()"));
315 wxSemaphoreInternal::~wxSemaphoreInternal()
319 if ( !::CloseHandle(m_semaphore
) )
321 wxLogLastError(_T("CloseHandle(semaphore)"));
326 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
328 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
333 return wxSEMA_NO_ERROR
;
336 return wxSEMA_TIMEOUT
;
339 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
342 return wxSEMA_MISC_ERROR
;
345 wxSemaError
wxSemaphoreInternal::Post()
347 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
349 wxLogLastError(_T("ReleaseSemaphore"));
351 return wxSEMA_MISC_ERROR
;
354 return wxSEMA_NO_ERROR
;
357 // --------------------------------------------------------------------------
359 // --------------------------------------------------------------------------
361 // Win32 doesn't have explicit support for the POSIX condition variables and
362 // the Win32 events have quite different semantics, so we reimplement the
363 // conditions from scratch using the mutexes and semaphores
364 class wxConditionInternal
367 wxConditionInternal(wxMutex
& mutex
);
369 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
372 wxCondError
WaitTimeout(unsigned long milliseconds
);
374 wxCondError
Signal();
375 wxCondError
Broadcast();
378 // the number of threads currently waiting for this condition
381 // the critical section protecting m_numWaiters
382 wxCriticalSection m_csWaiters
;
385 wxSemaphore m_semaphore
;
388 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
391 // another thread can't access it until we return from ctor, so no need to
392 // protect access to m_numWaiters here
396 wxCondError
wxConditionInternal::Wait()
398 // increment the number of waiters
399 ::InterlockedIncrement(&m_numWaiters
);
403 // a potential race condition can occur here
405 // after a thread increments nwaiters, and unlocks the mutex and before the
406 // semaphore.Wait() is called, if another thread can cause a signal to be
409 // this race condition is handled by using a semaphore and incrementing the
410 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
411 // can 'remember' signals the race condition will not occur
413 // wait ( if necessary ) and decrement semaphore
414 wxSemaError err
= m_semaphore
.Wait();
417 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
420 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
422 ::InterlockedIncrement(&m_numWaiters
);
426 // a race condition can occur at this point in the code
428 // please see the comments in Wait(), for details
430 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
432 if ( err
== wxSEMA_BUSY
)
434 // another potential race condition exists here it is caused when a
435 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
436 // has not yet decremented 'nwaiters'.
438 // at this point if another thread calls signal() then the semaphore
439 // will be incremented, but the waiting thread will miss it.
441 // to handle this particular case, the waiting thread calls
442 // WaitForSingleObject again with a timeout of 0, after locking
443 // 'nwaiters_mutex'. this call does not block because of the zero
444 // timeout, but will allow the waiting thread to catch the missed
446 wxCriticalSectionLocker
lock(m_csWaiters
);
448 err
= m_semaphore
.WaitTimeout(0);
450 if ( err
!= wxSEMA_NO_ERROR
)
458 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
461 wxCondError
wxConditionInternal::Signal()
463 wxCriticalSectionLocker
lock(m_csWaiters
);
465 if ( m_numWaiters
> 0 )
467 // increment the semaphore by 1
468 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
469 return wxCOND_MISC_ERROR
;
474 return wxCOND_NO_ERROR
;
477 wxCondError
wxConditionInternal::Broadcast()
479 wxCriticalSectionLocker
lock(m_csWaiters
);
481 while ( m_numWaiters
> 0 )
483 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
484 return wxCOND_MISC_ERROR
;
489 return wxCOND_NO_ERROR
;
492 // ----------------------------------------------------------------------------
493 // wxThread implementation
494 // ----------------------------------------------------------------------------
496 // wxThreadInternal class
497 // ----------------------
499 class wxThreadInternal
506 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
518 if ( !::CloseHandle(m_hThread
) )
520 wxLogLastError(wxT("CloseHandle(thread)"));
527 // create a new (suspended) thread (for the given thread object)
528 bool Create(wxThread
*thread
, unsigned int stackSize
);
530 // wait for the thread to terminate, either by itself, or by asking it
531 // (politely, this is not Kill()!) to do it
532 wxThreadError
WaitForTerminate(bool shouldCancel
,
533 wxCriticalSection
& cs
,
534 wxThread::ExitCode
*pRc
);
536 // kill the thread unconditionally
537 wxThreadError
Kill();
539 // suspend/resume/terminate
542 void Cancel() { m_state
= STATE_CANCELED
; }
545 void SetState(wxThreadState state
) { m_state
= state
; }
546 wxThreadState
GetState() const { return m_state
; }
549 void SetPriority(unsigned int priority
);
550 unsigned int GetPriority() const { return m_priority
; }
552 // thread handle and id
553 HANDLE
GetHandle() const { return m_hThread
; }
554 DWORD
GetId() const { return m_tid
; }
557 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
560 HANDLE m_hThread
; // handle of the thread
561 wxThreadState m_state
; // state, see wxThreadState enum
562 unsigned int m_priority
; // thread priority in "wx" units
563 DWORD m_tid
; // thread id
565 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
568 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
573 // first of all, check whether we hadn't been cancelled already and don't
574 // start the user code at all then
575 wxThread
*thread
= (wxThread
*)param
;
576 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
578 rc
= (THREAD_RETVAL
)-1;
581 else // do run thread
583 // store the thread object in the TLS
584 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
586 wxLogSysError(_("Can not start thread: error writing TLS."));
591 rc
= (THREAD_RETVAL
)thread
->Entry();
593 // enter m_critsect before changing the thread state
594 thread
->m_critsect
.Enter();
595 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
596 thread
->m_internal
->SetState(STATE_EXITED
);
597 thread
->m_critsect
.Leave();
602 // if the thread was cancelled (from Delete()), then its handle is still
604 if ( thread
->IsDetached() && !wasCancelled
)
609 //else: the joinable threads handle will be closed when Wait() is done
614 void wxThreadInternal::SetPriority(unsigned int priority
)
616 m_priority
= priority
;
618 // translate wxWindows priority to the Windows one
620 if (m_priority
<= 20)
621 win_priority
= THREAD_PRIORITY_LOWEST
;
622 else if (m_priority
<= 40)
623 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
624 else if (m_priority
<= 60)
625 win_priority
= THREAD_PRIORITY_NORMAL
;
626 else if (m_priority
<= 80)
627 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
628 else if (m_priority
<= 100)
629 win_priority
= THREAD_PRIORITY_HIGHEST
;
632 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
633 win_priority
= THREAD_PRIORITY_NORMAL
;
636 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
638 wxLogSysError(_("Can't set thread priority"));
642 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
644 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
645 _T("Create()ing thread twice?") );
647 // for compilers which have it, we should use C RTL function for thread
648 // creation instead of Win32 API one because otherwise we will have memory
649 // leaks if the thread uses C RTL (and most threads do)
650 #ifdef wxUSE_BEGIN_THREAD
652 // Watcom is reported to not like 0 stack size (which means "use default"
653 // for the other compilers and is also the default value for stackSize)
657 #endif // __WATCOMC__
659 m_hThread
= (HANDLE
)_beginthreadex
661 NULL
, // default security
663 wxThreadInternal::WinThreadStart
, // entry point
666 (unsigned int *)&m_tid
668 #else // compiler doesn't have _beginthreadex
669 m_hThread
= ::CreateThread
671 NULL
, // default security
672 stackSize
, // stack size
673 wxThreadInternal::WinThreadStart
, // thread entry point
674 (LPVOID
)thread
, // parameter
675 CREATE_SUSPENDED
, // flags
676 &m_tid
// [out] thread id
678 #endif // _beginthreadex/CreateThread
680 if ( m_hThread
== NULL
)
682 wxLogSysError(_("Can't create thread"));
687 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
689 SetPriority(m_priority
);
695 wxThreadError
wxThreadInternal::Kill()
697 if ( !::TerminateThread(m_hThread
, (DWORD
)-1) )
699 wxLogSysError(_("Couldn't terminate thread"));
701 return wxTHREAD_MISC_ERROR
;
706 return wxTHREAD_NO_ERROR
;
710 wxThreadInternal::WaitForTerminate(bool shouldCancel
,
711 wxCriticalSection
& cs
,
712 wxThread::ExitCode
*pRc
)
714 wxThread::ExitCode rc
= 0;
716 // Delete() is always safe to call, so consider all possible states
718 // we might need to resume the thread, but we might also not need to cancel
719 // it if it doesn't run yet
720 bool shouldResume
= FALSE
,
723 // check if the thread already started to run
725 wxCriticalSectionLocker
lock(cs
);
727 if ( m_state
== STATE_NEW
)
731 // WinThreadStart() will see it and terminate immediately, no need
732 // to cancel the thread - but we still need to resume it to let it
734 m_state
= STATE_EXITED
;
736 Resume(); // it knows about STATE_EXITED special case
738 shouldCancel
= FALSE
;
743 // shouldResume is correctly set to FALSE here
747 shouldResume
= m_state
== STATE_PAUSED
;
751 // resume the thread if it is paused
755 // does is still run?
756 if ( isRunning
|| m_state
== STATE_RUNNING
)
758 if ( wxThread::IsMain() )
760 // set flag for wxIsWaitingForThread()
761 gs_waitingForThread
= TRUE
;
764 // ask the thread to terminate
767 wxCriticalSectionLocker
lock(cs
);
772 // we can't just wait for the thread to terminate because it might be
773 // calling some GUI functions and so it will never terminate before we
774 // process the Windows messages that result from these functions
775 // (note that even in console applications we might have to process
776 // messages if we use wxExecute() or timers or ...)
777 DWORD result
= 0; // suppress warnings from broken compilers
780 if ( wxThread::IsMain() )
782 // give the thread we're waiting for chance to do the GUI call
784 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
790 result
= ::MsgWaitForMultipleObjects
792 1, // number of objects to wait for
793 &m_hThread
, // the objects
794 FALSE
, // don't wait for all objects
795 INFINITE
, // no timeout
796 QS_ALLINPUT
| // return as soon as there are any events
804 wxLogSysError(_("Can not wait for thread termination"));
806 return wxTHREAD_KILLED
;
809 // thread we're waiting for terminated
812 case WAIT_OBJECT_0
+ 1:
813 // new message arrived, process it
815 // it looks that sometimes WAIT_OBJECT_0 + 1 is
816 // returned but there are no messages in the thread
817 // queue -- prevent DoMessageFromThreadWait() from
818 // blocking inside ::GetMessage() forever in this case
819 ::PostMessage(NULL
, WM_NULL
, 0, 0);
821 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
824 if ( traits
&& !traits
->DoMessageFromThreadWait() )
826 // WM_QUIT received: kill the thread
829 return wxTHREAD_KILLED
;
835 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
837 } while ( result
!= WAIT_OBJECT_0
);
839 if ( wxThread::IsMain() )
841 gs_waitingForThread
= FALSE
;
845 // although the thread might be already in the EXITED state it might not
846 // have terminated yet and so we are not sure that it has actually
847 // terminated if the "if" above hadn't been taken
850 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
852 wxLogLastError(wxT("GetExitCodeThread"));
854 rc
= (wxThread::ExitCode
)-1;
856 } while ( (DWORD
)rc
== STILL_ACTIVE
);
861 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
865 bool wxThreadInternal::Suspend()
867 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
868 if ( nSuspendCount
== (DWORD
)-1 )
870 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
875 m_state
= STATE_PAUSED
;
880 bool wxThreadInternal::Resume()
882 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
883 if ( nSuspendCount
== (DWORD
)-1 )
885 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
890 // don't change the state from STATE_EXITED because it's special and means
891 // we are going to terminate without running any user code - if we did it,
892 // the codei n Delete() wouldn't work
893 if ( m_state
!= STATE_EXITED
)
895 m_state
= STATE_RUNNING
;
904 wxThread
*wxThread::This()
906 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
908 // be careful, 0 may be a valid return value as well
909 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
911 wxLogSysError(_("Couldn't get the current thread pointer"));
919 bool wxThread::IsMain()
921 return ::GetCurrentThreadId() == gs_idMainThread
;
928 void wxThread::Yield()
930 // 0 argument to Sleep() is special and means to just give away the rest of
935 void wxThread::Sleep(unsigned long milliseconds
)
937 ::Sleep(milliseconds
);
940 int wxThread::GetCPUCount()
945 return si
.dwNumberOfProcessors
;
948 unsigned long wxThread::GetCurrentId()
950 return (unsigned long)::GetCurrentThreadId();
953 bool wxThread::SetConcurrency(size_t level
)
955 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
957 // ok only for the default one
961 // get system affinity mask first
962 HANDLE hProcess
= ::GetCurrentProcess();
963 DWORD dwProcMask
, dwSysMask
;
964 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
966 wxLogLastError(_T("GetProcessAffinityMask"));
971 // how many CPUs have we got?
972 if ( dwSysMask
== 1 )
974 // don't bother with all this complicated stuff - on a single
975 // processor system it doesn't make much sense anyhow
979 // calculate the process mask: it's a bit vector with one bit per
980 // processor; we want to schedule the process to run on first level
985 if ( dwSysMask
& bit
)
987 // ok, we can set this bit
990 // another process added
1002 // could we set all bits?
1005 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
1010 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1011 // exist in Win9x, use RT binding instead
1013 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
1015 // can use static var because we're always in the main thread here
1016 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1018 if ( !pfnSetProcessAffinityMask
)
1020 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
1023 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1024 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1027 // we've discovered a MT version of Win9x!
1028 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1029 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1032 if ( !pfnSetProcessAffinityMask
)
1034 // msg given above - do it only once
1038 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1040 wxLogLastError(_T("SetProcessAffinityMask"));
1051 wxThread::wxThread(wxThreadKind kind
)
1053 m_internal
= new wxThreadInternal();
1055 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1058 wxThread::~wxThread()
1063 // create/start thread
1064 // -------------------
1066 wxThreadError
wxThread::Create(unsigned int stackSize
)
1068 wxCriticalSectionLocker
lock(m_critsect
);
1070 if ( !m_internal
->Create(this, stackSize
) )
1071 return wxTHREAD_NO_RESOURCE
;
1073 return wxTHREAD_NO_ERROR
;
1076 wxThreadError
wxThread::Run()
1078 wxCriticalSectionLocker
lock(m_critsect
);
1080 if ( m_internal
->GetState() != STATE_NEW
)
1082 // actually, it may be almost any state at all, not only STATE_RUNNING
1083 return wxTHREAD_RUNNING
;
1086 // the thread has just been created and is still suspended - let it run
1090 // suspend/resume thread
1091 // ---------------------
1093 wxThreadError
wxThread::Pause()
1095 wxCriticalSectionLocker
lock(m_critsect
);
1097 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1100 wxThreadError
wxThread::Resume()
1102 wxCriticalSectionLocker
lock(m_critsect
);
1104 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1110 wxThread::ExitCode
wxThread::Wait()
1112 // although under Windows we can wait for any thread, it's an error to
1113 // wait for a detached one in wxWin API
1114 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1115 _T("wxThread::Wait(): can't wait for detached thread") );
1117 ExitCode rc
= (ExitCode
)-1;
1119 (void)m_internal
->WaitForTerminate(false, m_critsect
, &rc
);
1123 wxCriticalSectionLocker
lock(m_critsect
);
1124 m_internal
->SetState(STATE_EXITED
);
1129 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1131 wxThreadError rc
= m_internal
->WaitForTerminate(true, m_critsect
, pRc
);
1139 // update the status of the joinable thread
1140 wxCriticalSectionLocker
lock(m_critsect
);
1141 m_internal
->SetState(STATE_EXITED
);
1147 wxThreadError
wxThread::Kill()
1150 return wxTHREAD_NOT_RUNNING
;
1152 wxThreadError rc
= m_internal
->Kill();
1160 // update the status of the joinable thread
1161 wxCriticalSectionLocker
lock(m_critsect
);
1162 m_internal
->SetState(STATE_EXITED
);
1168 void wxThread::Exit(ExitCode status
)
1178 // update the status of the joinable thread
1179 wxCriticalSectionLocker
lock(m_critsect
);
1180 m_internal
->SetState(STATE_EXITED
);
1183 #ifdef wxUSE_BEGIN_THREAD
1184 _endthreadex((unsigned)status
);
1186 ::ExitThread((DWORD
)status
);
1187 #endif // VC++/!VC++
1189 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1195 void wxThread::SetPriority(unsigned int prio
)
1197 wxCriticalSectionLocker
lock(m_critsect
);
1199 m_internal
->SetPriority(prio
);
1202 unsigned int wxThread::GetPriority() const
1204 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1206 return m_internal
->GetPriority();
1209 unsigned long wxThread::GetId() const
1211 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1213 return (unsigned long)m_internal
->GetId();
1216 bool wxThread::IsRunning() const
1218 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1220 return m_internal
->GetState() == STATE_RUNNING
;
1223 bool wxThread::IsAlive() const
1225 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1227 return (m_internal
->GetState() == STATE_RUNNING
) ||
1228 (m_internal
->GetState() == STATE_PAUSED
);
1231 bool wxThread::IsPaused() const
1233 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1235 return m_internal
->GetState() == STATE_PAUSED
;
1238 bool wxThread::TestDestroy()
1240 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1242 return m_internal
->GetState() == STATE_CANCELED
;
1245 // ----------------------------------------------------------------------------
1246 // Automatic initialization for thread module
1247 // ----------------------------------------------------------------------------
1249 class wxThreadModule
: public wxModule
1252 virtual bool OnInit();
1253 virtual void OnExit();
1256 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1259 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1261 bool wxThreadModule::OnInit()
1263 // allocate TLS index for storing the pointer to the current thread
1264 gs_tlsThisThread
= ::TlsAlloc();
1265 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1267 // in normal circumstances it will only happen if all other
1268 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1269 // words, this should never happen
1270 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1275 // main thread doesn't have associated wxThread object, so store 0 in the
1277 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1279 ::TlsFree(gs_tlsThisThread
);
1280 gs_tlsThisThread
= 0xFFFFFFFF;
1282 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1287 gs_critsectWaitingForGui
= new wxCriticalSection();
1289 gs_critsectGui
= new wxCriticalSection();
1290 gs_critsectGui
->Enter();
1292 // no error return for GetCurrentThreadId()
1293 gs_idMainThread
= ::GetCurrentThreadId();
1298 void wxThreadModule::OnExit()
1300 if ( !::TlsFree(gs_tlsThisThread
) )
1302 wxLogLastError(wxT("TlsFree failed."));
1305 if ( gs_critsectGui
)
1307 gs_critsectGui
->Leave();
1308 delete gs_critsectGui
;
1309 gs_critsectGui
= NULL
;
1312 delete gs_critsectWaitingForGui
;
1313 gs_critsectWaitingForGui
= NULL
;
1316 // ----------------------------------------------------------------------------
1317 // under Windows, these functions are implemented using a critical section and
1318 // not a mutex, so the names are a bit confusing
1319 // ----------------------------------------------------------------------------
1321 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1323 // this would dead lock everything...
1324 wxASSERT_MSG( !wxThread::IsMain(),
1325 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1327 // the order in which we enter the critical sections here is crucial!!
1329 // set the flag telling to the main thread that we want to do some GUI
1331 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1333 gs_nWaitingForGui
++;
1336 wxWakeUpMainThread();
1338 // now we may block here because the main thread will soon let us in
1339 // (during the next iteration of OnIdle())
1340 gs_critsectGui
->Enter();
1343 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1345 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1347 if ( wxThread::IsMain() )
1349 gs_bGuiOwnedByMainThread
= FALSE
;
1353 // decrement the number of threads waiting for GUI access now
1354 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1355 wxT("calling wxMutexGuiLeave() without entering it first?") );
1357 gs_nWaitingForGui
--;
1359 wxWakeUpMainThread();
1362 gs_critsectGui
->Leave();
1365 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1367 wxASSERT_MSG( wxThread::IsMain(),
1368 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1370 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1372 if ( gs_nWaitingForGui
== 0 )
1374 // no threads are waiting for GUI - so we may acquire the lock without
1375 // any danger (but only if we don't already have it)
1376 if ( !wxGuiOwnedByMainThread() )
1378 gs_critsectGui
->Enter();
1380 gs_bGuiOwnedByMainThread
= TRUE
;
1382 //else: already have it, nothing to do
1386 // some threads are waiting, release the GUI lock if we have it
1387 if ( wxGuiOwnedByMainThread() )
1391 //else: some other worker thread is doing GUI
1395 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1397 return gs_bGuiOwnedByMainThread
;
1400 // wake up the main thread if it's in ::GetMessage()
1401 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1403 // sending any message would do - hopefully WM_NULL is harmless enough
1404 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1406 // should never happen
1407 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1411 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1413 return gs_waitingForThread
;
1416 // ----------------------------------------------------------------------------
1417 // include common implementation code
1418 // ----------------------------------------------------------------------------
1420 #include "wx/thrimpl.cpp"
1422 #endif // wxUSE_THREADS