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"
39 // must have this symbol defined to get _beginthread/_endthread declarations
44 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
46 #if defined(__BORLANDC__) && !defined(__MT__)
47 // I can't set -tWM in the IDE (anyone?) so have to do this
51 #if defined(__BORLANDC__) && !defined(__MFC_COMPAT__)
52 // Needed to know about _beginthreadex etc..
53 #define __MFC_COMPAT__
60 // ----------------------------------------------------------------------------
62 // ----------------------------------------------------------------------------
64 // the possible states of the thread ("=>" shows all possible transitions from
68 STATE_NEW
, // didn't start execution yet (=> RUNNING)
69 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
70 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
71 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
72 STATE_EXITED
// thread is terminating
75 // ----------------------------------------------------------------------------
76 // this module globals
77 // ----------------------------------------------------------------------------
79 // TLS index of the slot where we store the pointer to the current thread
80 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
82 // id of the main thread - the one which can call GUI functions without first
83 // calling wxMutexGuiEnter()
84 static DWORD gs_idMainThread
= 0;
86 // if it's FALSE, some secondary thread is holding the GUI lock
87 static bool gs_bGuiOwnedByMainThread
= TRUE
;
89 // critical section which controls access to all GUI functions: any secondary
90 // thread (i.e. except the main one) must enter this crit section before doing
92 static wxCriticalSection
*gs_critsectGui
= NULL
;
94 // critical section which protects gs_nWaitingForGui variable
95 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
97 // number of threads waiting for GUI in wxMutexGuiEnter()
98 static size_t gs_nWaitingForGui
= 0;
100 // are we waiting for a thread termination?
101 static bool gs_waitingForThread
= FALSE
;
103 // ============================================================================
104 // Windows implementation of thread classes
105 // ============================================================================
107 // ----------------------------------------------------------------------------
108 // wxMutex implementation
109 // ----------------------------------------------------------------------------
111 class wxMutexInternal
116 m_mutex
= ::CreateMutex(NULL
, FALSE
, NULL
);
119 wxLogSysError(_("Can not create mutex"));
123 ~wxMutexInternal() { if ( m_mutex
) CloseHandle(m_mutex
); }
131 m_internal
= new wxMutexInternal
;
140 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
146 wxMutexError
wxMutex::Lock()
150 ret
= WaitForSingleObject(m_internal
->m_mutex
, INFINITE
);
161 wxLogSysError(_("Couldn't acquire a mutex lock"));
162 return wxMUTEX_MISC_ERROR
;
166 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
170 return wxMUTEX_NO_ERROR
;
173 wxMutexError
wxMutex::TryLock()
177 ret
= WaitForSingleObject(m_internal
->m_mutex
, 0);
178 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
182 return wxMUTEX_NO_ERROR
;
185 wxMutexError
wxMutex::Unlock()
190 BOOL ret
= ReleaseMutex(m_internal
->m_mutex
);
193 wxLogSysError(_("Couldn't release a mutex"));
194 return wxMUTEX_MISC_ERROR
;
197 return wxMUTEX_NO_ERROR
;
200 // ----------------------------------------------------------------------------
201 // wxCondition implementation
202 // ----------------------------------------------------------------------------
204 class wxConditionInternal
207 wxConditionInternal()
209 event
= ::CreateEvent(
210 NULL
, // default secutiry
211 FALSE
, // not manual reset
212 FALSE
, // nonsignaled initially
213 NULL
// nameless event
217 wxLogSysError(_("Can not create event object."));
222 bool Wait(DWORD timeout
)
226 // FIXME this should be MsgWaitForMultipleObjects() as well probably
227 DWORD rc
= ::WaitForSingleObject(event
, timeout
);
231 return rc
!= WAIT_TIMEOUT
;
234 ~wxConditionInternal()
238 if ( !::CloseHandle(event
) )
240 wxLogLastError("CloseHandle(event)");
249 wxCondition::wxCondition()
251 m_internal
= new wxConditionInternal
;
254 wxCondition::~wxCondition()
259 void wxCondition::Wait()
261 (void)m_internal
->Wait(INFINITE
);
264 bool wxCondition::Wait(unsigned long sec
,
267 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
270 void wxCondition::Signal()
272 // set the event to signaled: if a thread is already waiting on it, it will
273 // be woken up, otherwise the event will remain in the signaled state until
274 // someone waits on it. In any case, the system will return it to a non
275 // signalled state afterwards. If multiple threads are waiting, only one
277 if ( !::SetEvent(m_internal
->event
) )
279 wxLogLastError("SetEvent");
283 void wxCondition::Broadcast()
285 // this works because all these threads are already waiting and so each
286 // SetEvent() inside Signal() is really a PulseEvent() because the event
287 // state is immediately returned to non-signaled
288 for ( int i
= 0; i
< m_internal
->waiters
; i
++ )
294 // ----------------------------------------------------------------------------
295 // wxCriticalSection implementation
296 // ----------------------------------------------------------------------------
298 wxCriticalSection::wxCriticalSection()
300 wxASSERT_MSG( sizeof(CRITICAL_SECTION
) <= sizeof(m_buffer
),
301 _T("must increase buffer size in wx/thread.h") );
303 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
306 wxCriticalSection::~wxCriticalSection()
308 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
311 void wxCriticalSection::Enter()
313 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
316 void wxCriticalSection::Leave()
318 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
321 // ----------------------------------------------------------------------------
322 // wxThread implementation
323 // ----------------------------------------------------------------------------
325 // wxThreadInternal class
326 // ----------------------
328 class wxThreadInternal
335 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
347 if ( !::CloseHandle(m_hThread
) )
349 wxLogLastError("CloseHandle(thread)");
356 // create a new (suspended) thread (for the given thread object)
357 bool Create(wxThread
*thread
);
359 // suspend/resume/terminate
362 void Cancel() { m_state
= STATE_CANCELED
; }
365 void SetState(wxThreadState state
) { m_state
= state
; }
366 wxThreadState
GetState() const { return m_state
; }
369 void SetPriority(unsigned int priority
);
370 unsigned int GetPriority() const { return m_priority
; }
372 // thread handle and id
373 HANDLE
GetHandle() const { return m_hThread
; }
374 DWORD
GetId() const { return m_tid
; }
377 static DWORD
WinThreadStart(wxThread
*thread
);
380 HANDLE m_hThread
; // handle of the thread
381 wxThreadState m_state
; // state, see wxThreadState enum
382 unsigned int m_priority
; // thread priority in "wx" units
383 DWORD m_tid
; // thread id
386 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
388 // first of all, check whether we hadn't been cancelled already
389 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
394 // store the thread object in the TLS
395 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
397 wxLogSysError(_("Can not start thread: error writing TLS."));
402 DWORD rc
= (DWORD
)thread
->Entry();
404 // enter m_critsect before changing the thread state
405 thread
->m_critsect
.Enter();
406 bool wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
407 thread
->m_internal
->SetState(STATE_EXITED
);
408 thread
->m_critsect
.Leave();
412 // if the thread was cancelled (from Delete()), then it the handle is still
414 if ( thread
->IsDetached() && !wasCancelled
)
419 //else: the joinable threads handle will be closed when Wait() is done
424 void wxThreadInternal::SetPriority(unsigned int priority
)
426 m_priority
= priority
;
428 // translate wxWindows priority to the Windows one
430 if (m_priority
<= 20)
431 win_priority
= THREAD_PRIORITY_LOWEST
;
432 else if (m_priority
<= 40)
433 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
434 else if (m_priority
<= 60)
435 win_priority
= THREAD_PRIORITY_NORMAL
;
436 else if (m_priority
<= 80)
437 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
438 else if (m_priority
<= 100)
439 win_priority
= THREAD_PRIORITY_HIGHEST
;
442 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
443 win_priority
= THREAD_PRIORITY_NORMAL
;
446 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
448 wxLogSysError(_("Can't set thread priority"));
452 bool wxThreadInternal::Create(wxThread
*thread
)
454 // for compilers which have it, we should use C RTL function for thread
455 // creation instead of Win32 API one because otherwise we will have memory
456 // leaks if the thread uses C RTL (and most threads do)
457 #if defined(__VISUALC__) || \
458 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) \\
459 (defined(__GNUG__) && defined(__MSVCRT__)
460 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
462 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
464 wxThreadInternal::WinThreadStart
,
465 thread
, CREATE_SUSPENDED
,
466 (unsigned int *)&m_tid
);
467 #else // compiler doesn't have _beginthreadex
468 m_hThread
= ::CreateThread
470 NULL
, // default security
471 0, // default stack size
472 (LPTHREAD_START_ROUTINE
) // thread entry point
473 wxThreadInternal::WinThreadStart
, //
474 (LPVOID
)thread
, // parameter
475 CREATE_SUSPENDED
, // flags
476 &m_tid
// [out] thread id
478 #endif // _beginthreadex/CreateThread
480 if ( m_hThread
== NULL
)
482 wxLogSysError(_("Can't create thread"));
487 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
489 SetPriority(m_priority
);
495 bool wxThreadInternal::Suspend()
497 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
498 if ( nSuspendCount
== (DWORD
)-1 )
500 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
505 m_state
= STATE_PAUSED
;
510 bool wxThreadInternal::Resume()
512 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
513 if ( nSuspendCount
== (DWORD
)-1 )
515 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
520 m_state
= STATE_RUNNING
;
528 wxThread
*wxThread::This()
530 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
532 // be careful, 0 may be a valid return value as well
533 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
535 wxLogSysError(_("Couldn't get the current thread pointer"));
543 bool wxThread::IsMain()
545 return ::GetCurrentThreadId() == gs_idMainThread
;
552 void wxThread::Yield()
554 // 0 argument to Sleep() is special and means to just give away the rest of
559 void wxThread::Sleep(unsigned long milliseconds
)
561 ::Sleep(milliseconds
);
564 int wxThread::GetCPUCount()
569 return si
.dwNumberOfProcessors
;
572 bool wxThread::SetConcurrency(size_t level
)
574 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
576 // ok only for the default one
580 // get system affinity mask first
581 HANDLE hProcess
= ::GetCurrentProcess();
582 DWORD dwProcMask
, dwSysMask
;
583 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
585 wxLogLastError(_T("GetProcessAffinityMask"));
590 // how many CPUs have we got?
591 if ( dwSysMask
== 1 )
593 // don't bother with all this complicated stuff - on a single
594 // processor system it doesn't make much sense anyhow
598 // calculate the process mask: it's a bit vector with one bit per
599 // processor; we want to schedule the process to run on first level
604 if ( dwSysMask
& bit
)
606 // ok, we can set this bit
609 // another process added
621 // could we set all bits?
624 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
629 // set it: we can't link to SetProcessAffinityMask() because it doesn't
630 // exist in Win9x, use RT binding instead
632 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
634 // can use static var because we're always in the main thread here
635 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
637 if ( !pfnSetProcessAffinityMask
)
639 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
642 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
643 ::GetProcAddress(hModKernel
,
644 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
645 "SetProcessAffinityMask");
647 _T("SetProcessAffinityMask"));
651 // we've discovered a MT version of Win9x!
652 wxASSERT_MSG( pfnSetProcessAffinityMask
,
653 _T("this system has several CPUs but no "
654 "SetProcessAffinityMask function?") );
657 if ( !pfnSetProcessAffinityMask
)
659 // msg given above - do it only once
663 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
665 wxLogLastError(_T("SetProcessAffinityMask"));
676 wxThread::wxThread(wxThreadKind kind
)
678 m_internal
= new wxThreadInternal();
680 m_isDetached
= kind
== wxTHREAD_DETACHED
;
683 wxThread::~wxThread()
688 // create/start thread
689 // -------------------
691 wxThreadError
wxThread::Create()
693 wxCriticalSectionLocker
lock(m_critsect
);
695 if ( !m_internal
->Create(this) )
696 return wxTHREAD_NO_RESOURCE
;
698 return wxTHREAD_NO_ERROR
;
701 wxThreadError
wxThread::Run()
703 wxCriticalSectionLocker
lock(m_critsect
);
705 if ( m_internal
->GetState() != STATE_NEW
)
707 // actually, it may be almost any state at all, not only STATE_RUNNING
708 return wxTHREAD_RUNNING
;
711 // the thread has just been created and is still suspended - let it run
715 // suspend/resume thread
716 // ---------------------
718 wxThreadError
wxThread::Pause()
720 wxCriticalSectionLocker
lock(m_critsect
);
722 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
725 wxThreadError
wxThread::Resume()
727 wxCriticalSectionLocker
lock(m_critsect
);
729 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
735 wxThread::ExitCode
wxThread::Wait()
737 // although under Windows we can wait for any thread, it's an error to
738 // wait for a detached one in wxWin API
739 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
740 _T("can't wait for detached thread") );
742 ExitCode rc
= (ExitCode
)-1;
751 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
755 // Delete() is always safe to call, so consider all possible states
757 // has the thread started to run?
758 bool shouldResume
= FALSE
;
761 wxCriticalSectionLocker
lock(m_critsect
);
763 if ( m_internal
->GetState() == STATE_NEW
)
765 // WinThreadStart() will see it and terminate immediately
766 m_internal
->SetState(STATE_EXITED
);
772 // is the thread paused?
773 if ( shouldResume
|| IsPaused() )
776 HANDLE hThread
= m_internal
->GetHandle();
778 // does is still run?
783 // set flag for wxIsWaitingForThread()
784 gs_waitingForThread
= TRUE
;
791 // ask the thread to terminate
793 wxCriticalSectionLocker
lock(m_critsect
);
795 m_internal
->Cancel();
799 // we can't just wait for the thread to terminate because it might be
800 // calling some GUI functions and so it will never terminate before we
801 // process the Windows messages that result from these functions
805 result
= ::MsgWaitForMultipleObjects
807 1, // number of objects to wait for
808 &hThread
, // the objects
809 FALSE
, // don't wait for all objects
810 INFINITE
, // no timeout
811 QS_ALLEVENTS
// return as soon as there are any events
818 wxLogSysError(_("Can not wait for thread termination"));
820 return wxTHREAD_KILLED
;
823 // thread we're waiting for terminated
826 case WAIT_OBJECT_0
+ 1:
827 // new message arrived, process it
828 if ( !wxTheApp
->DoMessage() )
830 // WM_QUIT received: kill the thread
833 return wxTHREAD_KILLED
;
838 // give the thread we're waiting for chance to exit
839 // from the GUI call it might have been in
840 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
849 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
851 } while ( result
!= WAIT_OBJECT_0
);
853 // simply wait for the thread to terminate
855 // OTOH, even console apps create windows (in wxExecute, for WinSock
856 // &c), so may be use MsgWaitForMultipleObject() too here?
857 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
859 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
861 #endif // wxUSE_GUI/!wxUSE_GUI
865 gs_waitingForThread
= FALSE
;
873 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
875 wxLogLastError("GetExitCodeThread");
882 // if the thread exits normally, this is done in WinThreadStart, but in
883 // this case it would have been too early because
884 // MsgWaitForMultipleObject() would fail if the therad handle was
885 // closed while we were waiting on it, so we must do it here
889 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
890 wxT("thread must be already terminated.") );
895 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
898 wxThreadError
wxThread::Kill()
901 return wxTHREAD_NOT_RUNNING
;
903 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
905 wxLogSysError(_("Couldn't terminate thread"));
907 return wxTHREAD_MISC_ERROR
;
917 return wxTHREAD_NO_ERROR
;
920 void wxThread::Exit(ExitCode status
)
929 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
930 _endthreadex((unsigned)status
);
932 ::ExitThread((DWORD
)status
);
935 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
941 void wxThread::SetPriority(unsigned int prio
)
943 wxCriticalSectionLocker
lock(m_critsect
);
945 m_internal
->SetPriority(prio
);
948 unsigned int wxThread::GetPriority() const
950 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
952 return m_internal
->GetPriority();
955 unsigned long wxThread::GetId() const
957 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
959 return (unsigned long)m_internal
->GetId();
962 bool wxThread::IsRunning() const
964 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
966 return m_internal
->GetState() == STATE_RUNNING
;
969 bool wxThread::IsAlive() const
971 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
973 return (m_internal
->GetState() == STATE_RUNNING
) ||
974 (m_internal
->GetState() == STATE_PAUSED
);
977 bool wxThread::IsPaused() const
979 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
981 return m_internal
->GetState() == STATE_PAUSED
;
984 bool wxThread::TestDestroy()
986 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
988 return m_internal
->GetState() == STATE_CANCELED
;
991 // ----------------------------------------------------------------------------
992 // Automatic initialization for thread module
993 // ----------------------------------------------------------------------------
995 class wxThreadModule
: public wxModule
998 virtual bool OnInit();
999 virtual void OnExit();
1002 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1005 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1007 bool wxThreadModule::OnInit()
1009 // allocate TLS index for storing the pointer to the current thread
1010 gs_tlsThisThread
= ::TlsAlloc();
1011 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1013 // in normal circumstances it will only happen if all other
1014 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1015 // words, this should never happen
1016 wxLogSysError(_("Thread module initialization failed: "
1017 "impossible to allocate index in thread "
1023 // main thread doesn't have associated wxThread object, so store 0 in the
1025 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1027 ::TlsFree(gs_tlsThisThread
);
1028 gs_tlsThisThread
= 0xFFFFFFFF;
1030 wxLogSysError(_("Thread module initialization failed: "
1031 "can not store value in thread local storage"));
1036 gs_critsectWaitingForGui
= new wxCriticalSection();
1038 gs_critsectGui
= new wxCriticalSection();
1039 gs_critsectGui
->Enter();
1041 // no error return for GetCurrentThreadId()
1042 gs_idMainThread
= ::GetCurrentThreadId();
1047 void wxThreadModule::OnExit()
1049 if ( !::TlsFree(gs_tlsThisThread
) )
1051 wxLogLastError("TlsFree failed.");
1054 if ( gs_critsectGui
)
1056 gs_critsectGui
->Leave();
1057 delete gs_critsectGui
;
1058 gs_critsectGui
= NULL
;
1061 delete gs_critsectWaitingForGui
;
1062 gs_critsectWaitingForGui
= NULL
;
1065 // ----------------------------------------------------------------------------
1066 // under Windows, these functions are implemented using a critical section and
1067 // not a mutex, so the names are a bit confusing
1068 // ----------------------------------------------------------------------------
1070 void WXDLLEXPORT
wxMutexGuiEnter()
1072 // this would dead lock everything...
1073 wxASSERT_MSG( !wxThread::IsMain(),
1074 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1076 // the order in which we enter the critical sections here is crucial!!
1078 // set the flag telling to the main thread that we want to do some GUI
1080 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1082 gs_nWaitingForGui
++;
1085 wxWakeUpMainThread();
1087 // now we may block here because the main thread will soon let us in
1088 // (during the next iteration of OnIdle())
1089 gs_critsectGui
->Enter();
1092 void WXDLLEXPORT
wxMutexGuiLeave()
1094 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1096 if ( wxThread::IsMain() )
1098 gs_bGuiOwnedByMainThread
= FALSE
;
1102 // decrement the number of waiters now
1103 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1104 wxT("calling wxMutexGuiLeave() without entering it first?") );
1106 gs_nWaitingForGui
--;
1108 wxWakeUpMainThread();
1111 gs_critsectGui
->Leave();
1114 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1116 wxASSERT_MSG( wxThread::IsMain(),
1117 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1119 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1121 if ( gs_nWaitingForGui
== 0 )
1123 // no threads are waiting for GUI - so we may acquire the lock without
1124 // any danger (but only if we don't already have it)
1125 if ( !wxGuiOwnedByMainThread() )
1127 gs_critsectGui
->Enter();
1129 gs_bGuiOwnedByMainThread
= TRUE
;
1131 //else: already have it, nothing to do
1135 // some threads are waiting, release the GUI lock if we have it
1136 if ( wxGuiOwnedByMainThread() )
1140 //else: some other worker thread is doing GUI
1144 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1146 return gs_bGuiOwnedByMainThread
;
1149 // wake up the main thread if it's in ::GetMessage()
1150 void WXDLLEXPORT
wxWakeUpMainThread()
1152 // sending any message would do - hopefully WM_NULL is harmless enough
1153 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1155 // should never happen
1156 wxLogLastError("PostThreadMessage(WM_NULL)");
1160 bool WXDLLEXPORT
wxIsWaitingForThread()
1162 return gs_waitingForThread
;
1165 #endif // wxUSE_THREADS