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__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
458 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
460 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
462 wxThreadInternal::WinThreadStart
,
463 thread
, CREATE_SUSPENDED
,
464 (unsigned int *)&m_tid
);
466 m_hThread
= ::CreateThread
468 NULL
, // default security
469 0, // default stack size
470 (LPTHREAD_START_ROUTINE
) // thread entry point
471 wxThreadInternal::WinThreadStart
, //
472 (LPVOID
)thread
, // parameter
473 CREATE_SUSPENDED
, // flags
474 &m_tid
// [out] thread id
478 if ( m_hThread
== NULL
)
480 wxLogSysError(_("Can't create thread"));
485 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
487 SetPriority(m_priority
);
493 bool wxThreadInternal::Suspend()
495 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
496 if ( nSuspendCount
== (DWORD
)-1 )
498 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
503 m_state
= STATE_PAUSED
;
508 bool wxThreadInternal::Resume()
510 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
511 if ( nSuspendCount
== (DWORD
)-1 )
513 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
518 m_state
= STATE_RUNNING
;
526 wxThread
*wxThread::This()
528 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
530 // be careful, 0 may be a valid return value as well
531 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
533 wxLogSysError(_("Couldn't get the current thread pointer"));
541 bool wxThread::IsMain()
543 return ::GetCurrentThreadId() == gs_idMainThread
;
550 void wxThread::Yield()
552 // 0 argument to Sleep() is special and means to just give away the rest of
557 void wxThread::Sleep(unsigned long milliseconds
)
559 ::Sleep(milliseconds
);
562 int wxThread::GetCPUCount()
567 return si
.dwNumberOfProcessors
;
570 bool wxThread::SetConcurrency(size_t level
)
572 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
574 // ok only for the default one
578 // get system affinity mask first
579 HANDLE hProcess
= ::GetCurrentProcess();
580 DWORD dwProcMask
, dwSysMask
;
581 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
583 wxLogLastError(_T("GetProcessAffinityMask"));
588 // how many CPUs have we got?
589 if ( dwSysMask
== 1 )
591 // don't bother with all this complicated stuff - on a single
592 // processor system it doesn't make much sense anyhow
596 // calculate the process mask: it's a bit vector with one bit per
597 // processor; we want to schedule the process to run on first level
602 if ( dwSysMask
& bit
)
604 // ok, we can set this bit
607 // another process added
619 // could we set all bits?
622 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
627 // set it: we can't link to SetProcessAffinityMask() because it doesn't
628 // exist in Win9x, use RT binding instead
630 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
632 // can use static var because we're always in the main thread here
633 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
635 if ( !pfnSetProcessAffinityMask
)
637 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
640 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
641 ::GetProcAddress(hModKernel
,
642 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
643 "SetProcessAffinityMask");
645 _T("SetProcessAffinityMask"));
649 // we've discovered a MT version of Win9x!
650 wxASSERT_MSG( pfnSetProcessAffinityMask
,
651 _T("this system has several CPUs but no "
652 "SetProcessAffinityMask function?") );
655 if ( !pfnSetProcessAffinityMask
)
657 // msg given above - do it only once
661 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
663 wxLogLastError(_T("SetProcessAffinityMask"));
674 wxThread::wxThread(wxThreadKind kind
)
676 m_internal
= new wxThreadInternal();
678 m_isDetached
= kind
== wxTHREAD_DETACHED
;
681 wxThread::~wxThread()
686 // create/start thread
687 // -------------------
689 wxThreadError
wxThread::Create()
691 wxCriticalSectionLocker
lock(m_critsect
);
693 if ( !m_internal
->Create(this) )
694 return wxTHREAD_NO_RESOURCE
;
696 return wxTHREAD_NO_ERROR
;
699 wxThreadError
wxThread::Run()
701 wxCriticalSectionLocker
lock(m_critsect
);
703 if ( m_internal
->GetState() != STATE_NEW
)
705 // actually, it may be almost any state at all, not only STATE_RUNNING
706 return wxTHREAD_RUNNING
;
709 // the thread has just been created and is still suspended - let it run
713 // suspend/resume thread
714 // ---------------------
716 wxThreadError
wxThread::Pause()
718 wxCriticalSectionLocker
lock(m_critsect
);
720 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
723 wxThreadError
wxThread::Resume()
725 wxCriticalSectionLocker
lock(m_critsect
);
727 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
733 wxThread::ExitCode
wxThread::Wait()
735 // although under Windows we can wait for any thread, it's an error to
736 // wait for a detached one in wxWin API
737 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
738 _T("can't wait for detached thread") );
740 ExitCode rc
= (ExitCode
)-1;
749 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
753 // Delete() is always safe to call, so consider all possible states
755 // has the thread started to run?
756 bool shouldResume
= FALSE
;
759 wxCriticalSectionLocker
lock(m_critsect
);
761 if ( m_internal
->GetState() == STATE_NEW
)
763 // WinThreadStart() will see it and terminate immediately
764 m_internal
->SetState(STATE_EXITED
);
770 // is the thread paused?
771 if ( shouldResume
|| IsPaused() )
774 HANDLE hThread
= m_internal
->GetHandle();
776 // does is still run?
781 // set flag for wxIsWaitingForThread()
782 gs_waitingForThread
= TRUE
;
789 // ask the thread to terminate
791 wxCriticalSectionLocker
lock(m_critsect
);
793 m_internal
->Cancel();
797 // we can't just wait for the thread to terminate because it might be
798 // calling some GUI functions and so it will never terminate before we
799 // process the Windows messages that result from these functions
803 result
= ::MsgWaitForMultipleObjects
805 1, // number of objects to wait for
806 &hThread
, // the objects
807 FALSE
, // don't wait for all objects
808 INFINITE
, // no timeout
809 QS_ALLEVENTS
// return as soon as there are any events
816 wxLogSysError(_("Can not wait for thread termination"));
818 return wxTHREAD_KILLED
;
821 // thread we're waiting for terminated
824 case WAIT_OBJECT_0
+ 1:
825 // new message arrived, process it
826 if ( !wxTheApp
->DoMessage() )
828 // WM_QUIT received: kill the thread
831 return wxTHREAD_KILLED
;
836 // give the thread we're waiting for chance to exit
837 // from the GUI call it might have been in
838 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
847 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
849 } while ( result
!= WAIT_OBJECT_0
);
851 // simply wait for the thread to terminate
853 // OTOH, even console apps create windows (in wxExecute, for WinSock
854 // &c), so may be use MsgWaitForMultipleObject() too here?
855 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
857 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
859 #endif // wxUSE_GUI/!wxUSE_GUI
863 gs_waitingForThread
= FALSE
;
871 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
873 wxLogLastError("GetExitCodeThread");
880 // if the thread exits normally, this is done in WinThreadStart, but in
881 // this case it would have been too early because
882 // MsgWaitForMultipleObject() would fail if the therad handle was
883 // closed while we were waiting on it, so we must do it here
887 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
888 wxT("thread must be already terminated.") );
893 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
896 wxThreadError
wxThread::Kill()
899 return wxTHREAD_NOT_RUNNING
;
901 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
903 wxLogSysError(_("Couldn't terminate thread"));
905 return wxTHREAD_MISC_ERROR
;
915 return wxTHREAD_NO_ERROR
;
918 void wxThread::Exit(ExitCode status
)
927 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
928 _endthreadex((unsigned)status
);
930 ::ExitThread((DWORD
)status
);
933 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
939 void wxThread::SetPriority(unsigned int prio
)
941 wxCriticalSectionLocker
lock(m_critsect
);
943 m_internal
->SetPriority(prio
);
946 unsigned int wxThread::GetPriority() const
948 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
950 return m_internal
->GetPriority();
953 unsigned long wxThread::GetId() const
955 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
957 return (unsigned long)m_internal
->GetId();
960 bool wxThread::IsRunning() const
962 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
964 return m_internal
->GetState() == STATE_RUNNING
;
967 bool wxThread::IsAlive() const
969 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
971 return (m_internal
->GetState() == STATE_RUNNING
) ||
972 (m_internal
->GetState() == STATE_PAUSED
);
975 bool wxThread::IsPaused() const
977 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
979 return m_internal
->GetState() == STATE_PAUSED
;
982 bool wxThread::TestDestroy()
984 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
986 return m_internal
->GetState() == STATE_CANCELED
;
989 // ----------------------------------------------------------------------------
990 // Automatic initialization for thread module
991 // ----------------------------------------------------------------------------
993 class wxThreadModule
: public wxModule
996 virtual bool OnInit();
997 virtual void OnExit();
1000 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1003 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1005 bool wxThreadModule::OnInit()
1007 // allocate TLS index for storing the pointer to the current thread
1008 gs_tlsThisThread
= ::TlsAlloc();
1009 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1011 // in normal circumstances it will only happen if all other
1012 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1013 // words, this should never happen
1014 wxLogSysError(_("Thread module initialization failed: "
1015 "impossible to allocate index in thread "
1021 // main thread doesn't have associated wxThread object, so store 0 in the
1023 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1025 ::TlsFree(gs_tlsThisThread
);
1026 gs_tlsThisThread
= 0xFFFFFFFF;
1028 wxLogSysError(_("Thread module initialization failed: "
1029 "can not store value in thread local storage"));
1034 gs_critsectWaitingForGui
= new wxCriticalSection();
1036 gs_critsectGui
= new wxCriticalSection();
1037 gs_critsectGui
->Enter();
1039 // no error return for GetCurrentThreadId()
1040 gs_idMainThread
= ::GetCurrentThreadId();
1045 void wxThreadModule::OnExit()
1047 if ( !::TlsFree(gs_tlsThisThread
) )
1049 wxLogLastError("TlsFree failed.");
1052 if ( gs_critsectGui
)
1054 gs_critsectGui
->Leave();
1055 delete gs_critsectGui
;
1056 gs_critsectGui
= NULL
;
1059 delete gs_critsectWaitingForGui
;
1060 gs_critsectWaitingForGui
= NULL
;
1063 // ----------------------------------------------------------------------------
1064 // under Windows, these functions are implemented using a critical section and
1065 // not a mutex, so the names are a bit confusing
1066 // ----------------------------------------------------------------------------
1068 void WXDLLEXPORT
wxMutexGuiEnter()
1070 // this would dead lock everything...
1071 wxASSERT_MSG( !wxThread::IsMain(),
1072 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1074 // the order in which we enter the critical sections here is crucial!!
1076 // set the flag telling to the main thread that we want to do some GUI
1078 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1080 gs_nWaitingForGui
++;
1083 wxWakeUpMainThread();
1085 // now we may block here because the main thread will soon let us in
1086 // (during the next iteration of OnIdle())
1087 gs_critsectGui
->Enter();
1090 void WXDLLEXPORT
wxMutexGuiLeave()
1092 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1094 if ( wxThread::IsMain() )
1096 gs_bGuiOwnedByMainThread
= FALSE
;
1100 // decrement the number of waiters now
1101 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1102 wxT("calling wxMutexGuiLeave() without entering it first?") );
1104 gs_nWaitingForGui
--;
1106 wxWakeUpMainThread();
1109 gs_critsectGui
->Leave();
1112 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1114 wxASSERT_MSG( wxThread::IsMain(),
1115 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1117 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1119 if ( gs_nWaitingForGui
== 0 )
1121 // no threads are waiting for GUI - so we may acquire the lock without
1122 // any danger (but only if we don't already have it)
1123 if ( !wxGuiOwnedByMainThread() )
1125 gs_critsectGui
->Enter();
1127 gs_bGuiOwnedByMainThread
= TRUE
;
1129 //else: already have it, nothing to do
1133 // some threads are waiting, release the GUI lock if we have it
1134 if ( wxGuiOwnedByMainThread() )
1138 //else: some other worker thread is doing GUI
1142 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1144 return gs_bGuiOwnedByMainThread
;
1147 // wake up the main thread if it's in ::GetMessage()
1148 void WXDLLEXPORT
wxWakeUpMainThread()
1150 // sending any message would do - hopefully WM_NULL is harmless enough
1151 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1153 // should never happen
1154 wxLogLastError("PostThreadMessage(WM_NULL)");
1158 bool WXDLLEXPORT
wxIsWaitingForThread()
1160 return gs_waitingForThread
;
1163 #endif // wxUSE_THREADS