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
603 // need to cancel the thread -- but we still need to resume 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
616 else if ( m_state
== STATE_EXITED
)
618 return wxTHREAD_NOT_RUNNING
;
620 else // running (but maybe paused or cancelled)
622 shouldResume
= m_state
== STATE_PAUSED
;
626 // resume the thread if it is paused
630 // is it still running?
631 if ( isRunning
|| m_state
== STATE_RUNNING
)
633 if ( wxThread::IsMain() )
635 // set flag for wxIsWaitingForThread()
636 gs_waitingForThread
= TRUE
;
639 // ask the thread to terminate
642 wxCriticalSectionLocker
lock(cs
);
647 // we can't just wait for the thread to terminate because it might be
648 // calling some GUI functions and so it will never terminate before we
649 // process the Windows messages that result from these functions
650 // (note that even in console applications we might have to process
651 // messages if we use wxExecute() or timers or ...)
652 DWORD result
= 0; // suppress warnings from broken compilers
655 if ( wxThread::IsMain() )
657 // give the thread we're waiting for chance to do the GUI call
659 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
665 result
= ::MsgWaitForMultipleObjects
667 1, // number of objects to wait for
668 &m_hThread
, // the objects
669 FALSE
, // don't wait for all objects
670 INFINITE
, // no timeout
671 QS_ALLINPUT
| // return as soon as there are any events
679 wxLogSysError(_("Can not wait for thread termination"));
681 return wxTHREAD_KILLED
;
684 // thread we're waiting for terminated
687 case WAIT_OBJECT_0
+ 1:
688 // new message arrived, process it -- but only if we're the
689 // main thread as we don't support processing messages in
692 // NB: we still must include QS_ALLINPUT even when waiting
693 // in a secondary thread because if it had created some
694 // window somehow (possible not even using wxWindows)
695 // the system might dead lock then
696 if ( wxThread::IsMain() )
698 // it looks that sometimes WAIT_OBJECT_0 + 1 is
699 // returned but there are no messages in the thread
700 // queue -- prevent DoMessageFromThreadWait() from
701 // blocking inside ::GetMessage() forever in this case
702 ::PostMessage(NULL
, WM_NULL
, 0, 0);
704 wxAppTraits
*traits
= wxTheApp
? wxTheApp
->GetTraits()
707 if ( traits
&& !traits
->DoMessageFromThreadWait() )
709 // WM_QUIT received: kill the thread
712 return wxTHREAD_KILLED
;
718 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
720 } while ( result
!= WAIT_OBJECT_0
);
722 if ( wxThread::IsMain() )
724 gs_waitingForThread
= FALSE
;
728 // although the thread might be already in the EXITED state it might not
729 // have terminated yet and so we are not sure that it has actually
730 // terminated if the "if" above hadn't been taken
733 if ( !::GetExitCodeThread(m_hThread
, (LPDWORD
)&rc
) )
735 wxLogLastError(wxT("GetExitCodeThread"));
737 rc
= (wxThread::ExitCode
)-1;
739 } while ( (DWORD
)rc
== STILL_ACTIVE
);
744 // we don't need the thread handle any more
747 wxCriticalSectionLocker
lock(cs
);
748 SetState(STATE_EXITED
);
750 return rc
== (wxThread::ExitCode
)-1 ? wxTHREAD_MISC_ERROR
754 bool wxThreadInternal::Suspend()
756 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
757 if ( nSuspendCount
== (DWORD
)-1 )
759 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
764 m_state
= STATE_PAUSED
;
769 bool wxThreadInternal::Resume()
771 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
772 if ( nSuspendCount
== (DWORD
)-1 )
774 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
779 // don't change the state from STATE_EXITED because it's special and means
780 // we are going to terminate without running any user code - if we did it,
781 // the codei n Delete() wouldn't work
782 if ( m_state
!= STATE_EXITED
)
784 m_state
= STATE_RUNNING
;
793 wxThread
*wxThread::This()
795 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
797 // be careful, 0 may be a valid return value as well
798 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
800 wxLogSysError(_("Couldn't get the current thread pointer"));
808 bool wxThread::IsMain()
810 return ::GetCurrentThreadId() == gs_idMainThread
;
813 void wxThread::Yield()
815 // 0 argument to Sleep() is special and means to just give away the rest of
820 void wxThread::Sleep(unsigned long milliseconds
)
822 ::Sleep(milliseconds
);
825 int wxThread::GetCPUCount()
830 return si
.dwNumberOfProcessors
;
833 unsigned long wxThread::GetCurrentId()
835 return (unsigned long)::GetCurrentThreadId();
838 bool wxThread::SetConcurrency(size_t level
)
841 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
843 // ok only for the default one
847 // get system affinity mask first
848 HANDLE hProcess
= ::GetCurrentProcess();
849 DWORD dwProcMask
, dwSysMask
;
850 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
852 wxLogLastError(_T("GetProcessAffinityMask"));
857 // how many CPUs have we got?
858 if ( dwSysMask
== 1 )
860 // don't bother with all this complicated stuff - on a single
861 // processor system it doesn't make much sense anyhow
865 // calculate the process mask: it's a bit vector with one bit per
866 // processor; we want to schedule the process to run on first level
871 if ( dwSysMask
& bit
)
873 // ok, we can set this bit
876 // another process added
888 // could we set all bits?
891 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
896 // set it: we can't link to SetProcessAffinityMask() because it doesn't
897 // exist in Win9x, use RT binding instead
899 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
901 // can use static var because we're always in the main thread here
902 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
904 if ( !pfnSetProcessAffinityMask
)
906 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
909 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
910 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
913 // we've discovered a MT version of Win9x!
914 wxASSERT_MSG( pfnSetProcessAffinityMask
,
915 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
918 if ( !pfnSetProcessAffinityMask
)
920 // msg given above - do it only once
924 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
926 wxLogLastError(_T("SetProcessAffinityMask"));
937 wxThread::wxThread(wxThreadKind kind
)
939 m_internal
= new wxThreadInternal();
941 m_isDetached
= kind
== wxTHREAD_DETACHED
;
944 wxThread::~wxThread()
949 // create/start thread
950 // -------------------
952 wxThreadError
wxThread::Create(unsigned int stackSize
)
954 wxCriticalSectionLocker
lock(m_critsect
);
956 if ( !m_internal
->Create(this, stackSize
) )
957 return wxTHREAD_NO_RESOURCE
;
959 return wxTHREAD_NO_ERROR
;
962 wxThreadError
wxThread::Run()
964 wxCriticalSectionLocker
lock(m_critsect
);
966 if ( m_internal
->GetState() != STATE_NEW
)
968 // actually, it may be almost any state at all, not only STATE_RUNNING
969 return wxTHREAD_RUNNING
;
972 // the thread has just been created and is still suspended - let it run
976 // suspend/resume thread
977 // ---------------------
979 wxThreadError
wxThread::Pause()
981 wxCriticalSectionLocker
lock(m_critsect
);
983 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
986 wxThreadError
wxThread::Resume()
988 wxCriticalSectionLocker
lock(m_critsect
);
990 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
996 wxThread::ExitCode
wxThread::Wait()
998 // although under Windows we can wait for any thread, it's an error to
999 // wait for a detached one in wxWin API
1000 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1001 _T("wxThread::Wait(): can't wait for detached thread") );
1003 ExitCode rc
= (ExitCode
)-1;
1005 (void)m_internal
->WaitForTerminate(false, m_critsect
, &rc
);
1010 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1012 return m_internal
->WaitForTerminate(true, m_critsect
, pRc
);
1015 wxThreadError
wxThread::Kill()
1018 return wxTHREAD_NOT_RUNNING
;
1020 wxThreadError rc
= m_internal
->Kill();
1028 // update the status of the joinable thread
1029 wxCriticalSectionLocker
lock(m_critsect
);
1030 m_internal
->SetState(STATE_EXITED
);
1036 void wxThread::Exit(ExitCode status
)
1046 // update the status of the joinable thread
1047 wxCriticalSectionLocker
lock(m_critsect
);
1048 m_internal
->SetState(STATE_EXITED
);
1051 #ifdef wxUSE_BEGIN_THREAD
1052 _endthreadex((unsigned)status
);
1054 ::ExitThread((DWORD
)status
);
1055 #endif // VC++/!VC++
1057 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1063 void wxThread::SetPriority(unsigned int prio
)
1065 wxCriticalSectionLocker
lock(m_critsect
);
1067 m_internal
->SetPriority(prio
);
1070 unsigned int wxThread::GetPriority() const
1072 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1074 return m_internal
->GetPriority();
1077 unsigned long wxThread::GetId() const
1079 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1081 return (unsigned long)m_internal
->GetId();
1084 bool wxThread::IsRunning() const
1086 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1088 return m_internal
->GetState() == STATE_RUNNING
;
1091 bool wxThread::IsAlive() const
1093 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1095 return (m_internal
->GetState() == STATE_RUNNING
) ||
1096 (m_internal
->GetState() == STATE_PAUSED
);
1099 bool wxThread::IsPaused() const
1101 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1103 return m_internal
->GetState() == STATE_PAUSED
;
1106 bool wxThread::TestDestroy()
1108 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1110 return m_internal
->GetState() == STATE_CANCELED
;
1113 // ----------------------------------------------------------------------------
1114 // Automatic initialization for thread module
1115 // ----------------------------------------------------------------------------
1117 class wxThreadModule
: public wxModule
1120 virtual bool OnInit();
1121 virtual void OnExit();
1124 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1127 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1129 bool wxThreadModule::OnInit()
1131 // allocate TLS index for storing the pointer to the current thread
1132 gs_tlsThisThread
= ::TlsAlloc();
1133 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1135 // in normal circumstances it will only happen if all other
1136 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1137 // words, this should never happen
1138 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1143 // main thread doesn't have associated wxThread object, so store 0 in the
1145 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1147 ::TlsFree(gs_tlsThisThread
);
1148 gs_tlsThisThread
= 0xFFFFFFFF;
1150 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1155 gs_critsectWaitingForGui
= new wxCriticalSection();
1157 gs_critsectGui
= new wxCriticalSection();
1158 gs_critsectGui
->Enter();
1160 // no error return for GetCurrentThreadId()
1161 gs_idMainThread
= ::GetCurrentThreadId();
1166 void wxThreadModule::OnExit()
1168 if ( !::TlsFree(gs_tlsThisThread
) )
1170 wxLogLastError(wxT("TlsFree failed."));
1173 if ( gs_critsectGui
)
1175 gs_critsectGui
->Leave();
1176 delete gs_critsectGui
;
1177 gs_critsectGui
= NULL
;
1180 delete gs_critsectWaitingForGui
;
1181 gs_critsectWaitingForGui
= NULL
;
1184 // ----------------------------------------------------------------------------
1185 // under Windows, these functions are implemented using a critical section and
1186 // not a mutex, so the names are a bit confusing
1187 // ----------------------------------------------------------------------------
1189 void WXDLLIMPEXP_BASE
wxMutexGuiEnter()
1191 // this would dead lock everything...
1192 wxASSERT_MSG( !wxThread::IsMain(),
1193 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1195 // the order in which we enter the critical sections here is crucial!!
1197 // set the flag telling to the main thread that we want to do some GUI
1199 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1201 gs_nWaitingForGui
++;
1204 wxWakeUpMainThread();
1206 // now we may block here because the main thread will soon let us in
1207 // (during the next iteration of OnIdle())
1208 gs_critsectGui
->Enter();
1211 void WXDLLIMPEXP_BASE
wxMutexGuiLeave()
1213 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1215 if ( wxThread::IsMain() )
1217 gs_bGuiOwnedByMainThread
= FALSE
;
1221 // decrement the number of threads waiting for GUI access now
1222 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1223 wxT("calling wxMutexGuiLeave() without entering it first?") );
1225 gs_nWaitingForGui
--;
1227 wxWakeUpMainThread();
1230 gs_critsectGui
->Leave();
1233 void WXDLLIMPEXP_BASE
wxMutexGuiLeaveOrEnter()
1235 wxASSERT_MSG( wxThread::IsMain(),
1236 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1238 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1240 if ( gs_nWaitingForGui
== 0 )
1242 // no threads are waiting for GUI - so we may acquire the lock without
1243 // any danger (but only if we don't already have it)
1244 if ( !wxGuiOwnedByMainThread() )
1246 gs_critsectGui
->Enter();
1248 gs_bGuiOwnedByMainThread
= TRUE
;
1250 //else: already have it, nothing to do
1254 // some threads are waiting, release the GUI lock if we have it
1255 if ( wxGuiOwnedByMainThread() )
1259 //else: some other worker thread is doing GUI
1263 bool WXDLLIMPEXP_BASE
wxGuiOwnedByMainThread()
1265 return gs_bGuiOwnedByMainThread
;
1268 // wake up the main thread if it's in ::GetMessage()
1269 void WXDLLIMPEXP_BASE
wxWakeUpMainThread()
1271 // sending any message would do - hopefully WM_NULL is harmless enough
1272 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1274 // should never happen
1275 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1279 bool WXDLLIMPEXP_BASE
wxIsWaitingForThread()
1281 return gs_waitingForThread
;
1284 // ----------------------------------------------------------------------------
1285 // include common implementation code
1286 // ----------------------------------------------------------------------------
1288 #include "wx/thrimpl.cpp"
1290 #endif // wxUSE_THREADS