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 event
= ::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."));
227 bool Wait(DWORD timeout
)
231 // FIXME this should be MsgWaitForMultipleObjects() as well probably
232 DWORD rc
= ::WaitForSingleObject(event
, timeout
);
236 return rc
!= WAIT_TIMEOUT
;
239 ~wxConditionInternal()
243 if ( !::CloseHandle(event
) )
245 wxLogLastError(wxT("CloseHandle(event)"));
254 wxCondition::wxCondition()
256 m_internal
= new wxConditionInternal
;
259 wxCondition::~wxCondition()
264 void wxCondition::Wait()
266 (void)m_internal
->Wait(INFINITE
);
269 bool wxCondition::Wait(unsigned long sec
,
272 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
275 void wxCondition::Signal()
277 // set the event to signaled: if a thread is already waiting on it, it will
278 // be woken up, otherwise the event will remain in the signaled state until
279 // someone waits on it. In any case, the system will return it to a non
280 // signalled state afterwards. If multiple threads are waiting, only one
282 if ( !::SetEvent(m_internal
->event
) )
284 wxLogLastError(wxT("SetEvent"));
288 void wxCondition::Broadcast()
290 // this works because all these threads are already waiting and so each
291 // SetEvent() inside Signal() is really a PulseEvent() because the event
292 // state is immediately returned to non-signaled
293 for ( int i
= 0; i
< m_internal
->waiters
; i
++ )
299 // ----------------------------------------------------------------------------
300 // wxCriticalSection implementation
301 // ----------------------------------------------------------------------------
303 wxCriticalSection::wxCriticalSection()
305 wxASSERT_MSG( sizeof(CRITICAL_SECTION
) <= sizeof(m_buffer
),
306 _T("must increase buffer size in wx/thread.h") );
308 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
311 wxCriticalSection::~wxCriticalSection()
313 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
316 void wxCriticalSection::Enter()
318 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
321 void wxCriticalSection::Leave()
323 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
326 // ----------------------------------------------------------------------------
327 // wxThread implementation
328 // ----------------------------------------------------------------------------
330 // wxThreadInternal class
331 // ----------------------
333 class wxThreadInternal
340 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
352 if ( !::CloseHandle(m_hThread
) )
354 wxLogLastError(wxT("CloseHandle(thread)"));
361 // create a new (suspended) thread (for the given thread object)
362 bool Create(wxThread
*thread
);
364 // suspend/resume/terminate
367 void Cancel() { m_state
= STATE_CANCELED
; }
370 void SetState(wxThreadState state
) { m_state
= state
; }
371 wxThreadState
GetState() const { return m_state
; }
374 void SetPriority(unsigned int priority
);
375 unsigned int GetPriority() const { return m_priority
; }
377 // thread handle and id
378 HANDLE
GetHandle() const { return m_hThread
; }
379 DWORD
GetId() const { return m_tid
; }
382 static DWORD
WinThreadStart(wxThread
*thread
);
385 HANDLE m_hThread
; // handle of the thread
386 wxThreadState m_state
; // state, see wxThreadState enum
387 unsigned int m_priority
; // thread priority in "wx" units
388 DWORD m_tid
; // thread id
391 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
396 // first of all, check whether we hadn't been cancelled already and don't
397 // start the user code at all then
398 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
403 else // do run thread
405 // store the thread object in the TLS
406 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
408 wxLogSysError(_("Can not start thread: error writing TLS."));
413 rc
= (DWORD
)thread
->Entry();
415 // enter m_critsect before changing the thread state
416 thread
->m_critsect
.Enter();
417 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
418 thread
->m_internal
->SetState(STATE_EXITED
);
419 thread
->m_critsect
.Leave();
424 // if the thread was cancelled (from Delete()), then its handle is still
426 if ( thread
->IsDetached() && !wasCancelled
)
431 //else: the joinable threads handle will be closed when Wait() is done
436 void wxThreadInternal::SetPriority(unsigned int priority
)
438 m_priority
= priority
;
440 // translate wxWindows priority to the Windows one
442 if (m_priority
<= 20)
443 win_priority
= THREAD_PRIORITY_LOWEST
;
444 else if (m_priority
<= 40)
445 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
446 else if (m_priority
<= 60)
447 win_priority
= THREAD_PRIORITY_NORMAL
;
448 else if (m_priority
<= 80)
449 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
450 else if (m_priority
<= 100)
451 win_priority
= THREAD_PRIORITY_HIGHEST
;
454 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
455 win_priority
= THREAD_PRIORITY_NORMAL
;
458 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
460 wxLogSysError(_("Can't set thread priority"));
464 bool wxThreadInternal::Create(wxThread
*thread
)
466 // for compilers which have it, we should use C RTL function for thread
467 // creation instead of Win32 API one because otherwise we will have memory
468 // leaks if the thread uses C RTL (and most threads do)
469 #if defined(__VISUALC__) || \
470 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
471 (defined(__GNUG__) && defined(__MSVCRT__))
472 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
474 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
476 wxThreadInternal::WinThreadStart
,
477 thread
, CREATE_SUSPENDED
,
478 (unsigned int *)&m_tid
);
479 #else // compiler doesn't have _beginthreadex
480 m_hThread
= ::CreateThread
482 NULL
, // default security
483 0, // default stack size
484 (LPTHREAD_START_ROUTINE
) // thread entry point
485 wxThreadInternal::WinThreadStart
, //
486 (LPVOID
)thread
, // parameter
487 CREATE_SUSPENDED
, // flags
488 &m_tid
// [out] thread id
490 #endif // _beginthreadex/CreateThread
492 if ( m_hThread
== NULL
)
494 wxLogSysError(_("Can't create thread"));
499 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
501 SetPriority(m_priority
);
507 bool wxThreadInternal::Suspend()
509 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
510 if ( nSuspendCount
== (DWORD
)-1 )
512 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
517 m_state
= STATE_PAUSED
;
522 bool wxThreadInternal::Resume()
524 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
525 if ( nSuspendCount
== (DWORD
)-1 )
527 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
532 // don't change the state from STATE_EXITED because it's special and means
533 // we are going to terminate without running any user code - if we did it,
534 // the codei n Delete() wouldn't work
535 if ( m_state
!= STATE_EXITED
)
537 m_state
= STATE_RUNNING
;
546 wxThread
*wxThread::This()
548 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
550 // be careful, 0 may be a valid return value as well
551 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
553 wxLogSysError(_("Couldn't get the current thread pointer"));
561 bool wxThread::IsMain()
563 return ::GetCurrentThreadId() == gs_idMainThread
;
570 void wxThread::Yield()
572 // 0 argument to Sleep() is special and means to just give away the rest of
577 void wxThread::Sleep(unsigned long milliseconds
)
579 ::Sleep(milliseconds
);
582 int wxThread::GetCPUCount()
587 return si
.dwNumberOfProcessors
;
590 bool wxThread::SetConcurrency(size_t level
)
592 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
594 // ok only for the default one
598 // get system affinity mask first
599 HANDLE hProcess
= ::GetCurrentProcess();
600 DWORD dwProcMask
, dwSysMask
;
601 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
603 wxLogLastError(_T("GetProcessAffinityMask"));
608 // how many CPUs have we got?
609 if ( dwSysMask
== 1 )
611 // don't bother with all this complicated stuff - on a single
612 // processor system it doesn't make much sense anyhow
616 // calculate the process mask: it's a bit vector with one bit per
617 // processor; we want to schedule the process to run on first level
622 if ( dwSysMask
& bit
)
624 // ok, we can set this bit
627 // another process added
639 // could we set all bits?
642 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
647 // set it: we can't link to SetProcessAffinityMask() because it doesn't
648 // exist in Win9x, use RT binding instead
650 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
652 // can use static var because we're always in the main thread here
653 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
655 if ( !pfnSetProcessAffinityMask
)
657 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
660 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
661 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
664 // we've discovered a MT version of Win9x!
665 wxASSERT_MSG( pfnSetProcessAffinityMask
,
666 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
669 if ( !pfnSetProcessAffinityMask
)
671 // msg given above - do it only once
675 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
677 wxLogLastError(_T("SetProcessAffinityMask"));
688 wxThread::wxThread(wxThreadKind kind
)
690 m_internal
= new wxThreadInternal();
692 m_isDetached
= kind
== wxTHREAD_DETACHED
;
695 wxThread::~wxThread()
700 // create/start thread
701 // -------------------
703 wxThreadError
wxThread::Create()
705 wxCriticalSectionLocker
lock(m_critsect
);
707 if ( !m_internal
->Create(this) )
708 return wxTHREAD_NO_RESOURCE
;
710 return wxTHREAD_NO_ERROR
;
713 wxThreadError
wxThread::Run()
715 wxCriticalSectionLocker
lock(m_critsect
);
717 if ( m_internal
->GetState() != STATE_NEW
)
719 // actually, it may be almost any state at all, not only STATE_RUNNING
720 return wxTHREAD_RUNNING
;
723 // the thread has just been created and is still suspended - let it run
727 // suspend/resume thread
728 // ---------------------
730 wxThreadError
wxThread::Pause()
732 wxCriticalSectionLocker
lock(m_critsect
);
734 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
737 wxThreadError
wxThread::Resume()
739 wxCriticalSectionLocker
lock(m_critsect
);
741 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
747 wxThread::ExitCode
wxThread::Wait()
749 // although under Windows we can wait for any thread, it's an error to
750 // wait for a detached one in wxWin API
751 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
752 _T("can't wait for detached thread") );
754 ExitCode rc
= (ExitCode
)-1;
763 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
767 // Delete() is always safe to call, so consider all possible states
769 // we might need to resume the thread, but we might also not need to cancel
770 // it if it doesn't run yet
771 bool shouldResume
= FALSE
,
775 // check if the thread already started to run
777 wxCriticalSectionLocker
lock(m_critsect
);
779 if ( m_internal
->GetState() == STATE_NEW
)
781 // WinThreadStart() will see it and terminate immediately, no need
782 // to cancel the thread - but we still need to resume it to let it
784 m_internal
->SetState(STATE_EXITED
);
786 Resume(); // it knows about STATE_EXITED special case
788 shouldCancel
= FALSE
;
791 // shouldResume is correctly set to FALSE here
795 shouldResume
= IsPaused();
799 // resume the thread if it is paused
803 HANDLE hThread
= m_internal
->GetHandle();
805 // does is still run?
806 if ( isRunning
|| IsRunning() )
810 // set flag for wxIsWaitingForThread()
811 gs_waitingForThread
= TRUE
;
818 // ask the thread to terminate
821 wxCriticalSectionLocker
lock(m_critsect
);
823 m_internal
->Cancel();
827 // we can't just wait for the thread to terminate because it might be
828 // calling some GUI functions and so it will never terminate before we
829 // process the Windows messages that result from these functions
833 result
= ::MsgWaitForMultipleObjects
835 1, // number of objects to wait for
836 &hThread
, // the objects
837 FALSE
, // don't wait for all objects
838 INFINITE
, // no timeout
839 QS_ALLEVENTS
// return as soon as there are any events
846 wxLogSysError(_("Can not wait for thread termination"));
848 return wxTHREAD_KILLED
;
851 // thread we're waiting for terminated
854 case WAIT_OBJECT_0
+ 1:
855 // new message arrived, process it
856 if ( !wxTheApp
->DoMessage() )
858 // WM_QUIT received: kill the thread
861 return wxTHREAD_KILLED
;
866 // give the thread we're waiting for chance to exit
867 // from the GUI call it might have been in
868 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
877 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
879 } while ( result
!= WAIT_OBJECT_0
);
881 // simply wait for the thread to terminate
883 // OTOH, even console apps create windows (in wxExecute, for WinSock
884 // &c), so may be use MsgWaitForMultipleObject() too here?
885 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
887 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
889 #endif // wxUSE_GUI/!wxUSE_GUI
893 gs_waitingForThread
= FALSE
;
901 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
903 wxLogLastError(wxT("GetExitCodeThread"));
910 // if the thread exits normally, this is done in WinThreadStart, but in
911 // this case it would have been too early because
912 // MsgWaitForMultipleObject() would fail if the thread handle was
913 // closed while we were waiting on it, so we must do it here
917 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
918 wxT("thread must be already terminated.") );
923 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
926 wxThreadError
wxThread::Kill()
929 return wxTHREAD_NOT_RUNNING
;
931 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
933 wxLogSysError(_("Couldn't terminate thread"));
935 return wxTHREAD_MISC_ERROR
;
945 return wxTHREAD_NO_ERROR
;
948 void wxThread::Exit(ExitCode status
)
957 #if defined(__VISUALC__) || \
958 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
959 (defined(__GNUG__) && defined(__MSVCRT__))
960 _endthreadex((unsigned)status
);
962 ::ExitThread((DWORD
)status
);
965 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
971 void wxThread::SetPriority(unsigned int prio
)
973 wxCriticalSectionLocker
lock(m_critsect
);
975 m_internal
->SetPriority(prio
);
978 unsigned int wxThread::GetPriority() const
980 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
982 return m_internal
->GetPriority();
985 unsigned long wxThread::GetId() const
987 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
989 return (unsigned long)m_internal
->GetId();
992 bool wxThread::IsRunning() const
994 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
996 return m_internal
->GetState() == STATE_RUNNING
;
999 bool wxThread::IsAlive() const
1001 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1003 return (m_internal
->GetState() == STATE_RUNNING
) ||
1004 (m_internal
->GetState() == STATE_PAUSED
);
1007 bool wxThread::IsPaused() const
1009 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1011 return m_internal
->GetState() == STATE_PAUSED
;
1014 bool wxThread::TestDestroy()
1016 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1018 return m_internal
->GetState() == STATE_CANCELED
;
1021 // ----------------------------------------------------------------------------
1022 // Automatic initialization for thread module
1023 // ----------------------------------------------------------------------------
1025 class wxThreadModule
: public wxModule
1028 virtual bool OnInit();
1029 virtual void OnExit();
1032 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1035 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1037 bool wxThreadModule::OnInit()
1039 // allocate TLS index for storing the pointer to the current thread
1040 gs_tlsThisThread
= ::TlsAlloc();
1041 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1043 // in normal circumstances it will only happen if all other
1044 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1045 // words, this should never happen
1046 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1051 // main thread doesn't have associated wxThread object, so store 0 in the
1053 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1055 ::TlsFree(gs_tlsThisThread
);
1056 gs_tlsThisThread
= 0xFFFFFFFF;
1058 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1063 gs_critsectWaitingForGui
= new wxCriticalSection();
1065 gs_critsectGui
= new wxCriticalSection();
1066 gs_critsectGui
->Enter();
1068 // no error return for GetCurrentThreadId()
1069 gs_idMainThread
= ::GetCurrentThreadId();
1074 void wxThreadModule::OnExit()
1076 if ( !::TlsFree(gs_tlsThisThread
) )
1078 wxLogLastError(wxT("TlsFree failed."));
1081 if ( gs_critsectGui
)
1083 gs_critsectGui
->Leave();
1084 delete gs_critsectGui
;
1085 gs_critsectGui
= NULL
;
1088 delete gs_critsectWaitingForGui
;
1089 gs_critsectWaitingForGui
= NULL
;
1092 // ----------------------------------------------------------------------------
1093 // under Windows, these functions are implemented using a critical section and
1094 // not a mutex, so the names are a bit confusing
1095 // ----------------------------------------------------------------------------
1097 void WXDLLEXPORT
wxMutexGuiEnter()
1099 // this would dead lock everything...
1100 wxASSERT_MSG( !wxThread::IsMain(),
1101 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1103 // the order in which we enter the critical sections here is crucial!!
1105 // set the flag telling to the main thread that we want to do some GUI
1107 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1109 gs_nWaitingForGui
++;
1112 wxWakeUpMainThread();
1114 // now we may block here because the main thread will soon let us in
1115 // (during the next iteration of OnIdle())
1116 gs_critsectGui
->Enter();
1119 void WXDLLEXPORT
wxMutexGuiLeave()
1121 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1123 if ( wxThread::IsMain() )
1125 gs_bGuiOwnedByMainThread
= FALSE
;
1129 // decrement the number of waiters now
1130 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1131 wxT("calling wxMutexGuiLeave() without entering it first?") );
1133 gs_nWaitingForGui
--;
1135 wxWakeUpMainThread();
1138 gs_critsectGui
->Leave();
1141 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1143 wxASSERT_MSG( wxThread::IsMain(),
1144 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1146 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1148 if ( gs_nWaitingForGui
== 0 )
1150 // no threads are waiting for GUI - so we may acquire the lock without
1151 // any danger (but only if we don't already have it)
1152 if ( !wxGuiOwnedByMainThread() )
1154 gs_critsectGui
->Enter();
1156 gs_bGuiOwnedByMainThread
= TRUE
;
1158 //else: already have it, nothing to do
1162 // some threads are waiting, release the GUI lock if we have it
1163 if ( wxGuiOwnedByMainThread() )
1167 //else: some other worker thread is doing GUI
1171 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1173 return gs_bGuiOwnedByMainThread
;
1176 // wake up the main thread if it's in ::GetMessage()
1177 void WXDLLEXPORT
wxWakeUpMainThread()
1179 // sending any message would do - hopefully WM_NULL is harmless enough
1180 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1182 // should never happen
1183 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1187 bool WXDLLEXPORT
wxIsWaitingForThread()
1189 return gs_waitingForThread
;
1192 #endif // wxUSE_THREADS