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
;
375 DECLARE_NO_COPY_CLASS(wxConditionInternal
)
378 wxConditionInternal::wxConditionInternal(wxMutex
& mutex
)
385 void wxConditionInternal::Wait()
387 // increment the number of waiters
388 m_mutexNumWaiters
.Lock();
390 m_mutexNumWaiters
.Unlock();
394 // a potential race condition can occur here
396 // after a thread increments nwaiters, and unlocks the mutex and before the
397 // semaphore.Wait() is called, if another thread can cause a signal to be
400 // this race condition is handled by using a semaphore and incrementing the
401 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
402 // can 'remember' signals the race condition will not occur
404 // wait ( if necessary ) and decrement semaphore
410 bool wxConditionInternal::Wait( unsigned long timeout_millis
)
412 m_mutexNumWaiters
.Lock();
414 m_mutexNumWaiters
.Unlock();
418 // a race condition can occur at this point in the code
420 // please see the comments in Wait(), for details
424 bool result
= m_semaphore
.Wait( timeout_millis
);
428 // another potential race condition exists here it is caused when a
429 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
430 // has not yet decremented 'nwaiters'.
432 // at this point if another thread calls signal() then the semaphore
433 // will be incremented, but the waiting thread will miss it.
435 // to handle this particular case, the waiting thread calls
436 // WaitForSingleObject again with a timeout of 0, after locking
437 // 'nwaiters_mutex'. this call does not block because of the zero
438 // timeout, but will allow the waiting thread to catch the missed
440 m_mutexNumWaiters
.Lock();
441 result
= m_semaphore
.Wait( 0 );
449 m_mutexNumWaiters
.Unlock();
457 void wxConditionInternal::Signal()
459 m_mutexNumWaiters
.Lock();
461 if ( m_numWaiters
> 0 )
463 // increment the semaphore by 1
469 m_mutexNumWaiters
.Unlock();
472 void wxConditionInternal::Broadcast()
474 m_mutexNumWaiters
.Lock();
476 while ( m_numWaiters
> 0 )
482 m_mutexNumWaiters
.Unlock();
485 // ----------------------------------------------------------------------------
486 // wxCondition implementation
487 // ----------------------------------------------------------------------------
489 wxCondition::wxCondition(wxMutex
& mutex
)
491 m_internal
= new wxConditionInternal( mutex
);
494 wxCondition::~wxCondition()
499 void wxCondition::Wait()
504 bool wxCondition::Wait( unsigned long timeout_millis
)
506 return m_internal
->Wait(timeout_millis
);
509 void wxCondition::Signal()
511 m_internal
->Signal();
514 void wxCondition::Broadcast()
516 m_internal
->Broadcast();
519 // ----------------------------------------------------------------------------
520 // wxCriticalSection implementation
521 // ----------------------------------------------------------------------------
523 wxCriticalSection::wxCriticalSection()
526 // Done this way to stop warnings during compilation about statement
527 // always being FALSE
528 int csSize
= sizeof(CRITICAL_SECTION
);
529 int bSize
= sizeof(m_buffer
);
530 wxASSERT_MSG( csSize
<= bSize
,
531 _T("must increase buffer size in wx/thread.h") );
534 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
537 wxCriticalSection::~wxCriticalSection()
539 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
542 void wxCriticalSection::Enter()
544 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
547 void wxCriticalSection::Leave()
549 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
552 // ----------------------------------------------------------------------------
553 // wxThread implementation
554 // ----------------------------------------------------------------------------
556 // wxThreadInternal class
557 // ----------------------
559 class wxThreadInternal
566 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
578 if ( !::CloseHandle(m_hThread
) )
580 wxLogLastError(wxT("CloseHandle(thread)"));
587 // create a new (suspended) thread (for the given thread object)
588 bool Create(wxThread
*thread
, unsigned int stackSize
);
590 // suspend/resume/terminate
593 void Cancel() { m_state
= STATE_CANCELED
; }
596 void SetState(wxThreadState state
) { m_state
= state
; }
597 wxThreadState
GetState() const { return m_state
; }
600 void SetPriority(unsigned int priority
);
601 unsigned int GetPriority() const { return m_priority
; }
603 // thread handle and id
604 HANDLE
GetHandle() const { return m_hThread
; }
605 DWORD
GetId() const { return m_tid
; }
608 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
611 HANDLE m_hThread
; // handle of the thread
612 wxThreadState m_state
; // state, see wxThreadState enum
613 unsigned int m_priority
; // thread priority in "wx" units
614 DWORD m_tid
; // thread id
617 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
622 // first of all, check whether we hadn't been cancelled already and don't
623 // start the user code at all then
624 wxThread
*thread
= (wxThread
*)param
;
625 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
627 rc
= (THREAD_RETVAL
)-1;
630 else // do run thread
632 // store the thread object in the TLS
633 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
635 wxLogSysError(_("Can not start thread: error writing TLS."));
640 rc
= (THREAD_RETVAL
)thread
->Entry();
642 // enter m_critsect before changing the thread state
643 thread
->m_critsect
.Enter();
644 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
645 thread
->m_internal
->SetState(STATE_EXITED
);
646 thread
->m_critsect
.Leave();
651 // if the thread was cancelled (from Delete()), then its handle is still
653 if ( thread
->IsDetached() && !wasCancelled
)
658 //else: the joinable threads handle will be closed when Wait() is done
663 void wxThreadInternal::SetPriority(unsigned int priority
)
665 m_priority
= priority
;
667 // translate wxWindows priority to the Windows one
669 if (m_priority
<= 20)
670 win_priority
= THREAD_PRIORITY_LOWEST
;
671 else if (m_priority
<= 40)
672 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
673 else if (m_priority
<= 60)
674 win_priority
= THREAD_PRIORITY_NORMAL
;
675 else if (m_priority
<= 80)
676 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
677 else if (m_priority
<= 100)
678 win_priority
= THREAD_PRIORITY_HIGHEST
;
681 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
682 win_priority
= THREAD_PRIORITY_NORMAL
;
685 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
687 wxLogSysError(_("Can't set thread priority"));
691 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
693 // for compilers which have it, we should use C RTL function for thread
694 // creation instead of Win32 API one because otherwise we will have memory
695 // leaks if the thread uses C RTL (and most threads do)
696 #ifdef wxUSE_BEGIN_THREAD
698 // Watcom is reported to not like 0 stack size (which means "use default"
699 // for the other compilers and is also the default value for stackSize)
703 #endif // __WATCOMC__
705 m_hThread
= (HANDLE
)_beginthreadex
707 NULL
, // default security
709 wxThreadInternal::WinThreadStart
, // entry point
712 (unsigned int *)&m_tid
714 #else // compiler doesn't have _beginthreadex
715 m_hThread
= ::CreateThread
717 NULL
, // default security
718 stackSize
, // stack size
719 wxThreadInternal::WinThreadStart
, // thread entry point
720 (LPVOID
)thread
, // parameter
721 CREATE_SUSPENDED
, // flags
722 &m_tid
// [out] thread id
724 #endif // _beginthreadex/CreateThread
726 if ( m_hThread
== NULL
)
728 wxLogSysError(_("Can't create thread"));
733 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
735 SetPriority(m_priority
);
741 bool wxThreadInternal::Suspend()
743 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
744 if ( nSuspendCount
== (DWORD
)-1 )
746 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
751 m_state
= STATE_PAUSED
;
756 bool wxThreadInternal::Resume()
758 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
759 if ( nSuspendCount
== (DWORD
)-1 )
761 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
766 // don't change the state from STATE_EXITED because it's special and means
767 // we are going to terminate without running any user code - if we did it,
768 // the codei n Delete() wouldn't work
769 if ( m_state
!= STATE_EXITED
)
771 m_state
= STATE_RUNNING
;
780 wxThread
*wxThread::This()
782 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
784 // be careful, 0 may be a valid return value as well
785 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
787 wxLogSysError(_("Couldn't get the current thread pointer"));
795 bool wxThread::IsMain()
797 return ::GetCurrentThreadId() == gs_idMainThread
;
804 void wxThread::Yield()
806 // 0 argument to Sleep() is special and means to just give away the rest of
811 void wxThread::Sleep(unsigned long milliseconds
)
813 ::Sleep(milliseconds
);
816 int wxThread::GetCPUCount()
821 return si
.dwNumberOfProcessors
;
824 unsigned long wxThread::GetCurrentId()
826 return (unsigned long)::GetCurrentThreadId();
829 bool wxThread::SetConcurrency(size_t level
)
831 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
833 // ok only for the default one
837 // get system affinity mask first
838 HANDLE hProcess
= ::GetCurrentProcess();
839 DWORD dwProcMask
, dwSysMask
;
840 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
842 wxLogLastError(_T("GetProcessAffinityMask"));
847 // how many CPUs have we got?
848 if ( dwSysMask
== 1 )
850 // don't bother with all this complicated stuff - on a single
851 // processor system it doesn't make much sense anyhow
855 // calculate the process mask: it's a bit vector with one bit per
856 // processor; we want to schedule the process to run on first level
861 if ( dwSysMask
& bit
)
863 // ok, we can set this bit
866 // another process added
878 // could we set all bits?
881 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
886 // set it: we can't link to SetProcessAffinityMask() because it doesn't
887 // exist in Win9x, use RT binding instead
889 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
891 // can use static var because we're always in the main thread here
892 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
894 if ( !pfnSetProcessAffinityMask
)
896 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
899 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
900 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
903 // we've discovered a MT version of Win9x!
904 wxASSERT_MSG( pfnSetProcessAffinityMask
,
905 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
908 if ( !pfnSetProcessAffinityMask
)
910 // msg given above - do it only once
914 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
916 wxLogLastError(_T("SetProcessAffinityMask"));
927 wxThread::wxThread(wxThreadKind kind
)
929 m_internal
= new wxThreadInternal();
931 m_isDetached
= kind
== wxTHREAD_DETACHED
;
934 wxThread::~wxThread()
939 // create/start thread
940 // -------------------
942 wxThreadError
wxThread::Create(unsigned int stackSize
)
944 wxCriticalSectionLocker
lock(m_critsect
);
946 if ( !m_internal
->Create(this, stackSize
) )
947 return wxTHREAD_NO_RESOURCE
;
949 return wxTHREAD_NO_ERROR
;
952 wxThreadError
wxThread::Run()
954 wxCriticalSectionLocker
lock(m_critsect
);
956 if ( m_internal
->GetState() != STATE_NEW
)
958 // actually, it may be almost any state at all, not only STATE_RUNNING
959 return wxTHREAD_RUNNING
;
962 // the thread has just been created and is still suspended - let it run
966 // suspend/resume thread
967 // ---------------------
969 wxThreadError
wxThread::Pause()
971 wxCriticalSectionLocker
lock(m_critsect
);
973 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
976 wxThreadError
wxThread::Resume()
978 wxCriticalSectionLocker
lock(m_critsect
);
980 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
986 wxThread::ExitCode
wxThread::Wait()
988 // although under Windows we can wait for any thread, it's an error to
989 // wait for a detached one in wxWin API
990 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
991 _T("can't wait for detached thread") );
993 ExitCode rc
= (ExitCode
)-1;
1002 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1006 // Delete() is always safe to call, so consider all possible states
1008 // we might need to resume the thread, but we might also not need to cancel
1009 // it if it doesn't run yet
1010 bool shouldResume
= FALSE
,
1011 shouldCancel
= TRUE
,
1014 // check if the thread already started to run
1016 wxCriticalSectionLocker
lock(m_critsect
);
1018 if ( m_internal
->GetState() == STATE_NEW
)
1020 // WinThreadStart() will see it and terminate immediately, no need
1021 // to cancel the thread - but we still need to resume it to let it
1023 m_internal
->SetState(STATE_EXITED
);
1025 Resume(); // it knows about STATE_EXITED special case
1027 shouldCancel
= FALSE
;
1030 // shouldResume is correctly set to FALSE here
1034 shouldResume
= IsPaused();
1038 // resume the thread if it is paused
1042 HANDLE hThread
= m_internal
->GetHandle();
1044 // does is still run?
1045 if ( isRunning
|| IsRunning() )
1049 // set flag for wxIsWaitingForThread()
1050 gs_waitingForThread
= TRUE
;
1053 wxBeginBusyCursor();
1057 // ask the thread to terminate
1060 wxCriticalSectionLocker
lock(m_critsect
);
1062 m_internal
->Cancel();
1066 // we can't just wait for the thread to terminate because it might be
1067 // calling some GUI functions and so it will never terminate before we
1068 // process the Windows messages that result from these functions
1072 result
= ::MsgWaitForMultipleObjects
1074 1, // number of objects to wait for
1075 &hThread
, // the objects
1076 FALSE
, // don't wait for all objects
1077 INFINITE
, // no timeout
1078 QS_ALLEVENTS
// return as soon as there are any events
1085 wxLogSysError(_("Can not wait for thread termination"));
1087 return wxTHREAD_KILLED
;
1090 // thread we're waiting for terminated
1093 case WAIT_OBJECT_0
+ 1:
1094 // new message arrived, process it
1095 if ( !wxTheApp
->DoMessage() )
1097 // WM_QUIT received: kill the thread
1100 return wxTHREAD_KILLED
;
1105 // give the thread we're waiting for chance to exit
1106 // from the GUI call it might have been in
1107 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1116 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1118 } while ( result
!= WAIT_OBJECT_0
);
1120 // simply wait for the thread to terminate
1122 // OTOH, even console apps create windows (in wxExecute, for WinSock
1123 // &c), so may be use MsgWaitForMultipleObject() too here?
1124 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1126 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1128 #endif // wxUSE_GUI/!wxUSE_GUI
1132 gs_waitingForThread
= FALSE
;
1140 // although the thread might be already in the EXITED state it might not
1141 // have terminated yet and so we are not sure that it has actually
1142 // terminated if the "if" above hadn't been taken
1145 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1147 wxLogLastError(wxT("GetExitCodeThread"));
1151 } while ( (DWORD
)rc
== STILL_ACTIVE
);
1155 // if the thread exits normally, this is done in WinThreadStart, but in
1156 // this case it would have been too early because
1157 // MsgWaitForMultipleObject() would fail if the thread handle was
1158 // closed while we were waiting on it, so we must do it here
1165 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1168 wxThreadError
wxThread::Kill()
1171 return wxTHREAD_NOT_RUNNING
;
1173 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1175 wxLogSysError(_("Couldn't terminate thread"));
1177 return wxTHREAD_MISC_ERROR
;
1187 return wxTHREAD_NO_ERROR
;
1190 void wxThread::Exit(ExitCode status
)
1199 #ifdef wxUSE_BEGIN_THREAD
1200 _endthreadex((unsigned)status
);
1202 ::ExitThread((DWORD
)status
);
1203 #endif // VC++/!VC++
1205 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1211 void wxThread::SetPriority(unsigned int prio
)
1213 wxCriticalSectionLocker
lock(m_critsect
);
1215 m_internal
->SetPriority(prio
);
1218 unsigned int wxThread::GetPriority() const
1220 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1222 return m_internal
->GetPriority();
1225 unsigned long wxThread::GetId() const
1227 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1229 return (unsigned long)m_internal
->GetId();
1232 bool wxThread::IsRunning() const
1234 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1236 return m_internal
->GetState() == STATE_RUNNING
;
1239 bool wxThread::IsAlive() const
1241 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1243 return (m_internal
->GetState() == STATE_RUNNING
) ||
1244 (m_internal
->GetState() == STATE_PAUSED
);
1247 bool wxThread::IsPaused() const
1249 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1251 return m_internal
->GetState() == STATE_PAUSED
;
1254 bool wxThread::TestDestroy()
1256 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1258 return m_internal
->GetState() == STATE_CANCELED
;
1261 // ----------------------------------------------------------------------------
1262 // Automatic initialization for thread module
1263 // ----------------------------------------------------------------------------
1265 class wxThreadModule
: public wxModule
1268 virtual bool OnInit();
1269 virtual void OnExit();
1272 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1275 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1277 bool wxThreadModule::OnInit()
1279 // allocate TLS index for storing the pointer to the current thread
1280 gs_tlsThisThread
= ::TlsAlloc();
1281 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1283 // in normal circumstances it will only happen if all other
1284 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1285 // words, this should never happen
1286 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1291 // main thread doesn't have associated wxThread object, so store 0 in the
1293 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1295 ::TlsFree(gs_tlsThisThread
);
1296 gs_tlsThisThread
= 0xFFFFFFFF;
1298 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1303 gs_critsectWaitingForGui
= new wxCriticalSection();
1305 gs_critsectGui
= new wxCriticalSection();
1306 gs_critsectGui
->Enter();
1308 // no error return for GetCurrentThreadId()
1309 gs_idMainThread
= ::GetCurrentThreadId();
1314 void wxThreadModule::OnExit()
1316 if ( !::TlsFree(gs_tlsThisThread
) )
1318 wxLogLastError(wxT("TlsFree failed."));
1321 if ( gs_critsectGui
)
1323 gs_critsectGui
->Leave();
1324 delete gs_critsectGui
;
1325 gs_critsectGui
= NULL
;
1328 delete gs_critsectWaitingForGui
;
1329 gs_critsectWaitingForGui
= NULL
;
1332 // ----------------------------------------------------------------------------
1333 // under Windows, these functions are implemented using a critical section and
1334 // not a mutex, so the names are a bit confusing
1335 // ----------------------------------------------------------------------------
1337 void WXDLLEXPORT
wxMutexGuiEnter()
1339 // this would dead lock everything...
1340 wxASSERT_MSG( !wxThread::IsMain(),
1341 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1343 // the order in which we enter the critical sections here is crucial!!
1345 // set the flag telling to the main thread that we want to do some GUI
1347 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1349 gs_nWaitingForGui
++;
1352 wxWakeUpMainThread();
1354 // now we may block here because the main thread will soon let us in
1355 // (during the next iteration of OnIdle())
1356 gs_critsectGui
->Enter();
1359 void WXDLLEXPORT
wxMutexGuiLeave()
1361 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1363 if ( wxThread::IsMain() )
1365 gs_bGuiOwnedByMainThread
= FALSE
;
1369 // decrement the number of threads waiting for GUI access now
1370 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1371 wxT("calling wxMutexGuiLeave() without entering it first?") );
1373 gs_nWaitingForGui
--;
1375 wxWakeUpMainThread();
1378 gs_critsectGui
->Leave();
1381 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1383 wxASSERT_MSG( wxThread::IsMain(),
1384 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1386 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1388 if ( gs_nWaitingForGui
== 0 )
1390 // no threads are waiting for GUI - so we may acquire the lock without
1391 // any danger (but only if we don't already have it)
1392 if ( !wxGuiOwnedByMainThread() )
1394 gs_critsectGui
->Enter();
1396 gs_bGuiOwnedByMainThread
= TRUE
;
1398 //else: already have it, nothing to do
1402 // some threads are waiting, release the GUI lock if we have it
1403 if ( wxGuiOwnedByMainThread() )
1407 //else: some other worker thread is doing GUI
1411 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1413 return gs_bGuiOwnedByMainThread
;
1416 // wake up the main thread if it's in ::GetMessage()
1417 void WXDLLEXPORT
wxWakeUpMainThread()
1419 // sending any message would do - hopefully WM_NULL is harmless enough
1420 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1422 // should never happen
1423 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1427 bool WXDLLEXPORT
wxIsWaitingForThread()
1429 return gs_waitingForThread
;
1432 #endif // wxUSE_THREADS