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
);
358 ~wxConditionInternal();
362 bool Wait( unsigned long timeout_millis
);
370 wxMutex m_mutexNumWaiters
;
374 wxSemaphore m_semaphore
;
377 wxConditionInternal::wxConditionInternal( wxMutex
*mutex
)
384 wxConditionInternal::~wxConditionInternal()
388 void wxConditionInternal::Wait()
390 // increment the number of waiters
391 m_mutexNumWaiters
.Lock();
393 m_mutexNumWaiters
.Unlock();
397 // a potential race condition can occur here
399 // after a thread increments nwaiters, and unlocks the mutex and before the
400 // semaphore.Wait() is called, if another thread can cause a signal to be
403 // this race condition is handled by using a semaphore and incrementing the
404 // semaphore only if 'nwaiters' is greater that zero since the semaphore,
405 // can 'remember' signals the race condition will not occur
407 // wait ( if necessary ) and decrement semaphore
413 bool wxConditionInternal::Wait( unsigned long timeout_millis
)
415 m_mutexNumWaiters
.Lock();
417 m_mutexNumWaiters
.Unlock();
421 // a race condition can occur at this point in the code
423 // please see the comments in Wait(), for details
427 bool result
= m_semaphore
.Wait( timeout_millis
);
431 // another potential race condition exists here it is caused when a
432 // 'waiting' thread timesout, and returns from WaitForSingleObject, but
433 // has not yet decremented 'nwaiters'.
435 // at this point if another thread calls signal() then the semaphore
436 // will be incremented, but the waiting thread will miss it.
438 // to handle this particular case, the waiting thread calls
439 // WaitForSingleObject again with a timeout of 0, after locking
440 // 'nwaiters_mutex'. this call does not block because of the zero
441 // timeout, but will allow the waiting thread to catch the missed
443 m_mutexNumWaiters
.Lock();
444 result
= m_semaphore
.Wait( 0 );
452 m_mutexNumWaiters
.Unlock();
460 void wxConditionInternal::Signal()
462 m_mutexNumWaiters
.Lock();
464 if ( m_numWaiters
> 0 )
466 // increment the semaphore by 1
472 m_mutexNumWaiters
.Unlock();
475 void wxConditionInternal::Broadcast()
477 m_mutexNumWaiters
.Lock();
479 while ( m_numWaiters
> 0 )
485 m_mutexNumWaiters
.Unlock();
488 // ----------------------------------------------------------------------------
489 // wxCondition implementation
490 // ----------------------------------------------------------------------------
492 wxCondition::wxCondition( wxMutex
*mutex
)
496 wxFAIL_MSG( _T("NULL mutex in wxCondition ctor") );
502 m_internal
= new wxConditionInternal( mutex
);
506 wxCondition::~wxCondition()
511 void wxCondition::Wait()
517 bool wxCondition::Wait( unsigned long timeout_millis
)
519 return m_internal
? m_internal
->Wait(timeout_millis
) : FALSE
;
522 void wxCondition::Signal()
525 m_internal
->Signal();
528 void wxCondition::Broadcast()
531 m_internal
->Broadcast();
534 // ----------------------------------------------------------------------------
535 // wxCriticalSection implementation
536 // ----------------------------------------------------------------------------
538 wxCriticalSection::wxCriticalSection()
541 // Done this way to stop warnings during compilation about statement
542 // always being FALSE
543 int csSize
= sizeof(CRITICAL_SECTION
);
544 int bSize
= sizeof(m_buffer
);
545 wxASSERT_MSG( csSize
<= bSize
,
546 _T("must increase buffer size in wx/thread.h") );
549 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
552 wxCriticalSection::~wxCriticalSection()
554 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
557 void wxCriticalSection::Enter()
559 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
562 void wxCriticalSection::Leave()
564 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
567 // ----------------------------------------------------------------------------
568 // wxThread implementation
569 // ----------------------------------------------------------------------------
571 // wxThreadInternal class
572 // ----------------------
574 class wxThreadInternal
581 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
593 if ( !::CloseHandle(m_hThread
) )
595 wxLogLastError(wxT("CloseHandle(thread)"));
602 // create a new (suspended) thread (for the given thread object)
603 bool Create(wxThread
*thread
, unsigned int stackSize
);
605 // suspend/resume/terminate
608 void Cancel() { m_state
= STATE_CANCELED
; }
611 void SetState(wxThreadState state
) { m_state
= state
; }
612 wxThreadState
GetState() const { return m_state
; }
615 void SetPriority(unsigned int priority
);
616 unsigned int GetPriority() const { return m_priority
; }
618 // thread handle and id
619 HANDLE
GetHandle() const { return m_hThread
; }
620 DWORD
GetId() const { return m_tid
; }
623 static THREAD_RETVAL THREAD_CALLCONV
WinThreadStart(void *thread
);
626 HANDLE m_hThread
; // handle of the thread
627 wxThreadState m_state
; // state, see wxThreadState enum
628 unsigned int m_priority
; // thread priority in "wx" units
629 DWORD m_tid
; // thread id
632 THREAD_RETVAL THREAD_CALLCONV
wxThreadInternal::WinThreadStart(void *param
)
637 // first of all, check whether we hadn't been cancelled already and don't
638 // start the user code at all then
639 wxThread
*thread
= (wxThread
*)param
;
640 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
642 rc
= (THREAD_RETVAL
)-1;
645 else // do run thread
647 // store the thread object in the TLS
648 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
650 wxLogSysError(_("Can not start thread: error writing TLS."));
655 rc
= (THREAD_RETVAL
)thread
->Entry();
657 // enter m_critsect before changing the thread state
658 thread
->m_critsect
.Enter();
659 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
660 thread
->m_internal
->SetState(STATE_EXITED
);
661 thread
->m_critsect
.Leave();
666 // if the thread was cancelled (from Delete()), then its handle is still
668 if ( thread
->IsDetached() && !wasCancelled
)
673 //else: the joinable threads handle will be closed when Wait() is done
678 void wxThreadInternal::SetPriority(unsigned int priority
)
680 m_priority
= priority
;
682 // translate wxWindows priority to the Windows one
684 if (m_priority
<= 20)
685 win_priority
= THREAD_PRIORITY_LOWEST
;
686 else if (m_priority
<= 40)
687 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
688 else if (m_priority
<= 60)
689 win_priority
= THREAD_PRIORITY_NORMAL
;
690 else if (m_priority
<= 80)
691 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
692 else if (m_priority
<= 100)
693 win_priority
= THREAD_PRIORITY_HIGHEST
;
696 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
697 win_priority
= THREAD_PRIORITY_NORMAL
;
700 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
702 wxLogSysError(_("Can't set thread priority"));
706 bool wxThreadInternal::Create(wxThread
*thread
, unsigned int stackSize
)
708 // for compilers which have it, we should use C RTL function for thread
709 // creation instead of Win32 API one because otherwise we will have memory
710 // leaks if the thread uses C RTL (and most threads do)
711 #ifdef wxUSE_BEGIN_THREAD
713 // Watcom is reported to not like 0 stack size (which means "use default"
714 // for the other compilers and is also the default value for stackSize)
718 #endif // __WATCOMC__
720 m_hThread
= (HANDLE
)_beginthreadex
722 NULL
, // default security
724 wxThreadInternal::WinThreadStart
, // entry point
727 (unsigned int *)&m_tid
729 #else // compiler doesn't have _beginthreadex
730 m_hThread
= ::CreateThread
732 NULL
, // default security
733 stackSize
, // stack size
734 wxThreadInternal::WinThreadStart
, // thread entry point
735 (LPVOID
)thread
, // parameter
736 CREATE_SUSPENDED
, // flags
737 &m_tid
// [out] thread id
739 #endif // _beginthreadex/CreateThread
741 if ( m_hThread
== NULL
)
743 wxLogSysError(_("Can't create thread"));
748 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
750 SetPriority(m_priority
);
756 bool wxThreadInternal::Suspend()
758 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
759 if ( nSuspendCount
== (DWORD
)-1 )
761 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
766 m_state
= STATE_PAUSED
;
771 bool wxThreadInternal::Resume()
773 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
774 if ( nSuspendCount
== (DWORD
)-1 )
776 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
781 // don't change the state from STATE_EXITED because it's special and means
782 // we are going to terminate without running any user code - if we did it,
783 // the codei n Delete() wouldn't work
784 if ( m_state
!= STATE_EXITED
)
786 m_state
= STATE_RUNNING
;
795 wxThread
*wxThread::This()
797 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
799 // be careful, 0 may be a valid return value as well
800 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
802 wxLogSysError(_("Couldn't get the current thread pointer"));
810 bool wxThread::IsMain()
812 return ::GetCurrentThreadId() == gs_idMainThread
;
819 void wxThread::Yield()
821 // 0 argument to Sleep() is special and means to just give away the rest of
826 void wxThread::Sleep(unsigned long milliseconds
)
828 ::Sleep(milliseconds
);
831 int wxThread::GetCPUCount()
836 return si
.dwNumberOfProcessors
;
839 unsigned long wxThread::GetCurrentId()
841 return (unsigned long)::GetCurrentThreadId();
844 bool wxThread::SetConcurrency(size_t level
)
846 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
848 // ok only for the default one
852 // get system affinity mask first
853 HANDLE hProcess
= ::GetCurrentProcess();
854 DWORD dwProcMask
, dwSysMask
;
855 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
857 wxLogLastError(_T("GetProcessAffinityMask"));
862 // how many CPUs have we got?
863 if ( dwSysMask
== 1 )
865 // don't bother with all this complicated stuff - on a single
866 // processor system it doesn't make much sense anyhow
870 // calculate the process mask: it's a bit vector with one bit per
871 // processor; we want to schedule the process to run on first level
876 if ( dwSysMask
& bit
)
878 // ok, we can set this bit
881 // another process added
893 // could we set all bits?
896 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
901 // set it: we can't link to SetProcessAffinityMask() because it doesn't
902 // exist in Win9x, use RT binding instead
904 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
906 // can use static var because we're always in the main thread here
907 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
909 if ( !pfnSetProcessAffinityMask
)
911 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
914 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
915 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
918 // we've discovered a MT version of Win9x!
919 wxASSERT_MSG( pfnSetProcessAffinityMask
,
920 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
923 if ( !pfnSetProcessAffinityMask
)
925 // msg given above - do it only once
929 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
931 wxLogLastError(_T("SetProcessAffinityMask"));
942 wxThread::wxThread(wxThreadKind kind
)
944 m_internal
= new wxThreadInternal();
946 m_isDetached
= kind
== wxTHREAD_DETACHED
;
949 wxThread::~wxThread()
954 // create/start thread
955 // -------------------
957 wxThreadError
wxThread::Create(unsigned int stackSize
)
959 wxCriticalSectionLocker
lock(m_critsect
);
961 if ( !m_internal
->Create(this, stackSize
) )
962 return wxTHREAD_NO_RESOURCE
;
964 return wxTHREAD_NO_ERROR
;
967 wxThreadError
wxThread::Run()
969 wxCriticalSectionLocker
lock(m_critsect
);
971 if ( m_internal
->GetState() != STATE_NEW
)
973 // actually, it may be almost any state at all, not only STATE_RUNNING
974 return wxTHREAD_RUNNING
;
977 // the thread has just been created and is still suspended - let it run
981 // suspend/resume thread
982 // ---------------------
984 wxThreadError
wxThread::Pause()
986 wxCriticalSectionLocker
lock(m_critsect
);
988 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
991 wxThreadError
wxThread::Resume()
993 wxCriticalSectionLocker
lock(m_critsect
);
995 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
1001 wxThread::ExitCode
wxThread::Wait()
1003 // although under Windows we can wait for any thread, it's an error to
1004 // wait for a detached one in wxWin API
1005 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
1006 _T("can't wait for detached thread") );
1008 ExitCode rc
= (ExitCode
)-1;
1017 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
1021 // Delete() is always safe to call, so consider all possible states
1023 // we might need to resume the thread, but we might also not need to cancel
1024 // it if it doesn't run yet
1025 bool shouldResume
= FALSE
,
1026 shouldCancel
= TRUE
,
1029 // check if the thread already started to run
1031 wxCriticalSectionLocker
lock(m_critsect
);
1033 if ( m_internal
->GetState() == STATE_NEW
)
1035 // WinThreadStart() will see it and terminate immediately, no need
1036 // to cancel the thread - but we still need to resume it to let it
1038 m_internal
->SetState(STATE_EXITED
);
1040 Resume(); // it knows about STATE_EXITED special case
1042 shouldCancel
= FALSE
;
1045 // shouldResume is correctly set to FALSE here
1049 shouldResume
= IsPaused();
1053 // resume the thread if it is paused
1057 HANDLE hThread
= m_internal
->GetHandle();
1059 // does is still run?
1060 if ( isRunning
|| IsRunning() )
1064 // set flag for wxIsWaitingForThread()
1065 gs_waitingForThread
= TRUE
;
1068 wxBeginBusyCursor();
1072 // ask the thread to terminate
1075 wxCriticalSectionLocker
lock(m_critsect
);
1077 m_internal
->Cancel();
1081 // we can't just wait for the thread to terminate because it might be
1082 // calling some GUI functions and so it will never terminate before we
1083 // process the Windows messages that result from these functions
1087 result
= ::MsgWaitForMultipleObjects
1089 1, // number of objects to wait for
1090 &hThread
, // the objects
1091 FALSE
, // don't wait for all objects
1092 INFINITE
, // no timeout
1093 QS_ALLEVENTS
// return as soon as there are any events
1100 wxLogSysError(_("Can not wait for thread termination"));
1102 return wxTHREAD_KILLED
;
1105 // thread we're waiting for terminated
1108 case WAIT_OBJECT_0
+ 1:
1109 // new message arrived, process it
1110 if ( !wxTheApp
->DoMessage() )
1112 // WM_QUIT received: kill the thread
1115 return wxTHREAD_KILLED
;
1120 // give the thread we're waiting for chance to exit
1121 // from the GUI call it might have been in
1122 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
1131 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1133 } while ( result
!= WAIT_OBJECT_0
);
1135 // simply wait for the thread to terminate
1137 // OTOH, even console apps create windows (in wxExecute, for WinSock
1138 // &c), so may be use MsgWaitForMultipleObject() too here?
1139 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
1141 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1143 #endif // wxUSE_GUI/!wxUSE_GUI
1147 gs_waitingForThread
= FALSE
;
1155 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
1157 wxLogLastError(wxT("GetExitCodeThread"));
1164 // if the thread exits normally, this is done in WinThreadStart, but in
1165 // this case it would have been too early because
1166 // MsgWaitForMultipleObject() would fail if the thread handle was
1167 // closed while we were waiting on it, so we must do it here
1171 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
1172 wxT("thread must be already terminated.") );
1177 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
1180 wxThreadError
wxThread::Kill()
1183 return wxTHREAD_NOT_RUNNING
;
1185 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
1187 wxLogSysError(_("Couldn't terminate thread"));
1189 return wxTHREAD_MISC_ERROR
;
1199 return wxTHREAD_NO_ERROR
;
1202 void wxThread::Exit(ExitCode status
)
1211 #ifdef wxUSE_BEGIN_THREAD
1212 _endthreadex((unsigned)status
);
1214 ::ExitThread((DWORD
)status
);
1215 #endif // VC++/!VC++
1217 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1223 void wxThread::SetPriority(unsigned int prio
)
1225 wxCriticalSectionLocker
lock(m_critsect
);
1227 m_internal
->SetPriority(prio
);
1230 unsigned int wxThread::GetPriority() const
1232 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1234 return m_internal
->GetPriority();
1237 unsigned long wxThread::GetId() const
1239 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1241 return (unsigned long)m_internal
->GetId();
1244 bool wxThread::IsRunning() const
1246 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1248 return m_internal
->GetState() == STATE_RUNNING
;
1251 bool wxThread::IsAlive() const
1253 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1255 return (m_internal
->GetState() == STATE_RUNNING
) ||
1256 (m_internal
->GetState() == STATE_PAUSED
);
1259 bool wxThread::IsPaused() const
1261 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1263 return m_internal
->GetState() == STATE_PAUSED
;
1266 bool wxThread::TestDestroy()
1268 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1270 return m_internal
->GetState() == STATE_CANCELED
;
1273 // ----------------------------------------------------------------------------
1274 // Automatic initialization for thread module
1275 // ----------------------------------------------------------------------------
1277 class wxThreadModule
: public wxModule
1280 virtual bool OnInit();
1281 virtual void OnExit();
1284 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1287 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1289 bool wxThreadModule::OnInit()
1291 // allocate TLS index for storing the pointer to the current thread
1292 gs_tlsThisThread
= ::TlsAlloc();
1293 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1295 // in normal circumstances it will only happen if all other
1296 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1297 // words, this should never happen
1298 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1303 // main thread doesn't have associated wxThread object, so store 0 in the
1305 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1307 ::TlsFree(gs_tlsThisThread
);
1308 gs_tlsThisThread
= 0xFFFFFFFF;
1310 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1315 gs_critsectWaitingForGui
= new wxCriticalSection();
1317 gs_critsectGui
= new wxCriticalSection();
1318 gs_critsectGui
->Enter();
1320 // no error return for GetCurrentThreadId()
1321 gs_idMainThread
= ::GetCurrentThreadId();
1326 void wxThreadModule::OnExit()
1328 if ( !::TlsFree(gs_tlsThisThread
) )
1330 wxLogLastError(wxT("TlsFree failed."));
1333 if ( gs_critsectGui
)
1335 gs_critsectGui
->Leave();
1336 delete gs_critsectGui
;
1337 gs_critsectGui
= NULL
;
1340 delete gs_critsectWaitingForGui
;
1341 gs_critsectWaitingForGui
= NULL
;
1344 // ----------------------------------------------------------------------------
1345 // under Windows, these functions are implemented using a critical section and
1346 // not a mutex, so the names are a bit confusing
1347 // ----------------------------------------------------------------------------
1349 void WXDLLEXPORT
wxMutexGuiEnter()
1351 // this would dead lock everything...
1352 wxASSERT_MSG( !wxThread::IsMain(),
1353 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1355 // the order in which we enter the critical sections here is crucial!!
1357 // set the flag telling to the main thread that we want to do some GUI
1359 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1361 gs_nWaitingForGui
++;
1364 wxWakeUpMainThread();
1366 // now we may block here because the main thread will soon let us in
1367 // (during the next iteration of OnIdle())
1368 gs_critsectGui
->Enter();
1371 void WXDLLEXPORT
wxMutexGuiLeave()
1373 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1375 if ( wxThread::IsMain() )
1377 gs_bGuiOwnedByMainThread
= FALSE
;
1381 // decrement the number of threads waiting for GUI access now
1382 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1383 wxT("calling wxMutexGuiLeave() without entering it first?") );
1385 gs_nWaitingForGui
--;
1387 wxWakeUpMainThread();
1390 gs_critsectGui
->Leave();
1393 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1395 wxASSERT_MSG( wxThread::IsMain(),
1396 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1398 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1400 if ( gs_nWaitingForGui
== 0 )
1402 // no threads are waiting for GUI - so we may acquire the lock without
1403 // any danger (but only if we don't already have it)
1404 if ( !wxGuiOwnedByMainThread() )
1406 gs_critsectGui
->Enter();
1408 gs_bGuiOwnedByMainThread
= TRUE
;
1410 //else: already have it, nothing to do
1414 // some threads are waiting, release the GUI lock if we have it
1415 if ( wxGuiOwnedByMainThread() )
1419 //else: some other worker thread is doing GUI
1423 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1425 return gs_bGuiOwnedByMainThread
;
1428 // wake up the main thread if it's in ::GetMessage()
1429 void WXDLLEXPORT
wxWakeUpMainThread()
1431 // sending any message would do - hopefully WM_NULL is harmless enough
1432 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1434 // should never happen
1435 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1439 bool WXDLLEXPORT
wxIsWaitingForThread()
1441 return gs_waitingForThread
;
1444 #endif // wxUSE_THREADS