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))
48 // ----------------------------------------------------------------------------
50 // ----------------------------------------------------------------------------
52 // the possible states of the thread ("=>" shows all possible transitions from
56 STATE_NEW
, // didn't start execution yet (=> RUNNING)
57 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
58 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
59 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
60 STATE_EXITED
// thread is terminating
63 // ----------------------------------------------------------------------------
64 // this module globals
65 // ----------------------------------------------------------------------------
67 // TLS index of the slot where we store the pointer to the current thread
68 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
70 // id of the main thread - the one which can call GUI functions without first
71 // calling wxMutexGuiEnter()
72 static DWORD gs_idMainThread
= 0;
74 // if it's FALSE, some secondary thread is holding the GUI lock
75 static bool gs_bGuiOwnedByMainThread
= TRUE
;
77 // critical section which controls access to all GUI functions: any secondary
78 // thread (i.e. except the main one) must enter this crit section before doing
80 static wxCriticalSection
*gs_critsectGui
= NULL
;
82 // critical section which protects gs_nWaitingForGui variable
83 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
85 // number of threads waiting for GUI in wxMutexGuiEnter()
86 static size_t gs_nWaitingForGui
= 0;
88 // are we waiting for a thread termination?
89 static bool gs_waitingForThread
= FALSE
;
91 // ============================================================================
92 // Windows implementation of thread classes
93 // ============================================================================
95 // ----------------------------------------------------------------------------
96 // wxMutex implementation
97 // ----------------------------------------------------------------------------
104 m_mutex
= ::CreateMutex(NULL
, FALSE
, NULL
);
107 wxLogSysError(_("Can not create mutex"));
111 ~wxMutexInternal() { if ( m_mutex
) CloseHandle(m_mutex
); }
119 m_internal
= new wxMutexInternal
;
128 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
134 wxMutexError
wxMutex::Lock()
138 ret
= WaitForSingleObject(m_internal
->m_mutex
, INFINITE
);
149 wxLogSysError(_("Couldn't acquire a mutex lock"));
150 return wxMUTEX_MISC_ERROR
;
154 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
158 return wxMUTEX_NO_ERROR
;
161 wxMutexError
wxMutex::TryLock()
165 ret
= WaitForSingleObject(m_internal
->m_mutex
, 0);
166 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
170 return wxMUTEX_NO_ERROR
;
173 wxMutexError
wxMutex::Unlock()
178 BOOL ret
= ReleaseMutex(m_internal
->m_mutex
);
181 wxLogSysError(_("Couldn't release a mutex"));
182 return wxMUTEX_MISC_ERROR
;
185 return wxMUTEX_NO_ERROR
;
188 // ----------------------------------------------------------------------------
189 // wxCondition implementation
190 // ----------------------------------------------------------------------------
192 class wxConditionInternal
195 wxConditionInternal()
197 event
= ::CreateEvent(
198 NULL
, // default secutiry
199 FALSE
, // not manual reset
200 FALSE
, // nonsignaled initially
201 NULL
// nameless event
205 wxLogSysError(_("Can not create event object."));
210 bool Wait(DWORD timeout
)
214 // FIXME this should be MsgWaitForMultipleObjects() as well probably
215 DWORD rc
= ::WaitForSingleObject(event
, timeout
);
219 return rc
!= WAIT_TIMEOUT
;
222 ~wxConditionInternal()
226 if ( !::CloseHandle(event
) )
228 wxLogLastError("CloseHandle(event)");
237 wxCondition::wxCondition()
239 m_internal
= new wxConditionInternal
;
242 wxCondition::~wxCondition()
247 void wxCondition::Wait()
249 (void)m_internal
->Wait(INFINITE
);
252 bool wxCondition::Wait(unsigned long sec
,
255 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
258 void wxCondition::Signal()
260 // set the event to signaled: if a thread is already waiting on it, it will
261 // be woken up, otherwise the event will remain in the signaled state until
262 // someone waits on it. In any case, the system will return it to a non
263 // signalled state afterwards. If multiple threads are waiting, only one
265 if ( !::SetEvent(m_internal
->event
) )
267 wxLogLastError("SetEvent");
271 void wxCondition::Broadcast()
273 // this works because all these threads are already waiting and so each
274 // SetEvent() inside Signal() is really a PulseEvent() because the event
275 // state is immediately returned to non-signaled
276 for ( int i
= 0; i
< m_internal
->waiters
; i
++ )
282 // ----------------------------------------------------------------------------
283 // wxCriticalSection implementation
284 // ----------------------------------------------------------------------------
286 wxCriticalSection::wxCriticalSection()
288 wxASSERT_MSG( sizeof(CRITICAL_SECTION
) <= sizeof(m_buffer
),
289 _T("must increase buffer size in wx/thread.h") );
291 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
294 wxCriticalSection::~wxCriticalSection()
296 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
299 void wxCriticalSection::Enter()
301 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
304 void wxCriticalSection::Leave()
306 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
309 // ----------------------------------------------------------------------------
310 // wxThread implementation
311 // ----------------------------------------------------------------------------
313 // wxThreadInternal class
314 // ----------------------
316 class wxThreadInternal
323 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
335 if ( !::CloseHandle(m_hThread
) )
337 wxLogLastError("CloseHandle(thread)");
344 // create a new (suspended) thread (for the given thread object)
345 bool Create(wxThread
*thread
);
347 // suspend/resume/terminate
350 void Cancel() { m_state
= STATE_CANCELED
; }
353 void SetState(wxThreadState state
) { m_state
= state
; }
354 wxThreadState
GetState() const { return m_state
; }
357 void SetPriority(unsigned int priority
);
358 unsigned int GetPriority() const { return m_priority
; }
360 // thread handle and id
361 HANDLE
GetHandle() const { return m_hThread
; }
362 DWORD
GetId() const { return m_tid
; }
365 static DWORD
WinThreadStart(wxThread
*thread
);
368 HANDLE m_hThread
; // handle of the thread
369 wxThreadState m_state
; // state, see wxThreadState enum
370 unsigned int m_priority
; // thread priority in "wx" units
371 DWORD m_tid
; // thread id
374 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
376 // first of all, check whether we hadn't been cancelled already
377 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
382 // store the thread object in the TLS
383 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
385 wxLogSysError(_("Can not start thread: error writing TLS."));
390 DWORD rc
= (DWORD
)thread
->Entry();
392 // enter m_critsect before changing the thread state
393 thread
->m_critsect
.Enter();
394 bool wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
395 thread
->m_internal
->SetState(STATE_EXITED
);
396 thread
->m_critsect
.Leave();
400 // if the thread was cancelled (from Delete()), then it the handle is still
402 if ( thread
->IsDetached() && !wasCancelled
)
407 //else: the joinable threads handle will be closed when Wait() is done
412 void wxThreadInternal::SetPriority(unsigned int priority
)
414 m_priority
= priority
;
416 // translate wxWindows priority to the Windows one
418 if (m_priority
<= 20)
419 win_priority
= THREAD_PRIORITY_LOWEST
;
420 else if (m_priority
<= 40)
421 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
422 else if (m_priority
<= 60)
423 win_priority
= THREAD_PRIORITY_NORMAL
;
424 else if (m_priority
<= 80)
425 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
426 else if (m_priority
<= 100)
427 win_priority
= THREAD_PRIORITY_HIGHEST
;
430 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
431 win_priority
= THREAD_PRIORITY_NORMAL
;
434 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
436 wxLogSysError(_("Can't set thread priority"));
440 bool wxThreadInternal::Create(wxThread
*thread
)
442 // for compilers which have it, we should use C RTL function for thread
443 // creation instead of Win32 API one because otherwise we will have memory
444 // leaks if the thread uses C RTL (and most threads do)
445 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
446 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
448 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
450 wxThreadInternal::WinThreadStart
,
451 thread
, CREATE_SUSPENDED
,
452 (unsigned int *)&m_tid
);
454 m_hThread
= ::CreateThread
456 NULL
, // default security
457 0, // default stack size
458 (LPTHREAD_START_ROUTINE
) // thread entry point
459 wxThreadInternal::WinThreadStart
, //
460 (LPVOID
)thread
, // parameter
461 CREATE_SUSPENDED
, // flags
462 &m_tid
// [out] thread id
466 if ( m_hThread
== NULL
)
468 wxLogSysError(_("Can't create thread"));
473 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
475 SetPriority(m_priority
);
481 bool wxThreadInternal::Suspend()
483 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
484 if ( nSuspendCount
== (DWORD
)-1 )
486 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
491 m_state
= STATE_PAUSED
;
496 bool wxThreadInternal::Resume()
498 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
499 if ( nSuspendCount
== (DWORD
)-1 )
501 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
506 m_state
= STATE_RUNNING
;
514 wxThread
*wxThread::This()
516 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
518 // be careful, 0 may be a valid return value as well
519 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
521 wxLogSysError(_("Couldn't get the current thread pointer"));
529 bool wxThread::IsMain()
531 return ::GetCurrentThreadId() == gs_idMainThread
;
538 void wxThread::Yield()
540 // 0 argument to Sleep() is special and means to just give away the rest of
545 void wxThread::Sleep(unsigned long milliseconds
)
547 ::Sleep(milliseconds
);
550 int wxThread::GetCPUCount()
555 return si
.dwNumberOfProcessors
;
558 bool wxThread::SetConcurrency(size_t level
)
560 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
562 // ok only for the default one
566 // get system affinity mask first
567 HANDLE hProcess
= ::GetCurrentProcess();
568 DWORD dwProcMask
, dwSysMask
;
569 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
571 wxLogLastError(_T("GetProcessAffinityMask"));
576 // how many CPUs have we got?
577 if ( dwSysMask
== 1 )
579 // don't bother with all this complicated stuff - on a single
580 // processor system it doesn't make much sense anyhow
584 // calculate the process mask: it's a bit vector with one bit per
585 // processor; we want to schedule the process to run on first level
590 if ( dwSysMask
& bit
)
592 // ok, we can set this bit
595 // another process added
607 // could we set all bits?
610 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
615 // set it: we can't link to SetProcessAffinityMask() because it doesn't
616 // exist in Win9x, use RT binding instead
618 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
620 // can use static var because we're always in the main thread here
621 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
623 if ( !pfnSetProcessAffinityMask
)
625 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
628 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
629 ::GetProcAddress(hModKernel
,
630 #if defined(__BORLANDC__) && (__BORLANDC__ <= 0x520)
631 "SetProcessAffinityMask");
633 _T("SetProcessAffinityMask"));
637 // we've discovered a MT version of Win9x!
638 wxASSERT_MSG( pfnSetProcessAffinityMask
,
639 _T("this system has several CPUs but no "
640 "SetProcessAffinityMask function?") );
643 if ( !pfnSetProcessAffinityMask
)
645 // msg given above - do it only once
649 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
651 wxLogLastError(_T("SetProcessAffinityMask"));
662 wxThread::wxThread(wxThreadKind kind
)
664 m_internal
= new wxThreadInternal();
666 m_isDetached
= kind
== wxTHREAD_DETACHED
;
669 wxThread::~wxThread()
674 // create/start thread
675 // -------------------
677 wxThreadError
wxThread::Create()
679 wxCriticalSectionLocker
lock(m_critsect
);
681 if ( !m_internal
->Create(this) )
682 return wxTHREAD_NO_RESOURCE
;
684 return wxTHREAD_NO_ERROR
;
687 wxThreadError
wxThread::Run()
689 wxCriticalSectionLocker
lock(m_critsect
);
691 if ( m_internal
->GetState() != STATE_NEW
)
693 // actually, it may be almost any state at all, not only STATE_RUNNING
694 return wxTHREAD_RUNNING
;
697 // the thread has just been created and is still suspended - let it run
701 // suspend/resume thread
702 // ---------------------
704 wxThreadError
wxThread::Pause()
706 wxCriticalSectionLocker
lock(m_critsect
);
708 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
711 wxThreadError
wxThread::Resume()
713 wxCriticalSectionLocker
lock(m_critsect
);
715 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
721 wxThread::ExitCode
wxThread::Wait()
723 // although under Windows we can wait for any thread, it's an error to
724 // wait for a detached one in wxWin API
725 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
726 _T("can't wait for detached thread") );
728 ExitCode rc
= (ExitCode
)-1;
737 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
741 // Delete() is always safe to call, so consider all possible states
743 // has the thread started to run?
744 bool shouldResume
= FALSE
;
747 wxCriticalSectionLocker
lock(m_critsect
);
749 if ( m_internal
->GetState() == STATE_NEW
)
751 // WinThreadStart() will see it and terminate immediately
752 m_internal
->SetState(STATE_EXITED
);
758 // is the thread paused?
759 if ( shouldResume
|| IsPaused() )
762 HANDLE hThread
= m_internal
->GetHandle();
764 // does is still run?
769 // set flag for wxIsWaitingForThread()
770 gs_waitingForThread
= TRUE
;
777 // ask the thread to terminate
779 wxCriticalSectionLocker
lock(m_critsect
);
781 m_internal
->Cancel();
785 // we can't just wait for the thread to terminate because it might be
786 // calling some GUI functions and so it will never terminate before we
787 // process the Windows messages that result from these functions
791 result
= ::MsgWaitForMultipleObjects
793 1, // number of objects to wait for
794 &hThread
, // the objects
795 FALSE
, // don't wait for all objects
796 INFINITE
, // no timeout
797 QS_ALLEVENTS
// return as soon as there are any events
804 wxLogSysError(_("Can not wait for thread termination"));
806 return wxTHREAD_KILLED
;
809 // thread we're waiting for terminated
812 case WAIT_OBJECT_0
+ 1:
813 // new message arrived, process it
814 if ( !wxTheApp
->DoMessage() )
816 // WM_QUIT received: kill the thread
819 return wxTHREAD_KILLED
;
824 // give the thread we're waiting for chance to exit
825 // from the GUI call it might have been in
826 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
835 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
837 } while ( result
!= WAIT_OBJECT_0
);
839 // simply wait for the thread to terminate
841 // OTOH, even console apps create windows (in wxExecute, for WinSock
842 // &c), so may be use MsgWaitForMultipleObject() too here?
843 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
845 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
847 #endif // wxUSE_GUI/!wxUSE_GUI
851 gs_waitingForThread
= FALSE
;
859 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
861 wxLogLastError("GetExitCodeThread");
868 // if the thread exits normally, this is done in WinThreadStart, but in
869 // this case it would have been too early because
870 // MsgWaitForMultipleObject() would fail if the therad handle was
871 // closed while we were waiting on it, so we must do it here
875 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
876 wxT("thread must be already terminated.") );
881 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
884 wxThreadError
wxThread::Kill()
887 return wxTHREAD_NOT_RUNNING
;
889 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
891 wxLogSysError(_("Couldn't terminate thread"));
893 return wxTHREAD_MISC_ERROR
;
903 return wxTHREAD_NO_ERROR
;
906 void wxThread::Exit(ExitCode status
)
915 #if defined(__VISUALC__) || (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500))
916 _endthreadex((unsigned)status
);
918 ::ExitThread((DWORD
)status
);
921 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
927 void wxThread::SetPriority(unsigned int prio
)
929 wxCriticalSectionLocker
lock(m_critsect
);
931 m_internal
->SetPriority(prio
);
934 unsigned int wxThread::GetPriority() const
936 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
938 return m_internal
->GetPriority();
941 unsigned long wxThread::GetId() const
943 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
945 return (unsigned long)m_internal
->GetId();
948 bool wxThread::IsRunning() const
950 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
952 return m_internal
->GetState() == STATE_RUNNING
;
955 bool wxThread::IsAlive() const
957 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
959 return (m_internal
->GetState() == STATE_RUNNING
) ||
960 (m_internal
->GetState() == STATE_PAUSED
);
963 bool wxThread::IsPaused() const
965 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
967 return m_internal
->GetState() == STATE_PAUSED
;
970 bool wxThread::TestDestroy()
972 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
974 return m_internal
->GetState() == STATE_CANCELED
;
977 // ----------------------------------------------------------------------------
978 // Automatic initialization for thread module
979 // ----------------------------------------------------------------------------
981 class wxThreadModule
: public wxModule
984 virtual bool OnInit();
985 virtual void OnExit();
988 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
991 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
993 bool wxThreadModule::OnInit()
995 // allocate TLS index for storing the pointer to the current thread
996 gs_tlsThisThread
= ::TlsAlloc();
997 if ( gs_tlsThisThread
== 0xFFFFFFFF )
999 // in normal circumstances it will only happen if all other
1000 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1001 // words, this should never happen
1002 wxLogSysError(_("Thread module initialization failed: "
1003 "impossible to allocate index in thread "
1009 // main thread doesn't have associated wxThread object, so store 0 in the
1011 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1013 ::TlsFree(gs_tlsThisThread
);
1014 gs_tlsThisThread
= 0xFFFFFFFF;
1016 wxLogSysError(_("Thread module initialization failed: "
1017 "can not store value in thread local storage"));
1022 gs_critsectWaitingForGui
= new wxCriticalSection();
1024 gs_critsectGui
= new wxCriticalSection();
1025 gs_critsectGui
->Enter();
1027 // no error return for GetCurrentThreadId()
1028 gs_idMainThread
= ::GetCurrentThreadId();
1033 void wxThreadModule::OnExit()
1035 if ( !::TlsFree(gs_tlsThisThread
) )
1037 wxLogLastError("TlsFree failed.");
1040 if ( gs_critsectGui
)
1042 gs_critsectGui
->Leave();
1043 delete gs_critsectGui
;
1044 gs_critsectGui
= NULL
;
1047 delete gs_critsectWaitingForGui
;
1048 gs_critsectWaitingForGui
= NULL
;
1051 // ----------------------------------------------------------------------------
1052 // under Windows, these functions are implemented using a critical section and
1053 // not a mutex, so the names are a bit confusing
1054 // ----------------------------------------------------------------------------
1056 void WXDLLEXPORT
wxMutexGuiEnter()
1058 // this would dead lock everything...
1059 wxASSERT_MSG( !wxThread::IsMain(),
1060 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1062 // the order in which we enter the critical sections here is crucial!!
1064 // set the flag telling to the main thread that we want to do some GUI
1066 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1068 gs_nWaitingForGui
++;
1071 wxWakeUpMainThread();
1073 // now we may block here because the main thread will soon let us in
1074 // (during the next iteration of OnIdle())
1075 gs_critsectGui
->Enter();
1078 void WXDLLEXPORT
wxMutexGuiLeave()
1080 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1082 if ( wxThread::IsMain() )
1084 gs_bGuiOwnedByMainThread
= FALSE
;
1088 // decrement the number of waiters now
1089 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1090 wxT("calling wxMutexGuiLeave() without entering it first?") );
1092 gs_nWaitingForGui
--;
1094 wxWakeUpMainThread();
1097 gs_critsectGui
->Leave();
1100 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1102 wxASSERT_MSG( wxThread::IsMain(),
1103 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1105 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1107 if ( gs_nWaitingForGui
== 0 )
1109 // no threads are waiting for GUI - so we may acquire the lock without
1110 // any danger (but only if we don't already have it)
1111 if ( !wxGuiOwnedByMainThread() )
1113 gs_critsectGui
->Enter();
1115 gs_bGuiOwnedByMainThread
= TRUE
;
1117 //else: already have it, nothing to do
1121 // some threads are waiting, release the GUI lock if we have it
1122 if ( wxGuiOwnedByMainThread() )
1126 //else: some other worker thread is doing GUI
1130 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1132 return gs_bGuiOwnedByMainThread
;
1135 // wake up the main thread if it's in ::GetMessage()
1136 void WXDLLEXPORT
wxWakeUpMainThread()
1138 // sending any message would do - hopefully WM_NULL is harmless enough
1139 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1141 // should never happen
1142 wxLogLastError("PostThreadMessage(WM_NULL)");
1146 bool WXDLLEXPORT
wxIsWaitingForThread()
1148 return gs_waitingForThread
;
1151 #endif // wxUSE_THREADS