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__)
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 unsigned 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 // ----------------------------------------------------------------------------
91 // ----------------------------------------------------------------------------
93 // the possible states of the thread ("=>" shows all possible transitions from
97 STATE_NEW
, // didn't start execution yet (=> RUNNING)
98 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
99 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
100 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
101 STATE_EXITED
// thread is terminating
104 // ----------------------------------------------------------------------------
105 // this module globals
106 // ----------------------------------------------------------------------------
108 // TLS index of the slot where we store the pointer to the current thread
109 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
111 // id of the main thread - the one which can call GUI functions without first
112 // calling wxMutexGuiEnter()
113 static DWORD gs_idMainThread
= 0;
115 // if it's FALSE, some secondary thread is holding the GUI lock
116 static bool gs_bGuiOwnedByMainThread
= TRUE
;
118 // critical section which controls access to all GUI functions: any secondary
119 // thread (i.e. except the main one) must enter this crit section before doing
121 static wxCriticalSection
*gs_critsectGui
= NULL
;
123 // critical section which protects gs_nWaitingForGui variable
124 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
126 // number of threads waiting for GUI in wxMutexGuiEnter()
127 static size_t gs_nWaitingForGui
= 0;
129 // are we waiting for a thread termination?
130 static bool gs_waitingForThread
= FALSE
;
132 // ============================================================================
133 // Windows implementation of thread and related classes
134 // ============================================================================
136 // ----------------------------------------------------------------------------
138 // ----------------------------------------------------------------------------
140 wxCriticalSection::wxCriticalSection()
142 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION
) <= sizeof(wxCritSectBuffer
),
143 wxCriticalSectionBufferTooSmall
);
145 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
148 wxCriticalSection::~wxCriticalSection()
150 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
153 void wxCriticalSection::Enter()
155 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
158 void wxCriticalSection::Leave()
160 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
163 // ----------------------------------------------------------------------------
165 // ----------------------------------------------------------------------------
167 class wxMutexInternal
170 wxMutexInternal(wxMutexType mutexType
);
173 bool IsOk() const { return m_mutex
!= NULL
; }
175 wxMutexError
Lock() { return LockTimeout(INFINITE
); }
176 wxMutexError
TryLock() { return LockTimeout(0); }
177 wxMutexError
Unlock();
180 wxMutexError
LockTimeout(DWORD milliseconds
);
184 DECLARE_NO_COPY_CLASS(wxMutexInternal
)
187 // all mutexes are recursive under Win32 so we don't use mutexType
188 wxMutexInternal::wxMutexInternal(wxMutexType
WXUNUSED(mutexType
))
190 // create a nameless (hence intra process and always private) mutex
191 m_mutex
= ::CreateMutex
193 NULL
, // default secutiry attributes
194 FALSE
, // not initially locked
200 wxLogLastError(_T("CreateMutex()"));
204 wxMutexInternal::~wxMutexInternal()
208 if ( !::CloseHandle(m_mutex
) )
210 wxLogLastError(_T("CloseHandle(mutex)"));
215 wxMutexError
wxMutexInternal::LockTimeout(DWORD milliseconds
)
217 DWORD rc
= ::WaitForSingleObject(m_mutex
, milliseconds
);
218 if ( rc
== WAIT_ABANDONED
)
220 // the previous caller died without releasing the mutex, but now we can
222 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
224 // use 0 timeout, normally we should always get it
225 rc
= ::WaitForSingleObject(m_mutex
, 0);
237 case WAIT_ABANDONED
: // checked for above
239 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
243 wxLogLastError(_T("WaitForSingleObject(mutex)"));
244 return wxMUTEX_MISC_ERROR
;
247 return wxMUTEX_NO_ERROR
;
250 wxMutexError
wxMutexInternal::Unlock()
252 if ( !::ReleaseMutex(m_mutex
) )
254 wxLogLastError(_T("ReleaseMutex()"));
256 return wxMUTEX_MISC_ERROR
;
259 return wxMUTEX_NO_ERROR
;
262 // --------------------------------------------------------------------------
264 // --------------------------------------------------------------------------
266 // a trivial wrapper around Win32 semaphore
267 class wxSemaphoreInternal
270 wxSemaphoreInternal(int initialcount
, int maxcount
);
271 ~wxSemaphoreInternal();
273 bool IsOk() const { return m_semaphore
!= NULL
; }
275 wxSemaError
Wait() { return WaitTimeout(INFINITE
); }
277 wxSemaError
TryWait()
279 wxSemaError rc
= WaitTimeout(0);
280 if ( rc
== wxSEMA_TIMEOUT
)
286 wxSemaError
WaitTimeout(unsigned long milliseconds
);
293 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal
)
296 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount
, int maxcount
)
301 // make it practically infinite
305 m_semaphore
= ::CreateSemaphore
307 NULL
, // default security attributes
315 wxLogLastError(_T("CreateSemaphore()"));
319 wxSemaphoreInternal::~wxSemaphoreInternal()
323 if ( !::CloseHandle(m_semaphore
) )
325 wxLogLastError(_T("CloseHandle(semaphore)"));
330 wxSemaError
wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds
)
332 DWORD rc
= ::WaitForSingleObject( m_semaphore
, milliseconds
);
337 return wxSEMA_NO_ERROR
;
340 return wxSEMA_TIMEOUT
;
343 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
346 return wxSEMA_MISC_ERROR
;
349 wxSemaError
wxSemaphoreInternal::Post()
352 if ( !::ReleaseSemaphore(m_semaphore
, 1, NULL
/* ptr to previous count */) )
355 wxLogLastError(_T("ReleaseSemaphore"));
357 return wxSEMA_MISC_ERROR
;
360 return wxSEMA_NO_ERROR
;
363 // --------------------------------------------------------------------------
365 // --------------------------------------------------------------------------
367 // Win32 doesn't have explicit support for the POSIX condition variables and
368 // the Win32 events have quite different semantics, so we reimplement the
369 // conditions from scratch using the mutexes and semaphores
370 class wxConditionInternal
373 wxConditionInternal(wxMutex
& mutex
);
375 bool IsOk() const { return m_mutex
.IsOk() && m_semaphore
.IsOk(); }
378 wxCondError
WaitTimeout(unsigned long milliseconds
);
380 wxCondError
Signal();
381 wxCondError
Broadcast();
384 // the number of threads currently waiting for this condition
387 // the critical section protecting m_numWaiters
388 wxCriticalSection m_csWaiters
;
391 wxSemaphore m_semaphore
;
394 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
397 // another thread can't access it until we return from ctor, so no need to
398 // protect access to m_numWaiters here
402 wxCondError
wxConditionInternal::Wait()
404 // increment the number of waiters
405 ::InterlockedIncrement(&m_numWaiters
);
409 // a potential race condition can occur here
411 // after a thread increments nwaiters, and unlocks the mutex and before the
412 // semaphore.Wait() is called, if another thread can cause a signal to be
415 // this race condition is handled by using a semaphore and incrementing the
416 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
417 // can 'remember' signals the race condition will not occur
419 // wait ( if necessary ) and decrement semaphore
420 wxSemaError err
= m_semaphore
.Wait();
423 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
426 wxCondError
wxConditionInternal::WaitTimeout(unsigned long milliseconds
)
428 ::InterlockedIncrement(&m_numWaiters
);
432 // a race condition can occur at this point in the code
434 // please see the comments in Wait(), for details
436 wxSemaError err
= m_semaphore
.WaitTimeout(milliseconds
);
438 if ( err
== wxSEMA_BUSY
)
440 // another potential race condition exists here it is caused when a
441 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
442 // has not yet decremented 'nwaiters'.
444 // at this point if another thread calls signal() then the semaphore
445 // will be incremented, but the waiting thread will miss it.
447 // to handle this particular case, the waiting thread calls
448 // WaitForSingleObject again with a timeout of 0, after locking
449 // 'nwaiters_mutex'. this call does not block because of the zero
450 // timeout, but will allow the waiting thread to catch the missed
452 wxCriticalSectionLocker
lock(m_csWaiters
);
454 err
= m_semaphore
.WaitTimeout(0);
456 if ( err
!= wxSEMA_NO_ERROR
)
464 return err
== wxSEMA_NO_ERROR
? wxCOND_NO_ERROR
: wxCOND_MISC_ERROR
;
467 wxCondError
wxConditionInternal::Signal()
469 wxCriticalSectionLocker
lock(m_csWaiters
);
471 if ( m_numWaiters
> 0 )
473 // increment the semaphore by 1
474 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
475 return wxCOND_MISC_ERROR
;
480 return wxCOND_NO_ERROR
;
483 wxCondError
wxConditionInternal::Broadcast()
485 wxCriticalSectionLocker
lock(m_csWaiters
);
487 while ( m_numWaiters
> 0 )
489 if ( m_semaphore
.Post() != wxSEMA_NO_ERROR
)
490 return wxCOND_MISC_ERROR
;
495 return wxCOND_NO_ERROR
;
498 // ----------------------------------------------------------------------------
499 // wxThread implementation
500 // ----------------------------------------------------------------------------
502 // wxThreadInternal class
503 // ----------------------
505 class wxThreadInternal
512 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
524 if ( !::CloseHandle(m_hThread
) )
526 wxLogLastError(wxT("CloseHandle(thread)"));
533 // create a new (suspended) thread (for the given thread object)
534 bool Create(wxThread
*thread
, unsigned int stackSize
);
536 // wait for the thread to terminate, either by itself, or by asking it
537 // (politely, this is not Kill()!) to do it
538 wxThreadError
WaitForTerminate(bool shouldCancel
,
539 wxCriticalSection
& cs
,
540 wxThread::ExitCode
*pRc
);
542 // kill the thread unconditionally
543 wxThreadError
Kill();
545 // suspend/resume/terminate
548 void Cancel() { m_state
= STATE_CANCELED
; }
551 void SetState(wxThreadState state
) { m_state
= state
; }
552 wxThreadState
GetState() const { return m_state
; }
555 void SetPriority(unsigned int priority
);
556 unsigned int GetPriority() const { return m_priority
; }
558 // thread handle and id
559 HANDLE
GetHandle() const { return m_hThread
; }
560 DWORD
GetId() const { return m_tid
; }
563 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
566 HANDLE m_hThread
; // handle of the thread
567 wxThreadState m_state
; // state, see wxThreadState enum
568 unsigned int m_priority
; // thread priority in "wx" units
569 DWORD m_tid
; // thread id
571 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
574 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
579 // first of all, check whether we hadn't been cancelled already and don't
580 // start the user code at all then
581 wxThread
*thread
= (wxThread
*)param
;
582 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
584 rc
= (THREAD_RETVAL
)-1;
587 else // do run thread
589 // store the thread object in the TLS
590 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
592 wxLogSysError(_("Can not start thread: error writing TLS."));
597 rc
= (THREAD_RETVAL
)thread
->Entry();
599 // enter m_critsect before changing the thread state
600 thread
->m_critsect
.Enter();
601 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
602 thread
->m_internal
->SetState(STATE_EXITED
);
603 thread
->m_critsect
.Leave();
608 // if the thread was cancelled (from Delete()), then its handle is still
610 if ( thread
->IsDetached() && !wasCancelled
)
615 //else: the joinable threads handle will be closed when Wait() is done
620 void wxThreadInternal::SetPriority(unsigned int priority
)
622 m_priority
= priority
;
624 // translate wxWindows priority to the Windows one
626 if (m_priority
<= 20)
627 win_priority
= THREAD_PRIORITY_LOWEST
;
628 else if (m_priority
<= 40)
629 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
630 else if (m_priority
<= 60)
631 win_priority
= THREAD_PRIORITY_NORMAL
;
632 else if (m_priority
<= 80)
633 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
634 else if (m_priority
<= 100)
635 win_priority
= THREAD_PRIORITY_HIGHEST
;
638 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
639 win_priority
= THREAD_PRIORITY_NORMAL
;
642 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
644 wxLogSysError(_("Can't set thread priority"));
648 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
650 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
651 _T("Create()ing thread twice?") );
653 // for compilers which have it, we should use C RTL function for thread
654 // creation instead of Win32 API one because otherwise we will have memory
655 // leaks if the thread uses C RTL (and most threads do)
656 #ifdef wxUSE_BEGIN_THREAD
658 // Watcom is reported to not like 0 stack size (which means "use default"
659 // for the other compilers and is also the default value for stackSize)
663 #endif // __WATCOMC__
665 m_hThread
= (HANDLE
)_beginthreadex
667 NULL
, // default security
669 wxThreadInternal::WinThreadStart
, // entry point
672 (unsigned int *)&m_tid
674 #else // compiler doesn't have _beginthreadex
675 m_hThread
= ::CreateThread
677 NULL
, // default security
678 stackSize
, // stack size
679 wxThreadInternal::WinThreadStart
, // thread entry point
680 (LPVOID
)thread
, // parameter
681 CREATE_SUSPENDED
, // flags
682 &m_tid
// [out] thread id
684 #endif // _beginthreadex/CreateThread
686 if ( m_hThread
== NULL
)
688 wxLogSysError(_("Can't create thread"));
693 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
695 SetPriority(m_priority
);
701 wxThreadError
wxThreadInternal::Kill()
703 if ( !::TerminateThread(m_hThread
, (DWORD
)-1) )
705 wxLogSysError(_("Couldn't terminate thread"));
707 return wxTHREAD_MISC_ERROR
;
712 return wxTHREAD_NO_ERROR
;
716 wxThreadInternal::WaitForTerminate(bool shouldCancel
,
717 wxCriticalSection
& cs
,
718 wxThread::ExitCode
*pRc
)
720 wxThread::ExitCode rc
= 0;
722 // Delete() is always safe to call, so consider all possible states
724 // we might need to resume the thread, but we might also not need to cancel
725 // it if it doesn't run yet
726 bool shouldResume
= FALSE
,
729 // check if the thread already started to run
731 wxCriticalSectionLocker
lock(cs
);
733 if ( m_state
== STATE_NEW
)
737 // WinThreadStart() will see it and terminate immediately, no need
738 // to cancel the thread - but we still need to resume it to let it
740 m_state
= STATE_EXITED
;
742 Resume(); // it knows about STATE_EXITED special case
744 shouldCancel
= FALSE
;
749 // shouldResume is correctly set to FALSE here
753 shouldResume
= m_state
== STATE_PAUSED
;
757 // resume the thread if it is paused
761 // does is still run?
762 if ( isRunning
|| m_state
== STATE_RUNNING
)
764 if ( wxThread::IsMain() )
766 // set flag for wxIsWaitingForThread()
767 gs_waitingForThread
= TRUE
;
770 // ask the thread to terminate
773 wxCriticalSectionLocker
lock(cs
);
778 // we can't just wait for the thread to terminate because it might be
779 // calling some GUI functions and so it will never terminate before we
780 // process the Windows messages that result from these functions
781 // (note that even in console applications we might have to process
782 // messages if we use wxExecute() or timers or ...)
783 DWORD result
= 0; // suppress warnings from broken compilers
786 if ( wxThread::IsMain() )
788 // give the thread we're waiting for chance to do the GUI call
790 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
796 result
= ::MsgWaitForMultipleObjects
798 1, // number of objects to wait for
799 &m_hThread
, // the objects
800 FALSE
, // don't wait for all objects
801 INFINITE
, // no timeout
802 QS_ALLINPUT
| // return as soon as there are any events
810 wxLogSysError(_("Can not wait for thread termination"));
812 return wxTHREAD_KILLED
;
815 // thread we're waiting for terminated
818 case WAIT_OBJECT_0
+ 1:
819 // new message arrived, process it
821 // it looks that sometimes WAIT_OBJECT_0 + 1 is
822 // returned but there are no messages in the thread
823 // queue -- prevent DoMessageFromThreadWait() from
824 // blocking inside ::GetMessage() forever in this case
825 ::PostMessage(NULL
, WM_NULL
, 0, 0);
827 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
830 if ( traits
&& !traits
->DoMessageFromThreadWait() )
832 // WM_QUIT received: kill the thread
835 return wxTHREAD_KILLED
;
841 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
843 } while ( result
!= WAIT_OBJECT_0
);
845 if ( wxThread::IsMain() )
847 gs_waitingForThread
= FALSE
;
851 // although the thread might be already in the EXITED state it might not
852 // have terminated yet and so we are not sure that it has actually
853 // terminated if the "if" above hadn't been taken
856 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
858 wxLogLastError(wxT("GetExitCodeThread"));
860 rc
= (wxThread::ExitCode
)-1;
862 } while ( (DWORD
)rc
== STILL_ACTIVE
);
867 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
871 bool wxThreadInternal::Suspend()
873 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
874 if ( nSuspendCount
== (DWORD
)-1 )
876 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
881 m_state
= STATE_PAUSED
;
886 bool wxThreadInternal::Resume()
888 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
889 if ( nSuspendCount
== (DWORD
)-1 )
891 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
896 // don't change the state from STATE_EXITED because it's special and means
897 // we are going to terminate without running any user code - if we did it,
898 // the codei n Delete() wouldn't work
899 if ( m_state
!= STATE_EXITED
)
901 m_state
= STATE_RUNNING
;
910 wxThread
*wxThread::This()
912 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
914 // be careful, 0 may be a valid return value as well
915 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
917 wxLogSysError(_("Couldn't get the current thread pointer"));
925 bool wxThread::IsMain()
927 return ::GetCurrentThreadId() == gs_idMainThread
;
934 void wxThread::Yield()
936 // 0 argument to Sleep() is special and means to just give away the rest of
941 void wxThread::Sleep(unsigned long milliseconds
)
943 ::Sleep(milliseconds
);
946 int wxThread::GetCPUCount()
951 return si
.dwNumberOfProcessors
;
954 unsigned long wxThread::GetCurrentId()
956 return (unsigned long)::GetCurrentThreadId();
959 bool wxThread::SetConcurrency(size_t level
)
962 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
964 // ok only for the default one
968 // get system affinity mask first
969 HANDLE hProcess
= ::GetCurrentProcess();
970 DWORD dwProcMask
, dwSysMask
;
971 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
973 wxLogLastError(_T("GetProcessAffinityMask"));
978 // how many CPUs have we got?
979 if ( dwSysMask
== 1 )
981 // don't bother with all this complicated stuff - on a single
982 // processor system it doesn't make much sense anyhow
986 // calculate the process mask: it's a bit vector with one bit per
987 // processor; we want to schedule the process to run on first level
992 if ( dwSysMask
& bit
)
994 // ok, we can set this bit
997 // another process added
1000 // and that's enough
1009 // could we set all bits?
1012 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
1017 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1018 // exist in Win9x, use RT binding instead
1020 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
1022 // can use static var because we're always in the main thread here
1023 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
1025 if ( !pfnSetProcessAffinityMask
)
1027 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
1030 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
1031 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
1034 // we've discovered a MT version of Win9x!
1035 wxASSERT_MSG( pfnSetProcessAffinityMask
,
1036 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1039 if ( !pfnSetProcessAffinityMask
)
1041 // msg given above - do it only once
1045 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
1047 wxLogLastError(_T("SetProcessAffinityMask"));
1058 wxThread::wxThread(wxThreadKind kind
)
1060 m_internal
= new wxThreadInternal();
1062 m_isDetached
= kind
== wxTHREAD_DETACHED
;
1065 wxThread::~wxThread()
1070 // create/start thread
1071 // -------------------
1073 wxThreadError
wxThread::Create(unsigned int stackSize
)
1075 wxCriticalSectionLocker
lock(m_critsect
);
1077 if ( !m_internal
->Create(this, stackSize
) )
1078 return wxTHREAD_NO_RESOURCE
;
1080 return wxTHREAD_NO_ERROR
;
1083 wxThreadError
wxThread::Run()
1085 wxCriticalSectionLocker
lock(m_critsect
);
1087 if ( m_internal
->GetState() != STATE_NEW
)
1089 // actually, it may be almost any state at all, not only STATE_RUNNING
1090 return wxTHREAD_RUNNING
;
1093 // the thread has just been created and is still suspended - let it run
1097 // suspend/resume thread
1098 // ---------------------
1100 wxThreadError
wxThread::Pause()
1102 wxCriticalSectionLocker
lock(m_critsect
);
1104 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1107 wxThreadError
wxThread::Resume()
1109 wxCriticalSectionLocker
lock(m_critsect
);
1111 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1117 wxThread::ExitCode
wxThread::Wait()
1119 // although under Windows we can wait for any thread, it's an error to
1120 // wait for a detached one in wxWin API
1121 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1122 _T("wxThread::Wait(): can't wait for detached thread") );
1124 ExitCode rc
= (ExitCode
)-1;
1126 (void)m_internal
->WaitForTerminate(false, m_critsect
, &rc
);
1130 wxCriticalSectionLocker
lock(m_critsect
);
1131 m_internal
->SetState(STATE_EXITED
);
1136 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1138 wxThreadError rc
= m_internal
->WaitForTerminate(true, m_critsect
, pRc
);
1146 // update the status of the joinable thread
1147 wxCriticalSectionLocker
lock(m_critsect
);
1148 m_internal
->SetState(STATE_EXITED
);
1154 wxThreadError
wxThread::Kill()
1157 return wxTHREAD_NOT_RUNNING
;
1159 wxThreadError rc
= m_internal
->Kill();
1167 // update the status of the joinable thread
1168 wxCriticalSectionLocker
lock(m_critsect
);
1169 m_internal
->SetState(STATE_EXITED
);
1175 void wxThread::Exit(ExitCode status
)
1185 // update the status of the joinable thread
1186 wxCriticalSectionLocker
lock(m_critsect
);
1187 m_internal
->SetState(STATE_EXITED
);
1190 #ifdef wxUSE_BEGIN_THREAD
1191 _endthreadex((unsigned)status
);
1193 ::ExitThread((DWORD
)status
);
1194 #endif // VC++/!VC++
1196 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1202 void wxThread::SetPriority(unsigned int prio
)
1204 wxCriticalSectionLocker
lock(m_critsect
);
1206 m_internal
->SetPriority(prio
);
1209 unsigned int wxThread::GetPriority() const
1211 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1213 return m_internal
->GetPriority();
1216 unsigned long wxThread::GetId() const
1218 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1220 return (unsigned long)m_internal
->GetId();
1223 bool wxThread::IsRunning() const
1225 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1227 return m_internal
->GetState() == STATE_RUNNING
;
1230 bool wxThread::IsAlive() const
1232 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1234 return (m_internal
->GetState() == STATE_RUNNING
) ||
1235 (m_internal
->GetState() == STATE_PAUSED
);
1238 bool wxThread::IsPaused() const
1240 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1242 return m_internal
->GetState() == STATE_PAUSED
;
1245 bool wxThread::TestDestroy()
1247 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1249 return m_internal
->GetState() == STATE_CANCELED
;
1252 // ----------------------------------------------------------------------------
1253 // Automatic initialization for thread module
1254 // ----------------------------------------------------------------------------
1256 class wxThreadModule
: public wxModule
1259 virtual bool OnInit();
1260 virtual void OnExit();
1263 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1266 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1268 bool wxThreadModule::OnInit()
1270 // allocate TLS index for storing the pointer to the current thread
1271 gs_tlsThisThread
= ::TlsAlloc();
1272 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1274 // in normal circumstances it will only happen if all other
1275 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1276 // words, this should never happen
1277 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1282 // main thread doesn't have associated wxThread object, so store 0 in the
1284 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1286 ::TlsFree(gs_tlsThisThread
);
1287 gs_tlsThisThread
= 0xFFFFFFFF;
1289 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1294 gs_critsectWaitingForGui
= new wxCriticalSection();
1296 gs_critsectGui
= new wxCriticalSection();
1297 gs_critsectGui
->Enter();
1299 // no error return for GetCurrentThreadId()
1300 gs_idMainThread
= ::GetCurrentThreadId();
1305 void wxThreadModule::OnExit()
1307 if ( !::TlsFree(gs_tlsThisThread
) )
1309 wxLogLastError(wxT("TlsFree failed."));
1312 if ( gs_critsectGui
)
1314 gs_critsectGui
->Leave();
1315 delete gs_critsectGui
;
1316 gs_critsectGui
= NULL
;
1319 delete gs_critsectWaitingForGui
;
1320 gs_critsectWaitingForGui
= NULL
;
1323 // ----------------------------------------------------------------------------
1324 // under Windows, these functions are implemented using a critical section and
1325 // not a mutex, so the names are a bit confusing
1326 // ----------------------------------------------------------------------------
1328 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1330 // this would dead lock everything...
1331 wxASSERT_MSG( !wxThread::IsMain(),
1332 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1334 // the order in which we enter the critical sections here is crucial!!
1336 // set the flag telling to the main thread that we want to do some GUI
1338 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1340 gs_nWaitingForGui
++;
1343 wxWakeUpMainThread();
1345 // now we may block here because the main thread will soon let us in
1346 // (during the next iteration of OnIdle())
1347 gs_critsectGui
->Enter();
1350 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1352 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1354 if ( wxThread::IsMain() )
1356 gs_bGuiOwnedByMainThread
= FALSE
;
1360 // decrement the number of threads waiting for GUI access now
1361 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1362 wxT("calling wxMutexGuiLeave() without entering it first?") );
1364 gs_nWaitingForGui
--;
1366 wxWakeUpMainThread();
1369 gs_critsectGui
->Leave();
1372 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1374 wxASSERT_MSG( wxThread::IsMain(),
1375 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1377 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1379 if ( gs_nWaitingForGui
== 0 )
1381 // no threads are waiting for GUI - so we may acquire the lock without
1382 // any danger (but only if we don't already have it)
1383 if ( !wxGuiOwnedByMainThread() )
1385 gs_critsectGui
->Enter();
1387 gs_bGuiOwnedByMainThread
= TRUE
;
1389 //else: already have it, nothing to do
1393 // some threads are waiting, release the GUI lock if we have it
1394 if ( wxGuiOwnedByMainThread() )
1398 //else: some other worker thread is doing GUI
1402 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1404 return gs_bGuiOwnedByMainThread
;
1407 // wake up the main thread if it's in ::GetMessage()
1408 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1410 // sending any message would do - hopefully WM_NULL is harmless enough
1411 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1413 // should never happen
1414 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1418 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1420 return gs_waitingForThread
;
1423 // ----------------------------------------------------------------------------
1424 // include common implementation code
1425 // ----------------------------------------------------------------------------
1427 #include "wx/thrimpl.cpp"
1429 #endif // wxUSE_THREADS