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(__VISUALC__) || \
49 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
50 (defined(__GNUG__) && defined(__MSVCRT__))
52 #if defined(__BORLANDC__) && !defined(__MT__)
53 // I can't set -tWM in the IDE (anyone?) so have to do this
57 #if defined(__BORLANDC__) && !defined(__MFC_COMPAT__)
58 // Needed to know about _beginthreadex etc..
59 #define __MFC_COMPAT__
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // the possible states of the thread ("=>" shows all possible transitions from
73 STATE_NEW
, // didn't start execution yet (=> RUNNING)
74 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
75 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
76 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
77 STATE_EXITED
// thread is terminating
80 // ----------------------------------------------------------------------------
81 // this module globals
82 // ----------------------------------------------------------------------------
84 // TLS index of the slot where we store the pointer to the current thread
85 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
87 // id of the main thread - the one which can call GUI functions without first
88 // calling wxMutexGuiEnter()
89 static DWORD gs_idMainThread
= 0;
91 // if it's FALSE, some secondary thread is holding the GUI lock
92 static bool gs_bGuiOwnedByMainThread
= TRUE
;
94 // critical section which controls access to all GUI functions: any secondary
95 // thread (i.e. except the main one) must enter this crit section before doing
97 static wxCriticalSection
*gs_critsectGui
= NULL
;
99 // critical section which protects gs_nWaitingForGui variable
100 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
102 // number of threads waiting for GUI in wxMutexGuiEnter()
103 static size_t gs_nWaitingForGui
= 0;
105 // are we waiting for a thread termination?
106 static bool gs_waitingForThread
= FALSE
;
108 // ============================================================================
109 // Windows implementation of thread classes
110 // ============================================================================
112 // ----------------------------------------------------------------------------
113 // wxMutex implementation
114 // ----------------------------------------------------------------------------
116 class wxMutexInternal
121 m_mutex
= ::CreateMutex(NULL
, FALSE
, NULL
);
124 wxLogSysError(_("Can not create mutex"));
128 ~wxMutexInternal() { if ( m_mutex
) CloseHandle(m_mutex
); }
136 m_internal
= new wxMutexInternal
;
145 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
151 wxMutexError
wxMutex::Lock()
155 ret
= WaitForSingleObject(m_internal
->m_mutex
, INFINITE
);
166 wxLogSysError(_("Couldn't acquire a mutex lock"));
167 return wxMUTEX_MISC_ERROR
;
171 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
175 return wxMUTEX_NO_ERROR
;
178 wxMutexError
wxMutex::TryLock()
182 ret
= WaitForSingleObject(m_internal
->m_mutex
, 0);
183 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
187 return wxMUTEX_NO_ERROR
;
190 wxMutexError
wxMutex::Unlock()
195 BOOL ret
= ReleaseMutex(m_internal
->m_mutex
);
198 wxLogSysError(_("Couldn't release a mutex"));
199 return wxMUTEX_MISC_ERROR
;
202 return wxMUTEX_NO_ERROR
;
205 // ----------------------------------------------------------------------------
206 // wxCondition implementation
207 // ----------------------------------------------------------------------------
209 class wxConditionInternal
212 wxConditionInternal()
214 m_hEvent
= ::CreateEvent(
215 NULL
, // default secutiry
216 FALSE
, // not manual reset
217 FALSE
, // nonsignaled initially
218 NULL
// nameless event
222 wxLogSysError(_("Can not create event object."));
225 // nobody waits for us yet
229 bool Wait(DWORD timeout
)
231 // as m_nWaiters variable is accessed from multiple waiting threads
232 // (and possibly from the broadcasting thread), we need to change its
234 ::InterlockedIncrement(&m_nWaiters
);
236 // FIXME this should be MsgWaitForMultipleObjects() as we want to keep
237 // processing Windows messages while waiting (or don't we?)
238 DWORD rc
= ::WaitForSingleObject(m_hEvent
, timeout
);
240 ::InterlockedDecrement(&m_nWaiters
);
242 return rc
!= WAIT_TIMEOUT
;
247 // set the event to signaled: if a thread is already waiting on it, it
248 // will be woken up, otherwise the event will remain in the signaled
249 // state until someone waits on it. In any case, the system will return
250 // it to a non signalled state afterwards. If multiple threads are
251 // waiting, only one will be woken up.
252 if ( !::SetEvent(m_hEvent
) )
254 wxLogLastError(wxT("SetEvent"));
260 // we need to save the original value as m_nWaiters is goign to be
261 // decreased by the signalled thread resulting in the loop being
262 // executed less times than needed
263 LONG nWaiters
= m_nWaiters
;
265 // this works because all these threads are already waiting and so each
266 // SetEvent() inside Signal() is really a PulseEvent() because the
267 // event state is immediately returned to non-signaled
268 for ( LONG n
= 0; n
< nWaiters
; n
++ )
274 ~wxConditionInternal()
278 if ( !::CloseHandle(m_hEvent
) )
280 wxLogLastError(wxT("CloseHandle(event)"));
286 // the Win32 synchronization object corresponding to this event
289 // number of threads waiting for this condition
293 wxCondition::wxCondition()
295 m_internal
= new wxConditionInternal
;
298 wxCondition::~wxCondition()
303 void wxCondition::Wait()
305 (void)m_internal
->Wait(INFINITE
);
308 bool wxCondition::Wait(unsigned long sec
,
311 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
314 void wxCondition::Signal()
316 m_internal
->Signal();
319 void wxCondition::Broadcast()
321 m_internal
->Broadcast();
324 // ----------------------------------------------------------------------------
325 // wxCriticalSection implementation
326 // ----------------------------------------------------------------------------
328 wxCriticalSection::wxCriticalSection()
331 // Done this way to stop warnings during compilation about statement
332 // always being false
333 int csSize
= sizeof(CRITICAL_SECTION
);
334 int bSize
= sizeof(m_buffer
);
335 wxASSERT_MSG( csSize
<= bSize
,
336 _T("must increase buffer size in wx/thread.h") );
339 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
342 wxCriticalSection::~wxCriticalSection()
344 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
347 void wxCriticalSection::Enter()
349 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
352 void wxCriticalSection::Leave()
354 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
357 // ----------------------------------------------------------------------------
358 // wxThread implementation
359 // ----------------------------------------------------------------------------
361 // wxThreadInternal class
362 // ----------------------
364 class wxThreadInternal
371 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
383 if ( !::CloseHandle(m_hThread
) )
385 wxLogLastError(wxT("CloseHandle(thread)"));
392 // create a new (suspended) thread (for the given thread object)
393 bool Create(wxThread
*thread
);
395 // suspend/resume/terminate
398 void Cancel() { m_state
= STATE_CANCELED
; }
401 void SetState(wxThreadState state
) { m_state
= state
; }
402 wxThreadState
GetState() const { return m_state
; }
405 void SetPriority(unsigned int priority
);
406 unsigned int GetPriority() const { return m_priority
; }
408 // thread handle and id
409 HANDLE
GetHandle() const { return m_hThread
; }
410 DWORD
GetId() const { return m_tid
; }
413 static DWORD
WinThreadStart(wxThread
*thread
);
416 HANDLE m_hThread
; // handle of the thread
417 wxThreadState m_state
; // state, see wxThreadState enum
418 unsigned int m_priority
; // thread priority in "wx" units
419 DWORD m_tid
; // thread id
422 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
427 // first of all, check whether we hadn't been cancelled already and don't
428 // start the user code at all then
429 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
434 else // do run thread
436 // store the thread object in the TLS
437 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
439 wxLogSysError(_("Can not start thread: error writing TLS."));
444 rc
= (DWORD
)thread
->Entry();
446 // enter m_critsect before changing the thread state
447 thread
->m_critsect
.Enter();
448 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
449 thread
->m_internal
->SetState(STATE_EXITED
);
450 thread
->m_critsect
.Leave();
455 // if the thread was cancelled (from Delete()), then its handle is still
457 if ( thread
->IsDetached() && !wasCancelled
)
462 //else: the joinable threads handle will be closed when Wait() is done
467 void wxThreadInternal::SetPriority(unsigned int priority
)
469 m_priority
= priority
;
471 // translate wxWindows priority to the Windows one
473 if (m_priority
<= 20)
474 win_priority
= THREAD_PRIORITY_LOWEST
;
475 else if (m_priority
<= 40)
476 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
477 else if (m_priority
<= 60)
478 win_priority
= THREAD_PRIORITY_NORMAL
;
479 else if (m_priority
<= 80)
480 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
481 else if (m_priority
<= 100)
482 win_priority
= THREAD_PRIORITY_HIGHEST
;
485 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
486 win_priority
= THREAD_PRIORITY_NORMAL
;
489 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
491 wxLogSysError(_("Can't set thread priority"));
495 bool wxThreadInternal::Create(wxThread
*thread
)
497 // for compilers which have it, we should use C RTL function for thread
498 // creation instead of Win32 API one because otherwise we will have memory
499 // leaks if the thread uses C RTL (and most threads do)
500 #if defined(__VISUALC__) || \
501 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
502 (defined(__GNUG__) && defined(__MSVCRT__))
503 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
505 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
507 wxThreadInternal::WinThreadStart
,
508 thread
, CREATE_SUSPENDED
,
509 (unsigned int *)&m_tid
);
510 #else // compiler doesn't have _beginthreadex
511 m_hThread
= ::CreateThread
513 NULL
, // default security
514 0, // default stack size
515 (LPTHREAD_START_ROUTINE
) // thread entry point
516 wxThreadInternal::WinThreadStart
, //
517 (LPVOID
)thread
, // parameter
518 CREATE_SUSPENDED
, // flags
519 &m_tid
// [out] thread id
521 #endif // _beginthreadex/CreateThread
523 if ( m_hThread
== NULL
)
525 wxLogSysError(_("Can't create thread"));
530 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
532 SetPriority(m_priority
);
538 bool wxThreadInternal::Suspend()
540 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
541 if ( nSuspendCount
== (DWORD
)-1 )
543 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
548 m_state
= STATE_PAUSED
;
553 bool wxThreadInternal::Resume()
555 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
556 if ( nSuspendCount
== (DWORD
)-1 )
558 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
563 // don't change the state from STATE_EXITED because it's special and means
564 // we are going to terminate without running any user code - if we did it,
565 // the codei n Delete() wouldn't work
566 if ( m_state
!= STATE_EXITED
)
568 m_state
= STATE_RUNNING
;
577 wxThread
*wxThread::This()
579 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
581 // be careful, 0 may be a valid return value as well
582 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
584 wxLogSysError(_("Couldn't get the current thread pointer"));
592 bool wxThread::IsMain()
594 return ::GetCurrentThreadId() == gs_idMainThread
;
601 void wxThread::Yield()
603 // 0 argument to Sleep() is special and means to just give away the rest of
608 void wxThread::Sleep(unsigned long milliseconds
)
610 ::Sleep(milliseconds
);
613 int wxThread::GetCPUCount()
618 return si
.dwNumberOfProcessors
;
621 bool wxThread::SetConcurrency(size_t level
)
623 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
625 // ok only for the default one
629 // get system affinity mask first
630 HANDLE hProcess
= ::GetCurrentProcess();
631 DWORD dwProcMask
, dwSysMask
;
632 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
634 wxLogLastError(_T("GetProcessAffinityMask"));
639 // how many CPUs have we got?
640 if ( dwSysMask
== 1 )
642 // don't bother with all this complicated stuff - on a single
643 // processor system it doesn't make much sense anyhow
647 // calculate the process mask: it's a bit vector with one bit per
648 // processor; we want to schedule the process to run on first level
653 if ( dwSysMask
& bit
)
655 // ok, we can set this bit
658 // another process added
670 // could we set all bits?
673 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
678 // set it: we can't link to SetProcessAffinityMask() because it doesn't
679 // exist in Win9x, use RT binding instead
681 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
683 // can use static var because we're always in the main thread here
684 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
686 if ( !pfnSetProcessAffinityMask
)
688 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
691 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
692 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
695 // we've discovered a MT version of Win9x!
696 wxASSERT_MSG( pfnSetProcessAffinityMask
,
697 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
700 if ( !pfnSetProcessAffinityMask
)
702 // msg given above - do it only once
706 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
708 wxLogLastError(_T("SetProcessAffinityMask"));
719 wxThread::wxThread(wxThreadKind kind
)
721 m_internal
= new wxThreadInternal();
723 m_isDetached
= kind
== wxTHREAD_DETACHED
;
726 wxThread::~wxThread()
731 // create/start thread
732 // -------------------
734 wxThreadError
wxThread::Create()
736 wxCriticalSectionLocker
lock(m_critsect
);
738 if ( !m_internal
->Create(this) )
739 return wxTHREAD_NO_RESOURCE
;
741 return wxTHREAD_NO_ERROR
;
744 wxThreadError
wxThread::Run()
746 wxCriticalSectionLocker
lock(m_critsect
);
748 if ( m_internal
->GetState() != STATE_NEW
)
750 // actually, it may be almost any state at all, not only STATE_RUNNING
751 return wxTHREAD_RUNNING
;
754 // the thread has just been created and is still suspended - let it run
758 // suspend/resume thread
759 // ---------------------
761 wxThreadError
wxThread::Pause()
763 wxCriticalSectionLocker
lock(m_critsect
);
765 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
768 wxThreadError
wxThread::Resume()
770 wxCriticalSectionLocker
lock(m_critsect
);
772 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
778 wxThread::ExitCode
wxThread::Wait()
780 // although under Windows we can wait for any thread, it's an error to
781 // wait for a detached one in wxWin API
782 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
783 _T("can't wait for detached thread") );
785 ExitCode rc
= (ExitCode
)-1;
794 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
798 // Delete() is always safe to call, so consider all possible states
800 // we might need to resume the thread, but we might also not need to cancel
801 // it if it doesn't run yet
802 bool shouldResume
= FALSE
,
806 // check if the thread already started to run
808 wxCriticalSectionLocker
lock(m_critsect
);
810 if ( m_internal
->GetState() == STATE_NEW
)
812 // WinThreadStart() will see it and terminate immediately, no need
813 // to cancel the thread - but we still need to resume it to let it
815 m_internal
->SetState(STATE_EXITED
);
817 Resume(); // it knows about STATE_EXITED special case
819 shouldCancel
= FALSE
;
822 // shouldResume is correctly set to FALSE here
826 shouldResume
= IsPaused();
830 // resume the thread if it is paused
834 HANDLE hThread
= m_internal
->GetHandle();
836 // does is still run?
837 if ( isRunning
|| IsRunning() )
841 // set flag for wxIsWaitingForThread()
842 gs_waitingForThread
= TRUE
;
849 // ask the thread to terminate
852 wxCriticalSectionLocker
lock(m_critsect
);
854 m_internal
->Cancel();
858 // we can't just wait for the thread to terminate because it might be
859 // calling some GUI functions and so it will never terminate before we
860 // process the Windows messages that result from these functions
864 result
= ::MsgWaitForMultipleObjects
866 1, // number of objects to wait for
867 &hThread
, // the objects
868 FALSE
, // don't wait for all objects
869 INFINITE
, // no timeout
870 QS_ALLEVENTS
// return as soon as there are any events
877 wxLogSysError(_("Can not wait for thread termination"));
879 return wxTHREAD_KILLED
;
882 // thread we're waiting for terminated
885 case WAIT_OBJECT_0
+ 1:
886 // new message arrived, process it
887 if ( !wxTheApp
->DoMessage() )
889 // WM_QUIT received: kill the thread
892 return wxTHREAD_KILLED
;
897 // give the thread we're waiting for chance to exit
898 // from the GUI call it might have been in
899 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
908 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
910 } while ( result
!= WAIT_OBJECT_0
);
912 // simply wait for the thread to terminate
914 // OTOH, even console apps create windows (in wxExecute, for WinSock
915 // &c), so may be use MsgWaitForMultipleObject() too here?
916 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
918 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
920 #endif // wxUSE_GUI/!wxUSE_GUI
924 gs_waitingForThread
= FALSE
;
932 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
934 wxLogLastError(wxT("GetExitCodeThread"));
941 // if the thread exits normally, this is done in WinThreadStart, but in
942 // this case it would have been too early because
943 // MsgWaitForMultipleObject() would fail if the thread handle was
944 // closed while we were waiting on it, so we must do it here
948 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
949 wxT("thread must be already terminated.") );
954 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
957 wxThreadError
wxThread::Kill()
960 return wxTHREAD_NOT_RUNNING
;
962 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
964 wxLogSysError(_("Couldn't terminate thread"));
966 return wxTHREAD_MISC_ERROR
;
976 return wxTHREAD_NO_ERROR
;
979 void wxThread::Exit(ExitCode status
)
988 #if defined(__VISUALC__) || \
989 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
990 (defined(__GNUG__) && defined(__MSVCRT__))
991 _endthreadex((unsigned)status
);
993 ::ExitThread((DWORD
)status
);
996 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1002 void wxThread::SetPriority(unsigned int prio
)
1004 wxCriticalSectionLocker
lock(m_critsect
);
1006 m_internal
->SetPriority(prio
);
1009 unsigned int wxThread::GetPriority() const
1011 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1013 return m_internal
->GetPriority();
1016 unsigned long wxThread::GetId() const
1018 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1020 return (unsigned long)m_internal
->GetId();
1023 bool wxThread::IsRunning() const
1025 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1027 return m_internal
->GetState() == STATE_RUNNING
;
1030 bool wxThread::IsAlive() const
1032 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1034 return (m_internal
->GetState() == STATE_RUNNING
) ||
1035 (m_internal
->GetState() == STATE_PAUSED
);
1038 bool wxThread::IsPaused() const
1040 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1042 return m_internal
->GetState() == STATE_PAUSED
;
1045 bool wxThread::TestDestroy()
1047 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1049 return m_internal
->GetState() == STATE_CANCELED
;
1052 // ----------------------------------------------------------------------------
1053 // Automatic initialization for thread module
1054 // ----------------------------------------------------------------------------
1056 class wxThreadModule
: public wxModule
1059 virtual bool OnInit();
1060 virtual void OnExit();
1063 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1066 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1068 bool wxThreadModule::OnInit()
1070 // allocate TLS index for storing the pointer to the current thread
1071 gs_tlsThisThread
= ::TlsAlloc();
1072 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1074 // in normal circumstances it will only happen if all other
1075 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1076 // words, this should never happen
1077 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1082 // main thread doesn't have associated wxThread object, so store 0 in the
1084 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1086 ::TlsFree(gs_tlsThisThread
);
1087 gs_tlsThisThread
= 0xFFFFFFFF;
1089 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1094 gs_critsectWaitingForGui
= new wxCriticalSection();
1096 gs_critsectGui
= new wxCriticalSection();
1097 gs_critsectGui
->Enter();
1099 // no error return for GetCurrentThreadId()
1100 gs_idMainThread
= ::GetCurrentThreadId();
1105 void wxThreadModule::OnExit()
1107 if ( !::TlsFree(gs_tlsThisThread
) )
1109 wxLogLastError(wxT("TlsFree failed."));
1112 if ( gs_critsectGui
)
1114 gs_critsectGui
->Leave();
1115 delete gs_critsectGui
;
1116 gs_critsectGui
= NULL
;
1119 delete gs_critsectWaitingForGui
;
1120 gs_critsectWaitingForGui
= NULL
;
1123 // ----------------------------------------------------------------------------
1124 // under Windows, these functions are implemented using a critical section and
1125 // not a mutex, so the names are a bit confusing
1126 // ----------------------------------------------------------------------------
1128 void WXDLLEXPORT
wxMutexGuiEnter()
1130 // this would dead lock everything...
1131 wxASSERT_MSG( !wxThread::IsMain(),
1132 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1134 // the order in which we enter the critical sections here is crucial!!
1136 // set the flag telling to the main thread that we want to do some GUI
1138 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1140 gs_nWaitingForGui
++;
1143 wxWakeUpMainThread();
1145 // now we may block here because the main thread will soon let us in
1146 // (during the next iteration of OnIdle())
1147 gs_critsectGui
->Enter();
1150 void WXDLLEXPORT
wxMutexGuiLeave()
1152 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1154 if ( wxThread::IsMain() )
1156 gs_bGuiOwnedByMainThread
= FALSE
;
1160 // decrement the number of threads waiting for GUI access now
1161 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1162 wxT("calling wxMutexGuiLeave() without entering it first?") );
1164 gs_nWaitingForGui
--;
1166 wxWakeUpMainThread();
1169 gs_critsectGui
->Leave();
1172 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1174 wxASSERT_MSG( wxThread::IsMain(),
1175 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1177 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1179 if ( gs_nWaitingForGui
== 0 )
1181 // no threads are waiting for GUI - so we may acquire the lock without
1182 // any danger (but only if we don't already have it)
1183 if ( !wxGuiOwnedByMainThread() )
1185 gs_critsectGui
->Enter();
1187 gs_bGuiOwnedByMainThread
= TRUE
;
1189 //else: already have it, nothing to do
1193 // some threads are waiting, release the GUI lock if we have it
1194 if ( wxGuiOwnedByMainThread() )
1198 //else: some other worker thread is doing GUI
1202 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1204 return gs_bGuiOwnedByMainThread
;
1207 // wake up the main thread if it's in ::GetMessage()
1208 void WXDLLEXPORT
wxWakeUpMainThread()
1210 // sending any message would do - hopefully WM_NULL is harmless enough
1211 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1213 // should never happen
1214 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1218 bool WXDLLEXPORT
wxIsWaitingForThread()
1220 return gs_waitingForThread
;
1223 #endif // wxUSE_THREADS