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 #if defined(__GNUG__) && !defined(NO_GCC_PRAGMA)
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 // ----------------------------------------------------------------------------
364 // wxThread implementation
365 // ----------------------------------------------------------------------------
367 // wxThreadInternal class
368 // ----------------------
370 class wxThreadInternal
377 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
389 if ( !::CloseHandle(m_hThread
) )
391 wxLogLastError(wxT("CloseHandle(thread)"));
398 // create a new (suspended) thread (for the given thread object)
399 bool Create(wxThread
*thread
, unsigned int stackSize
);
401 // wait for the thread to terminate, either by itself, or by asking it
402 // (politely, this is not Kill()!) to do it
403 wxThreadError
WaitForTerminate(bool shouldCancel
,
404 wxCriticalSection
& cs
,
405 wxThread::ExitCode
*pRc
);
407 // kill the thread unconditionally
408 wxThreadError
Kill();
410 // suspend/resume/terminate
413 void Cancel() { m_state
= STATE_CANCELED
; }
416 void SetState(wxThreadState state
) { m_state
= state
; }
417 wxThreadState
GetState() const { return m_state
; }
420 void SetPriority(unsigned int priority
);
421 unsigned int GetPriority() const { return m_priority
; }
423 // thread handle and id
424 HANDLE
GetHandle() const { return m_hThread
; }
425 DWORD
GetId() const { return m_tid
; }
428 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
431 HANDLE m_hThread
; // handle of the thread
432 wxThreadState m_state
; // state, see wxThreadState enum
433 unsigned int m_priority
; // thread priority in "wx" units
434 DWORD m_tid
; // thread id
436 DECLARE_NO_COPY_CLASS(wxThreadInternal
)
439 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
444 // first of all, check whether we hadn't been cancelled already and don't
445 // start the user code at all then
446 wxThread
*thread
= (wxThread
*)param
;
447 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
449 rc
= (THREAD_RETVAL
)-1;
452 else // do run thread
454 // store the thread object in the TLS
455 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
457 wxLogSysError(_("Can not start thread: error writing TLS."));
462 rc
= (THREAD_RETVAL
)thread
->Entry();
464 // enter m_critsect before changing the thread state
465 thread
->m_critsect
.Enter();
466 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
467 thread
->m_internal
->SetState(STATE_EXITED
);
468 thread
->m_critsect
.Leave();
473 // if the thread was cancelled (from Delete()), then its handle is still
475 if ( thread
->IsDetached() && !wasCancelled
)
480 //else: the joinable threads handle will be closed when Wait() is done
485 void wxThreadInternal::SetPriority(unsigned int priority
)
487 m_priority
= priority
;
489 // translate wxWindows priority to the Windows one
491 if (m_priority
<= 20)
492 win_priority
= THREAD_PRIORITY_LOWEST
;
493 else if (m_priority
<= 40)
494 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
495 else if (m_priority
<= 60)
496 win_priority
= THREAD_PRIORITY_NORMAL
;
497 else if (m_priority
<= 80)
498 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
499 else if (m_priority
<= 100)
500 win_priority
= THREAD_PRIORITY_HIGHEST
;
503 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
504 win_priority
= THREAD_PRIORITY_NORMAL
;
507 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
509 wxLogSysError(_("Can't set thread priority"));
513 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
515 wxASSERT_MSG( m_state
== STATE_NEW
&& !m_hThread
,
516 _T("Create()ing thread twice?") );
518 // for compilers which have it, we should use C RTL function for thread
519 // creation instead of Win32 API one because otherwise we will have memory
520 // leaks if the thread uses C RTL (and most threads do)
521 #ifdef wxUSE_BEGIN_THREAD
523 // Watcom is reported to not like 0 stack size (which means "use default"
524 // for the other compilers and is also the default value for stackSize)
528 #endif // __WATCOMC__
530 m_hThread
= (HANDLE
)_beginthreadex
532 NULL
, // default security
534 wxThreadInternal::WinThreadStart
, // entry point
537 (unsigned int *)&m_tid
539 #else // compiler doesn't have _beginthreadex
540 m_hThread
= ::CreateThread
542 NULL
, // default security
543 stackSize
, // stack size
544 wxThreadInternal::WinThreadStart
, // thread entry point
545 (LPVOID
)thread
, // parameter
546 CREATE_SUSPENDED
, // flags
547 &m_tid
// [out] thread id
549 #endif // _beginthreadex/CreateThread
551 if ( m_hThread
== NULL
)
553 wxLogSysError(_("Can't create thread"));
558 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
560 SetPriority(m_priority
);
566 wxThreadError
wxThreadInternal::Kill()
568 if ( !::TerminateThread(m_hThread
, (DWORD
)-1) )
570 wxLogSysError(_("Couldn't terminate thread"));
572 return wxTHREAD_MISC_ERROR
;
577 return wxTHREAD_NO_ERROR
;
581 wxThreadInternal::WaitForTerminate(bool shouldCancel
,
582 wxCriticalSection
& cs
,
583 wxThread::ExitCode
*pRc
)
585 wxThread::ExitCode rc
= 0;
587 // Delete() is always safe to call, so consider all possible states
589 // we might need to resume the thread, but we might also not need to cancel
590 // it if it doesn't run yet
591 bool shouldResume
= FALSE
,
594 // check if the thread already started to run
596 wxCriticalSectionLocker
lock(cs
);
598 if ( m_state
== STATE_NEW
)
602 // WinThreadStart() will see it and terminate immediately, no need
603 // to cancel the thread - but we still need to resume it to let it
605 m_state
= STATE_EXITED
;
607 Resume(); // it knows about STATE_EXITED special case
609 shouldCancel
= FALSE
;
614 // shouldResume is correctly set to FALSE here
618 shouldResume
= m_state
== STATE_PAUSED
;
622 // resume the thread if it is paused
626 // is it still running?
627 if ( isRunning
|| m_state
== STATE_RUNNING
)
629 if ( wxThread::IsMain() )
631 // set flag for wxIsWaitingForThread()
632 gs_waitingForThread
= TRUE
;
635 // ask the thread to terminate
638 wxCriticalSectionLocker
lock(cs
);
643 // we can't just wait for the thread to terminate because it might be
644 // calling some GUI functions and so it will never terminate before we
645 // process the Windows messages that result from these functions
646 // (note that even in console applications we might have to process
647 // messages if we use wxExecute() or timers or ...)
648 DWORD result
= 0; // suppress warnings from broken compilers
651 if ( wxThread::IsMain() )
653 // give the thread we're waiting for chance to do the GUI call
655 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
661 result
= ::MsgWaitForMultipleObjects
663 1, // number of objects to wait for
664 &m_hThread
, // the objects
665 FALSE
, // don't wait for all objects
666 INFINITE
, // no timeout
667 QS_ALLINPUT
| // return as soon as there are any events
675 wxLogSysError(_("Can not wait for thread termination"));
677 return wxTHREAD_KILLED
;
680 // thread we're waiting for terminated
683 case WAIT_OBJECT_0
+ 1:
684 // new message arrived, process it -- but only if we're the
685 // main thread as we don't support processing messages in
688 // NB: we still must include QS_ALLINPUT even when waiting
689 // in a secondary thread because if it had created some
690 // window somehow (possible not even using wxWindows)
691 // the system might dead lock then
692 if ( wxThread::IsMain() )
694 // it looks that sometimes WAIT_OBJECT_0 + 1 is
695 // returned but there are no messages in the thread
696 // queue -- prevent DoMessageFromThreadWait() from
697 // blocking inside ::GetMessage() forever in this case
698 ::PostMessage(NULL
, WM_NULL
, 0, 0);
700 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
703 if ( traits
&& !traits
->DoMessageFromThreadWait() )
705 // WM_QUIT received: kill the thread
708 return wxTHREAD_KILLED
;
714 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
716 } while ( result
!= WAIT_OBJECT_0
);
718 if ( wxThread::IsMain() )
720 gs_waitingForThread
= FALSE
;
724 // although the thread might be already in the EXITED state it might not
725 // have terminated yet and so we are not sure that it has actually
726 // terminated if the "if" above hadn't been taken
729 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
731 wxLogLastError(wxT("GetExitCodeThread"));
733 rc
= (wxThread::ExitCode
)-1;
735 } while ( (DWORD
)rc
== STILL_ACTIVE
);
740 // we don't need the thread handle any more
743 wxCriticalSectionLocker
lock(cs
);
744 SetState(STATE_EXITED
);
746 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
750 bool wxThreadInternal::Suspend()
752 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
753 if ( nSuspendCount
== (DWORD
)-1 )
755 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
760 m_state
= STATE_PAUSED
;
765 bool wxThreadInternal::Resume()
767 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
768 if ( nSuspendCount
== (DWORD
)-1 )
770 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
775 // don't change the state from STATE_EXITED because it's special and means
776 // we are going to terminate without running any user code - if we did it,
777 // the codei n Delete() wouldn't work
778 if ( m_state
!= STATE_EXITED
)
780 m_state
= STATE_RUNNING
;
789 wxThread
*wxThread::This()
791 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
793 // be careful, 0 may be a valid return value as well
794 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
796 wxLogSysError(_("Couldn't get the current thread pointer"));
804 bool wxThread::IsMain()
806 return ::GetCurrentThreadId() == gs_idMainThread
;
809 void wxThread::Yield()
811 // 0 argument to Sleep() is special and means to just give away the rest of
816 void wxThread::Sleep(unsigned long milliseconds
)
818 ::Sleep(milliseconds
);
821 int wxThread::GetCPUCount()
826 return si
.dwNumberOfProcessors
;
829 unsigned long wxThread::GetCurrentId()
831 return (unsigned long)::GetCurrentThreadId();
834 bool wxThread::SetConcurrency(size_t level
)
837 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
839 // ok only for the default one
843 // get system affinity mask first
844 HANDLE hProcess
= ::GetCurrentProcess();
845 DWORD dwProcMask
, dwSysMask
;
846 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
848 wxLogLastError(_T("GetProcessAffinityMask"));
853 // how many CPUs have we got?
854 if ( dwSysMask
== 1 )
856 // don't bother with all this complicated stuff - on a single
857 // processor system it doesn't make much sense anyhow
861 // calculate the process mask: it's a bit vector with one bit per
862 // processor; we want to schedule the process to run on first level
867 if ( dwSysMask
& bit
)
869 // ok, we can set this bit
872 // another process added
884 // could we set all bits?
887 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
892 // set it: we can't link to SetProcessAffinityMask() because it doesn't
893 // exist in Win9x, use RT binding instead
895 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
897 // can use static var because we're always in the main thread here
898 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
900 if ( !pfnSetProcessAffinityMask
)
902 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
905 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
906 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
909 // we've discovered a MT version of Win9x!
910 wxASSERT_MSG( pfnSetProcessAffinityMask
,
911 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
914 if ( !pfnSetProcessAffinityMask
)
916 // msg given above - do it only once
920 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
922 wxLogLastError(_T("SetProcessAffinityMask"));
933 wxThread::wxThread(wxThreadKind kind
)
935 m_internal
= new wxThreadInternal();
937 m_isDetached
= kind
== wxTHREAD_DETACHED
;
940 wxThread::~wxThread()
945 // create/start thread
946 // -------------------
948 wxThreadError
wxThread::Create(unsigned int stackSize
)
950 wxCriticalSectionLocker
lock(m_critsect
);
952 if ( !m_internal
->Create(this, stackSize
) )
953 return wxTHREAD_NO_RESOURCE
;
955 return wxTHREAD_NO_ERROR
;
958 wxThreadError
wxThread::Run()
960 wxCriticalSectionLocker
lock(m_critsect
);
962 if ( m_internal
->GetState() != STATE_NEW
)
964 // actually, it may be almost any state at all, not only STATE_RUNNING
965 return wxTHREAD_RUNNING
;
968 // the thread has just been created and is still suspended - let it run
972 // suspend/resume thread
973 // ---------------------
975 wxThreadError
wxThread::Pause()
977 wxCriticalSectionLocker
lock(m_critsect
);
979 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
982 wxThreadError
wxThread::Resume()
984 wxCriticalSectionLocker
lock(m_critsect
);
986 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
992 wxThread::ExitCode
wxThread::Wait()
994 // although under Windows we can wait for any thread, it's an error to
995 // wait for a detached one in wxWin API
996 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
997 _T("wxThread::Wait(): can't wait for detached thread") );
999 ExitCode rc
= (ExitCode
)-1;
1001 (void)m_internal
->WaitForTerminate(false, m_critsect
, &rc
);
1006 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1008 return m_internal
->WaitForTerminate(true, m_critsect
, pRc
);
1011 wxThreadError
wxThread::Kill()
1014 return wxTHREAD_NOT_RUNNING
;
1016 wxThreadError rc
= m_internal
->Kill();
1024 // update the status of the joinable thread
1025 wxCriticalSectionLocker
lock(m_critsect
);
1026 m_internal
->SetState(STATE_EXITED
);
1032 void wxThread::Exit(ExitCode status
)
1042 // update the status of the joinable thread
1043 wxCriticalSectionLocker
lock(m_critsect
);
1044 m_internal
->SetState(STATE_EXITED
);
1047 #ifdef wxUSE_BEGIN_THREAD
1048 _endthreadex((unsigned)status
);
1050 ::ExitThread((DWORD
)status
);
1051 #endif // VC++/!VC++
1053 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1059 void wxThread::SetPriority(unsigned int prio
)
1061 wxCriticalSectionLocker
lock(m_critsect
);
1063 m_internal
->SetPriority(prio
);
1066 unsigned int wxThread::GetPriority() const
1068 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1070 return m_internal
->GetPriority();
1073 unsigned long wxThread::GetId() const
1075 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1077 return (unsigned long)m_internal
->GetId();
1080 bool wxThread::IsRunning() const
1082 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1084 return m_internal
->GetState() == STATE_RUNNING
;
1087 bool wxThread::IsAlive() const
1089 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1091 return (m_internal
->GetState() == STATE_RUNNING
) ||
1092 (m_internal
->GetState() == STATE_PAUSED
);
1095 bool wxThread::IsPaused() const
1097 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1099 return m_internal
->GetState() == STATE_PAUSED
;
1102 bool wxThread::TestDestroy()
1104 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1106 return m_internal
->GetState() == STATE_CANCELED
;
1109 // ----------------------------------------------------------------------------
1110 // Automatic initialization for thread module
1111 // ----------------------------------------------------------------------------
1113 class wxThreadModule
: public wxModule
1116 virtual bool OnInit();
1117 virtual void OnExit();
1120 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1123 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1125 bool wxThreadModule::OnInit()
1127 // allocate TLS index for storing the pointer to the current thread
1128 gs_tlsThisThread
= ::TlsAlloc();
1129 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1131 // in normal circumstances it will only happen if all other
1132 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1133 // words, this should never happen
1134 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1139 // main thread doesn't have associated wxThread object, so store 0 in the
1141 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1143 ::TlsFree(gs_tlsThisThread
);
1144 gs_tlsThisThread
= 0xFFFFFFFF;
1146 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1151 gs_critsectWaitingForGui
= new wxCriticalSection();
1153 gs_critsectGui
= new wxCriticalSection();
1154 gs_critsectGui
->Enter();
1156 // no error return for GetCurrentThreadId()
1157 gs_idMainThread
= ::GetCurrentThreadId();
1162 void wxThreadModule::OnExit()
1164 if ( !::TlsFree(gs_tlsThisThread
) )
1166 wxLogLastError(wxT("TlsFree failed."));
1169 if ( gs_critsectGui
)
1171 gs_critsectGui
->Leave();
1172 delete gs_critsectGui
;
1173 gs_critsectGui
= NULL
;
1176 delete gs_critsectWaitingForGui
;
1177 gs_critsectWaitingForGui
= NULL
;
1180 // ----------------------------------------------------------------------------
1181 // under Windows, these functions are implemented using a critical section and
1182 // not a mutex, so the names are a bit confusing
1183 // ----------------------------------------------------------------------------
1185 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1187 // this would dead lock everything...
1188 wxASSERT_MSG( !wxThread::IsMain(),
1189 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1191 // the order in which we enter the critical sections here is crucial!!
1193 // set the flag telling to the main thread that we want to do some GUI
1195 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1197 gs_nWaitingForGui
++;
1200 wxWakeUpMainThread();
1202 // now we may block here because the main thread will soon let us in
1203 // (during the next iteration of OnIdle())
1204 gs_critsectGui
->Enter();
1207 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1209 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1211 if ( wxThread::IsMain() )
1213 gs_bGuiOwnedByMainThread
= FALSE
;
1217 // decrement the number of threads waiting for GUI access now
1218 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1219 wxT("calling wxMutexGuiLeave() without entering it first?") );
1221 gs_nWaitingForGui
--;
1223 wxWakeUpMainThread();
1226 gs_critsectGui
->Leave();
1229 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1231 wxASSERT_MSG( wxThread::IsMain(),
1232 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1234 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1236 if ( gs_nWaitingForGui
== 0 )
1238 // no threads are waiting for GUI - so we may acquire the lock without
1239 // any danger (but only if we don't already have it)
1240 if ( !wxGuiOwnedByMainThread() )
1242 gs_critsectGui
->Enter();
1244 gs_bGuiOwnedByMainThread
= TRUE
;
1246 //else: already have it, nothing to do
1250 // some threads are waiting, release the GUI lock if we have it
1251 if ( wxGuiOwnedByMainThread() )
1255 //else: some other worker thread is doing GUI
1259 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1261 return gs_bGuiOwnedByMainThread
;
1264 // wake up the main thread if it's in ::GetMessage()
1265 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1267 // sending any message would do - hopefully WM_NULL is harmless enough
1268 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1270 // should never happen
1271 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1275 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1277 return gs_waitingForThread
;
1280 // ----------------------------------------------------------------------------
1281 // include common implementation code
1282 // ----------------------------------------------------------------------------
1284 #include "wx/thrimpl.cpp"
1286 #endif // wxUSE_THREADS