1 /////////////////////////////////////////////////////////////////////////////
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)
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__)
34 #include "wx/msw/private.h"
36 #include "wx/module.h"
37 #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__)) || \
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 classes
131 // ============================================================================
133 // ----------------------------------------------------------------------------
134 // wxMutex implementation
135 // ----------------------------------------------------------------------------
137 class wxMutexInternal
142 m_mutex
= ::CreateMutex(NULL
, FALSE
, NULL
);
145 wxLogSysError(_("Can not create mutex"));
149 ~wxMutexInternal() { if ( m_mutex
) ::CloseHandle(m_mutex
); }
157 m_internal
= new wxMutexInternal
;
166 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
172 wxMutexError
wxMutex::Lock()
176 ret
= WaitForSingleObject(m_internal
->m_mutex
, INFINITE
);
187 wxLogSysError(_("Couldn't acquire a mutex lock"));
188 return wxMUTEX_MISC_ERROR
;
192 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
196 return wxMUTEX_NO_ERROR
;
199 wxMutexError
wxMutex::TryLock()
203 ret
= WaitForSingleObject(m_internal
->m_mutex
, 0);
204 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
208 return wxMUTEX_NO_ERROR
;
211 wxMutexError
wxMutex::Unlock()
216 BOOL ret
= ReleaseMutex(m_internal
->m_mutex
);
219 wxLogSysError(_("Couldn't release a mutex"));
220 return wxMUTEX_MISC_ERROR
;
223 return wxMUTEX_NO_ERROR
;
226 // ==========================================================================
228 // ==========================================================================
230 // --------------------------------------------------------------------------
231 // wxSemaphoreInternal
232 // --------------------------------------------------------------------------
234 class wxSemaphoreInternal
237 wxSemaphoreInternal( int initialcount
= 0, int maxcount
= 0 );
238 ~wxSemaphoreInternal();
243 bool Wait( unsigned long timeout_millis
);
251 wxSemaphoreInternal::wxSemaphoreInternal( int initialcount
, int maxcount
)
255 // make it practically infinite
259 m_semaphore
= ::CreateSemaphore( NULL
, initialcount
, maxcount
, NULL
);
262 wxLogLastError(_T("CreateSemaphore()"));
266 wxSemaphoreInternal::~wxSemaphoreInternal()
268 CloseHandle( m_semaphore
);
271 void wxSemaphoreInternal::Wait()
273 if ( ::WaitForSingleObject( m_semaphore
, INFINITE
) != WAIT_OBJECT_0
)
275 wxLogLastError(_T("WaitForSingleObject"));
279 bool wxSemaphoreInternal::TryWait()
284 bool wxSemaphoreInternal::Wait( unsigned long timeout_millis
)
286 DWORD result
= ::WaitForSingleObject( m_semaphore
, timeout_millis
);
297 wxLogLastError(_T("WaitForSingleObject()"));
303 void wxSemaphoreInternal::Post()
305 if ( !::ReleaseSemaphore( m_semaphore
, 1, NULL
) )
307 wxLogLastError(_T("ReleaseSemaphore"));
311 // --------------------------------------------------------------------------
313 // --------------------------------------------------------------------------
315 wxSemaphore::wxSemaphore( int initialcount
, int maxcount
)
317 m_internal
= new wxSemaphoreInternal( initialcount
, maxcount
);
320 wxSemaphore::~wxSemaphore()
325 void wxSemaphore::Wait()
330 bool wxSemaphore::TryWait()
332 return m_internal
->TryWait();
335 bool wxSemaphore::Wait( unsigned long timeout_millis
)
337 return m_internal
->Wait( timeout_millis
);
340 void wxSemaphore::Post()
346 // ==========================================================================
348 // ==========================================================================
350 // --------------------------------------------------------------------------
351 // wxConditionInternal
352 // --------------------------------------------------------------------------
354 class wxConditionInternal
357 wxConditionInternal(wxMutex
& mutex
);
361 bool Wait( unsigned long timeout_millis
);
369 wxMutex m_mutexNumWaiters
;
373 wxSemaphore m_semaphore
;
376 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
383 void wxConditionInternal::Wait()
385 // increment the number of waiters
386 m_mutexNumWaiters
.Lock();
388 m_mutexNumWaiters
.Unlock();
392 // a potential race condition can occur here
394 // after a thread increments nwaiters, and unlocks the mutex and before the
395 // semaphore.Wait() is called, if another thread can cause a signal to be
398 // this race condition is handled by using a semaphore and incrementing the
399 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
400 // can 'remember' signals the race condition will not occur
402 // wait ( if necessary ) and decrement semaphore
408 bool wxConditionInternal::Wait( unsigned long timeout_millis
)
410 m_mutexNumWaiters
.Lock();
412 m_mutexNumWaiters
.Unlock();
416 // a race condition can occur at this point in the code
418 // please see the comments in Wait(), for details
422 bool result
= m_semaphore
.Wait( timeout_millis
);
426 // another potential race condition exists here it is caused when a
427 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
428 // has not yet decremented 'nwaiters'.
430 // at this point if another thread calls signal() then the semaphore
431 // will be incremented, but the waiting thread will miss it.
433 // to handle this particular case, the waiting thread calls
434 // WaitForSingleObject again with a timeout of 0, after locking
435 // 'nwaiters_mutex'. this call does not block because of the zero
436 // timeout, but will allow the waiting thread to catch the missed
438 m_mutexNumWaiters
.Lock();
439 result
= m_semaphore
.Wait( 0 );
447 m_mutexNumWaiters
.Unlock();
455 void wxConditionInternal::Signal()
457 m_mutexNumWaiters
.Lock();
459 if ( m_numWaiters
> 0 )
461 // increment the semaphore by 1
467 m_mutexNumWaiters
.Unlock();
470 void wxConditionInternal::Broadcast()
472 m_mutexNumWaiters
.Lock();
474 while ( m_numWaiters
> 0 )
480 m_mutexNumWaiters
.Unlock();
483 // ----------------------------------------------------------------------------
484 // wxCondition implementation
485 // ----------------------------------------------------------------------------
487 wxCondition::wxCondition(wxMutex
& mutex
)
489 m_internal
= new wxConditionInternal( mutex
);
492 wxCondition::~wxCondition()
497 void wxCondition::Wait()
502 bool wxCondition::Wait( unsigned long timeout_millis
)
504 return m_internal
->Wait(timeout_millis
);
507 void wxCondition::Signal()
509 m_internal
->Signal();
512 void wxCondition::Broadcast()
514 m_internal
->Broadcast();
517 // ----------------------------------------------------------------------------
518 // wxCriticalSection implementation
519 // ----------------------------------------------------------------------------
521 wxCriticalSection::wxCriticalSection()
524 // Done this way to stop warnings during compilation about statement
525 // always being FALSE
526 int csSize
= sizeof(CRITICAL_SECTION
);
527 int bSize
= sizeof(m_buffer
);
528 wxASSERT_MSG( csSize
<= bSize
,
529 _T("must increase buffer size in wx/thread.h") );
532 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
535 wxCriticalSection::~wxCriticalSection()
537 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
540 void wxCriticalSection::Enter()
542 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
545 void wxCriticalSection::Leave()
547 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
550 // ----------------------------------------------------------------------------
551 // wxThread implementation
552 // ----------------------------------------------------------------------------
554 // wxThreadInternal class
555 // ----------------------
557 class wxThreadInternal
564 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
576 if ( !::CloseHandle(m_hThread
) )
578 wxLogLastError(wxT("CloseHandle(thread)"));
585 // create a new (suspended) thread (for the given thread object)
586 bool Create(wxThread
*thread
, unsigned int stackSize
);
588 // suspend/resume/terminate
591 void Cancel() { m_state
= STATE_CANCELED
; }
594 void SetState(wxThreadState state
) { m_state
= state
; }
595 wxThreadState
GetState() const { return m_state
; }
598 void SetPriority(unsigned int priority
);
599 unsigned int GetPriority() const { return m_priority
; }
601 // thread handle and id
602 HANDLE
GetHandle() const { return m_hThread
; }
603 DWORD
GetId() const { return m_tid
; }
606 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
609 HANDLE m_hThread
; // handle of the thread
610 wxThreadState m_state
; // state, see wxThreadState enum
611 unsigned int m_priority
; // thread priority in "wx" units
612 DWORD m_tid
; // thread id
615 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
620 // first of all, check whether we hadn't been cancelled already and don't
621 // start the user code at all then
622 wxThread
*thread
= (wxThread
*)param
;
623 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
625 rc
= (THREAD_RETVAL
)-1;
628 else // do run thread
630 // store the thread object in the TLS
631 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
633 wxLogSysError(_("Can not start thread: error writing TLS."));
638 rc
= (THREAD_RETVAL
)thread
->Entry();
640 // enter m_critsect before changing the thread state
641 thread
->m_critsect
.Enter();
642 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
643 thread
->m_internal
->SetState(STATE_EXITED
);
644 thread
->m_critsect
.Leave();
649 // if the thread was cancelled (from Delete()), then its handle is still
651 if ( thread
->IsDetached() && !wasCancelled
)
656 //else: the joinable threads handle will be closed when Wait() is done
661 void wxThreadInternal::SetPriority(unsigned int priority
)
663 m_priority
= priority
;
665 // translate wxWindows priority to the Windows one
667 if (m_priority
<= 20)
668 win_priority
= THREAD_PRIORITY_LOWEST
;
669 else if (m_priority
<= 40)
670 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
671 else if (m_priority
<= 60)
672 win_priority
= THREAD_PRIORITY_NORMAL
;
673 else if (m_priority
<= 80)
674 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
675 else if (m_priority
<= 100)
676 win_priority
= THREAD_PRIORITY_HIGHEST
;
679 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
680 win_priority
= THREAD_PRIORITY_NORMAL
;
683 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
685 wxLogSysError(_("Can't set thread priority"));
689 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
691 // for compilers which have it, we should use C RTL function for thread
692 // creation instead of Win32 API one because otherwise we will have memory
693 // leaks if the thread uses C RTL (and most threads do)
694 #ifdef wxUSE_BEGIN_THREAD
696 // Watcom is reported to not like 0 stack size (which means "use default"
697 // for the other compilers and is also the default value for stackSize)
701 #endif // __WATCOMC__
703 m_hThread
= (HANDLE
)_beginthreadex
705 NULL
, // default security
707 wxThreadInternal::WinThreadStart
, // entry point
710 (unsigned int *)&m_tid
712 #else // compiler doesn't have _beginthreadex
713 m_hThread
= ::CreateThread
715 NULL
, // default security
716 stackSize
, // stack size
717 wxThreadInternal::WinThreadStart
, // thread entry point
718 (LPVOID
)thread
, // parameter
719 CREATE_SUSPENDED
, // flags
720 &m_tid
// [out] thread id
722 #endif // _beginthreadex/CreateThread
724 if ( m_hThread
== NULL
)
726 wxLogSysError(_("Can't create thread"));
731 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
733 SetPriority(m_priority
);
739 bool wxThreadInternal::Suspend()
741 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
742 if ( nSuspendCount
== (DWORD
)-1 )
744 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
749 m_state
= STATE_PAUSED
;
754 bool wxThreadInternal::Resume()
756 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
757 if ( nSuspendCount
== (DWORD
)-1 )
759 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
764 // don't change the state from STATE_EXITED because it's special and means
765 // we are going to terminate without running any user code - if we did it,
766 // the codei n Delete() wouldn't work
767 if ( m_state
!= STATE_EXITED
)
769 m_state
= STATE_RUNNING
;
778 wxThread
*wxThread::This()
780 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
782 // be careful, 0 may be a valid return value as well
783 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
785 wxLogSysError(_("Couldn't get the current thread pointer"));
793 bool wxThread::IsMain()
795 return ::GetCurrentThreadId() == gs_idMainThread
;
802 void wxThread::Yield()
804 // 0 argument to Sleep() is special and means to just give away the rest of
809 void wxThread::Sleep(unsigned long milliseconds
)
811 ::Sleep(milliseconds
);
814 int wxThread::GetCPUCount()
819 return si
.dwNumberOfProcessors
;
822 unsigned long wxThread::GetCurrentId()
824 return (unsigned long)::GetCurrentThreadId();
827 bool wxThread::SetConcurrency(size_t level
)
829 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
831 // ok only for the default one
835 // get system affinity mask first
836 HANDLE hProcess
= ::GetCurrentProcess();
837 DWORD dwProcMask
, dwSysMask
;
838 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
840 wxLogLastError(_T("GetProcessAffinityMask"));
845 // how many CPUs have we got?
846 if ( dwSysMask
== 1 )
848 // don't bother with all this complicated stuff - on a single
849 // processor system it doesn't make much sense anyhow
853 // calculate the process mask: it's a bit vector with one bit per
854 // processor; we want to schedule the process to run on first level
859 if ( dwSysMask
& bit
)
861 // ok, we can set this bit
864 // another process added
876 // could we set all bits?
879 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
884 // set it: we can't link to SetProcessAffinityMask() because it doesn't
885 // exist in Win9x, use RT binding instead
887 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
889 // can use static var because we're always in the main thread here
890 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
892 if ( !pfnSetProcessAffinityMask
)
894 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
897 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
898 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
901 // we've discovered a MT version of Win9x!
902 wxASSERT_MSG( pfnSetProcessAffinityMask
,
903 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
906 if ( !pfnSetProcessAffinityMask
)
908 // msg given above - do it only once
912 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
914 wxLogLastError(_T("SetProcessAffinityMask"));
925 wxThread::wxThread(wxThreadKind kind
)
927 m_internal
= new wxThreadInternal();
929 m_isDetached
= kind
== wxTHREAD_DETACHED
;
932 wxThread::~wxThread()
937 // create/start thread
938 // -------------------
940 wxThreadError
wxThread::Create(unsigned int stackSize
)
942 wxCriticalSectionLocker
lock(m_critsect
);
944 if ( !m_internal
->Create(this, stackSize
) )
945 return wxTHREAD_NO_RESOURCE
;
947 return wxTHREAD_NO_ERROR
;
950 wxThreadError
wxThread::Run()
952 wxCriticalSectionLocker
lock(m_critsect
);
954 if ( m_internal
->GetState() != STATE_NEW
)
956 // actually, it may be almost any state at all, not only STATE_RUNNING
957 return wxTHREAD_RUNNING
;
960 // the thread has just been created and is still suspended - let it run
964 // suspend/resume thread
965 // ---------------------
967 wxThreadError
wxThread::Pause()
969 wxCriticalSectionLocker
lock(m_critsect
);
971 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
974 wxThreadError
wxThread::Resume()
976 wxCriticalSectionLocker
lock(m_critsect
);
978 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
984 wxThread::ExitCode
wxThread::Wait()
986 // although under Windows we can wait for any thread, it's an error to
987 // wait for a detached one in wxWin API
988 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
989 _T("can't wait for detached thread") );
991 ExitCode rc
= (ExitCode
)-1;
1000 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1004 // Delete() is always safe to call, so consider all possible states
1006 // we might need to resume the thread, but we might also not need to cancel
1007 // it if it doesn't run yet
1008 bool shouldResume
= FALSE
,
1009 shouldCancel
= TRUE
,
1012 // check if the thread already started to run
1014 wxCriticalSectionLocker
lock(m_critsect
);
1016 if ( m_internal
->GetState() == STATE_NEW
)
1018 // WinThreadStart() will see it and terminate immediately, no need
1019 // to cancel the thread - but we still need to resume it to let it
1021 m_internal
->SetState(STATE_EXITED
);
1023 Resume(); // it knows about STATE_EXITED special case
1025 shouldCancel
= FALSE
;
1028 // shouldResume is correctly set to FALSE here
1032 shouldResume
= IsPaused();
1036 // resume the thread if it is paused
1040 HANDLE hThread
= m_internal
->GetHandle();
1042 // does is still run?
1043 if ( isRunning
|| IsRunning() )
1047 // set flag for wxIsWaitingForThread()
1048 gs_waitingForThread
= TRUE
;
1051 wxBeginBusyCursor();
1055 // ask the thread to terminate
1058 wxCriticalSectionLocker
lock(m_critsect
);
1060 m_internal
->Cancel();
1064 // we can't just wait for the thread to terminate because it might be
1065 // calling some GUI functions and so it will never terminate before we
1066 // process the Windows messages that result from these functions
1070 result
= ::MsgWaitForMultipleObjects
1072 1, // number of objects to wait for
1073 &hThread
, // the objects
1074 FALSE
, // don't wait for all objects
1075 INFINITE
, // no timeout
1076 QS_ALLEVENTS
// return as soon as there are any events
1083 wxLogSysError(_("Can not wait for thread termination"));
1085 return wxTHREAD_KILLED
;
1088 // thread we're waiting for terminated
1091 case WAIT_OBJECT_0
+ 1:
1092 // new message arrived, process it
1093 if ( !wxTheApp
->DoMessage() )
1095 // WM_QUIT received: kill the thread
1098 return wxTHREAD_KILLED
;
1103 // give the thread we're waiting for chance to exit
1104 // from the GUI call it might have been in
1105 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1114 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1116 } while ( result
!= WAIT_OBJECT_0
);
1118 // simply wait for the thread to terminate
1120 // OTOH, even console apps create windows (in wxExecute, for WinSock
1121 // &c), so may be use MsgWaitForMultipleObject() too here?
1122 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1124 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1126 #endif // wxUSE_GUI/!wxUSE_GUI
1130 gs_waitingForThread
= FALSE
;
1138 // although the thread might be already in the EXITED state it might not
1139 // have terminated yet and so we are not sure that it has actually
1140 // terminated if the "if" above hadn't been taken
1143 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1145 wxLogLastError(wxT("GetExitCodeThread"));
1149 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1153 // if the thread exits normally, this is done in WinThreadStart, but in
1154 // this case it would have been too early because
1155 // MsgWaitForMultipleObject() would fail if the thread handle was
1156 // closed while we were waiting on it, so we must do it here
1163 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1166 wxThreadError
wxThread::Kill()
1169 return wxTHREAD_NOT_RUNNING
;
1171 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1173 wxLogSysError(_("Couldn't terminate thread"));
1175 return wxTHREAD_MISC_ERROR
;
1185 return wxTHREAD_NO_ERROR
;
1188 void wxThread::Exit(ExitCode status
)
1197 #ifdef wxUSE_BEGIN_THREAD
1198 _endthreadex((unsigned)status
);
1200 ::ExitThread((DWORD
)status
);
1201 #endif // VC++/!VC++
1203 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1209 void wxThread::SetPriority(unsigned int prio
)
1211 wxCriticalSectionLocker
lock(m_critsect
);
1213 m_internal
->SetPriority(prio
);
1216 unsigned int wxThread::GetPriority() const
1218 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1220 return m_internal
->GetPriority();
1223 unsigned long wxThread::GetId() const
1225 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1227 return (unsigned long)m_internal
->GetId();
1230 bool wxThread::IsRunning() const
1232 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1234 return m_internal
->GetState() == STATE_RUNNING
;
1237 bool wxThread::IsAlive() const
1239 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1241 return (m_internal
->GetState() == STATE_RUNNING
) ||
1242 (m_internal
->GetState() == STATE_PAUSED
);
1245 bool wxThread::IsPaused() const
1247 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1249 return m_internal
->GetState() == STATE_PAUSED
;
1252 bool wxThread::TestDestroy()
1254 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1256 return m_internal
->GetState() == STATE_CANCELED
;
1259 // ----------------------------------------------------------------------------
1260 // Automatic initialization for thread module
1261 // ----------------------------------------------------------------------------
1263 class wxThreadModule
: public wxModule
1266 virtual bool OnInit();
1267 virtual void OnExit();
1270 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1273 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1275 bool wxThreadModule::OnInit()
1277 // allocate TLS index for storing the pointer to the current thread
1278 gs_tlsThisThread
= ::TlsAlloc();
1279 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1281 // in normal circumstances it will only happen if all other
1282 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1283 // words, this should never happen
1284 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1289 // main thread doesn't have associated wxThread object, so store 0 in the
1291 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1293 ::TlsFree(gs_tlsThisThread
);
1294 gs_tlsThisThread
= 0xFFFFFFFF;
1296 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1301 gs_critsectWaitingForGui
= new wxCriticalSection();
1303 gs_critsectGui
= new wxCriticalSection();
1304 gs_critsectGui
->Enter();
1306 // no error return for GetCurrentThreadId()
1307 gs_idMainThread
= ::GetCurrentThreadId();
1312 void wxThreadModule::OnExit()
1314 if ( !::TlsFree(gs_tlsThisThread
) )
1316 wxLogLastError(wxT("TlsFree failed."));
1319 if ( gs_critsectGui
)
1321 gs_critsectGui
->Leave();
1322 delete gs_critsectGui
;
1323 gs_critsectGui
= NULL
;
1326 delete gs_critsectWaitingForGui
;
1327 gs_critsectWaitingForGui
= NULL
;
1330 // ----------------------------------------------------------------------------
1331 // under Windows, these functions are implemented using a critical section and
1332 // not a mutex, so the names are a bit confusing
1333 // ----------------------------------------------------------------------------
1335 void WXDLLEXPORT
wxMutexGuiEnter()
1337 // this would dead lock everything...
1338 wxASSERT_MSG( !wxThread::IsMain(),
1339 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1341 // the order in which we enter the critical sections here is crucial!!
1343 // set the flag telling to the main thread that we want to do some GUI
1345 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1347 gs_nWaitingForGui
++;
1350 wxWakeUpMainThread();
1352 // now we may block here because the main thread will soon let us in
1353 // (during the next iteration of OnIdle())
1354 gs_critsectGui
->Enter();
1357 void WXDLLEXPORT
wxMutexGuiLeave()
1359 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1361 if ( wxThread::IsMain() )
1363 gs_bGuiOwnedByMainThread
= FALSE
;
1367 // decrement the number of threads waiting for GUI access now
1368 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1369 wxT("calling wxMutexGuiLeave() without entering it first?") );
1371 gs_nWaitingForGui
--;
1373 wxWakeUpMainThread();
1376 gs_critsectGui
->Leave();
1379 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1381 wxASSERT_MSG( wxThread::IsMain(),
1382 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1384 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1386 if ( gs_nWaitingForGui
== 0 )
1388 // no threads are waiting for GUI - so we may acquire the lock without
1389 // any danger (but only if we don't already have it)
1390 if ( !wxGuiOwnedByMainThread() )
1392 gs_critsectGui
->Enter();
1394 gs_bGuiOwnedByMainThread
= TRUE
;
1396 //else: already have it, nothing to do
1400 // some threads are waiting, release the GUI lock if we have it
1401 if ( wxGuiOwnedByMainThread() )
1405 //else: some other worker thread is doing GUI
1409 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1411 return gs_bGuiOwnedByMainThread
;
1414 // wake up the main thread if it's in ::GetMessage()
1415 void WXDLLEXPORT
wxWakeUpMainThread()
1417 // sending any message would do - hopefully WM_NULL is harmless enough
1418 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1420 // should never happen
1421 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1425 bool WXDLLEXPORT
wxIsWaitingForThread()
1427 return gs_waitingForThread
;
1430 #endif // wxUSE_THREADS