1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread Implementation
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: Vadim Zeitlin to make it work :-)
8 // Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
9 // Vadim Zeitlin (1999)
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
14 #pragma implementation "thread.h"
17 // ----------------------------------------------------------------------------
19 // ----------------------------------------------------------------------------
21 // For compilers that support precompilation, includes "wx.h".
22 #include "wx/wxprec.h"
24 #if defined(__BORLANDC__)
34 #include "wx/msw/private.h"
36 #include "wx/module.h"
37 #include "wx/thread.h"
43 // must have this symbol defined to get _beginthread/_endthread declarations
48 #if defined(__VISUALC__) || \
49 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
50 (defined(__GNUG__) && defined(__MSVCRT__))
52 #if defined(__BORLANDC__) && !defined(__MT__)
53 // I can't set -tWM in the IDE (anyone?) so have to do this
57 #if defined(__BORLANDC__) && !defined(__MFC_COMPAT__)
58 // Needed to know about _beginthreadex etc..
59 #define __MFC_COMPAT__
65 // ----------------------------------------------------------------------------
67 // ----------------------------------------------------------------------------
69 // the possible states of the thread ("=>" shows all possible transitions from
73 STATE_NEW
, // didn't start execution yet (=> RUNNING)
74 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
75 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
76 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
77 STATE_EXITED
// thread is terminating
80 // ----------------------------------------------------------------------------
81 // this module globals
82 // ----------------------------------------------------------------------------
84 // TLS index of the slot where we store the pointer to the current thread
85 static DWORD gs_tlsThisThread
= 0xFFFFFFFF;
87 // id of the main thread - the one which can call GUI functions without first
88 // calling wxMutexGuiEnter()
89 static DWORD gs_idMainThread
= 0;
91 // if it's FALSE, some secondary thread is holding the GUI lock
92 static bool gs_bGuiOwnedByMainThread
= TRUE
;
94 // critical section which controls access to all GUI functions: any secondary
95 // thread (i.e. except the main one) must enter this crit section before doing
97 static wxCriticalSection
*gs_critsectGui
= NULL
;
99 // critical section which protects gs_nWaitingForGui variable
100 static wxCriticalSection
*gs_critsectWaitingForGui
= NULL
;
102 // number of threads waiting for GUI in wxMutexGuiEnter()
103 static size_t gs_nWaitingForGui
= 0;
105 // are we waiting for a thread termination?
106 static bool gs_waitingForThread
= FALSE
;
108 // ============================================================================
109 // Windows implementation of thread classes
110 // ============================================================================
112 // ----------------------------------------------------------------------------
113 // wxMutex implementation
114 // ----------------------------------------------------------------------------
116 class wxMutexInternal
121 m_mutex
= ::CreateMutex(NULL
, FALSE
, NULL
);
124 wxLogSysError(_("Can not create mutex"));
128 ~wxMutexInternal() { if ( m_mutex
) CloseHandle(m_mutex
); }
136 m_internal
= new wxMutexInternal
;
145 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
151 wxMutexError
wxMutex::Lock()
155 ret
= WaitForSingleObject(m_internal
->m_mutex
, INFINITE
);
166 wxLogSysError(_("Couldn't acquire a mutex lock"));
167 return wxMUTEX_MISC_ERROR
;
171 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
175 return wxMUTEX_NO_ERROR
;
178 wxMutexError
wxMutex::TryLock()
182 ret
= WaitForSingleObject(m_internal
->m_mutex
, 0);
183 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
187 return wxMUTEX_NO_ERROR
;
190 wxMutexError
wxMutex::Unlock()
195 BOOL ret
= ReleaseMutex(m_internal
->m_mutex
);
198 wxLogSysError(_("Couldn't release a mutex"));
199 return wxMUTEX_MISC_ERROR
;
202 return wxMUTEX_NO_ERROR
;
205 // ----------------------------------------------------------------------------
206 // wxCondition implementation
207 // ----------------------------------------------------------------------------
209 class wxConditionInternal
212 wxConditionInternal()
214 m_hEvent
= ::CreateEvent(
215 NULL
, // default secutiry
216 FALSE
, // not manual reset
217 FALSE
, // nonsignaled initially
218 NULL
// nameless event
222 wxLogSysError(_("Can not create event object."));
225 // nobody waits for us yet
229 bool Wait(DWORD timeout
)
231 // as m_nWaiters variable is accessed from multiple waiting threads
232 // (and possibly from the broadcasting thread), we need to change its
234 ::InterlockedIncrement(&m_nWaiters
);
236 // FIXME this should be MsgWaitForMultipleObjects() as we want to keep
237 // processing Windows messages while waiting (or don't we?)
238 DWORD rc
= ::WaitForSingleObject(m_hEvent
, timeout
);
240 ::InterlockedDecrement(&m_nWaiters
);
242 return rc
!= WAIT_TIMEOUT
;
247 // set the event to signaled: if a thread is already waiting on it, it
248 // will be woken up, otherwise the event will remain in the signaled
249 // state until someone waits on it. In any case, the system will return
250 // it to a non signalled state afterwards. If multiple threads are
251 // waiting, only one will be woken up.
252 if ( !::SetEvent(m_hEvent
) )
254 wxLogLastError(wxT("SetEvent"));
260 // this works because all these threads are already waiting and so each
261 // SetEvent() inside Signal() is really a PulseEvent() because the
262 // event state is immediately returned to non-signaled
263 for ( LONG n
= 0; n
< m_nWaiters
; n
++ )
269 ~wxConditionInternal()
273 if ( !::CloseHandle(m_hEvent
) )
275 wxLogLastError(wxT("CloseHandle(event)"));
281 // the Win32 synchronization object corresponding to this event
284 // number of threads waiting for this condition
288 wxCondition::wxCondition()
290 m_internal
= new wxConditionInternal
;
293 wxCondition::~wxCondition()
298 void wxCondition::Wait()
300 (void)m_internal
->Wait(INFINITE
);
303 bool wxCondition::Wait(unsigned long sec
,
306 return m_internal
->Wait(sec
*1000 + nsec
/1000000);
309 void wxCondition::Signal()
311 m_internal
->Signal();
314 void wxCondition::Broadcast()
316 m_internal
->Broadcast();
319 // ----------------------------------------------------------------------------
320 // wxCriticalSection implementation
321 // ----------------------------------------------------------------------------
323 wxCriticalSection::wxCriticalSection()
325 wxASSERT_MSG( sizeof(CRITICAL_SECTION
) <= sizeof(m_buffer
),
326 _T("must increase buffer size in wx/thread.h") );
328 ::InitializeCriticalSection((CRITICAL_SECTION
*)m_buffer
);
331 wxCriticalSection::~wxCriticalSection()
333 ::DeleteCriticalSection((CRITICAL_SECTION
*)m_buffer
);
336 void wxCriticalSection::Enter()
338 ::EnterCriticalSection((CRITICAL_SECTION
*)m_buffer
);
341 void wxCriticalSection::Leave()
343 ::LeaveCriticalSection((CRITICAL_SECTION
*)m_buffer
);
346 // ----------------------------------------------------------------------------
347 // wxThread implementation
348 // ----------------------------------------------------------------------------
350 // wxThreadInternal class
351 // ----------------------
353 class wxThreadInternal
360 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
372 if ( !::CloseHandle(m_hThread
) )
374 wxLogLastError(wxT("CloseHandle(thread)"));
381 // create a new (suspended) thread (for the given thread object)
382 bool Create(wxThread
*thread
);
384 // suspend/resume/terminate
387 void Cancel() { m_state
= STATE_CANCELED
; }
390 void SetState(wxThreadState state
) { m_state
= state
; }
391 wxThreadState
GetState() const { return m_state
; }
394 void SetPriority(unsigned int priority
);
395 unsigned int GetPriority() const { return m_priority
; }
397 // thread handle and id
398 HANDLE
GetHandle() const { return m_hThread
; }
399 DWORD
GetId() const { return m_tid
; }
402 static DWORD
WinThreadStart(wxThread
*thread
);
405 HANDLE m_hThread
; // handle of the thread
406 wxThreadState m_state
; // state, see wxThreadState enum
407 unsigned int m_priority
; // thread priority in "wx" units
408 DWORD m_tid
; // thread id
411 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
416 // first of all, check whether we hadn't been cancelled already and don't
417 // start the user code at all then
418 if ( thread
->m_internal
->GetState() == STATE_EXITED
)
423 else // do run thread
425 // store the thread object in the TLS
426 if ( !::TlsSetValue(gs_tlsThisThread
, thread
) )
428 wxLogSysError(_("Can not start thread: error writing TLS."));
433 rc
= (DWORD
)thread
->Entry();
435 // enter m_critsect before changing the thread state
436 thread
->m_critsect
.Enter();
437 wasCancelled
= thread
->m_internal
->GetState() == STATE_CANCELED
;
438 thread
->m_internal
->SetState(STATE_EXITED
);
439 thread
->m_critsect
.Leave();
444 // if the thread was cancelled (from Delete()), then its handle is still
446 if ( thread
->IsDetached() && !wasCancelled
)
451 //else: the joinable threads handle will be closed when Wait() is done
456 void wxThreadInternal::SetPriority(unsigned int priority
)
458 m_priority
= priority
;
460 // translate wxWindows priority to the Windows one
462 if (m_priority
<= 20)
463 win_priority
= THREAD_PRIORITY_LOWEST
;
464 else if (m_priority
<= 40)
465 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
466 else if (m_priority
<= 60)
467 win_priority
= THREAD_PRIORITY_NORMAL
;
468 else if (m_priority
<= 80)
469 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
470 else if (m_priority
<= 100)
471 win_priority
= THREAD_PRIORITY_HIGHEST
;
474 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
475 win_priority
= THREAD_PRIORITY_NORMAL
;
478 if ( !::SetThreadPriority(m_hThread
, win_priority
) )
480 wxLogSysError(_("Can't set thread priority"));
484 bool wxThreadInternal::Create(wxThread
*thread
)
486 // for compilers which have it, we should use C RTL function for thread
487 // creation instead of Win32 API one because otherwise we will have memory
488 // leaks if the thread uses C RTL (and most threads do)
489 #if defined(__VISUALC__) || \
490 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
491 (defined(__GNUG__) && defined(__MSVCRT__))
492 typedef unsigned (__stdcall
*RtlThreadStart
)(void *);
494 m_hThread
= (HANDLE
)_beginthreadex(NULL
, 0,
496 wxThreadInternal::WinThreadStart
,
497 thread
, CREATE_SUSPENDED
,
498 (unsigned int *)&m_tid
);
499 #else // compiler doesn't have _beginthreadex
500 m_hThread
= ::CreateThread
502 NULL
, // default security
503 0, // default stack size
504 (LPTHREAD_START_ROUTINE
) // thread entry point
505 wxThreadInternal::WinThreadStart
, //
506 (LPVOID
)thread
, // parameter
507 CREATE_SUSPENDED
, // flags
508 &m_tid
// [out] thread id
510 #endif // _beginthreadex/CreateThread
512 if ( m_hThread
== NULL
)
514 wxLogSysError(_("Can't create thread"));
519 if ( m_priority
!= WXTHREAD_DEFAULT_PRIORITY
)
521 SetPriority(m_priority
);
527 bool wxThreadInternal::Suspend()
529 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
530 if ( nSuspendCount
== (DWORD
)-1 )
532 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
537 m_state
= STATE_PAUSED
;
542 bool wxThreadInternal::Resume()
544 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
545 if ( nSuspendCount
== (DWORD
)-1 )
547 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
552 // don't change the state from STATE_EXITED because it's special and means
553 // we are going to terminate without running any user code - if we did it,
554 // the codei n Delete() wouldn't work
555 if ( m_state
!= STATE_EXITED
)
557 m_state
= STATE_RUNNING
;
566 wxThread
*wxThread::This()
568 wxThread
*thread
= (wxThread
*)::TlsGetValue(gs_tlsThisThread
);
570 // be careful, 0 may be a valid return value as well
571 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
573 wxLogSysError(_("Couldn't get the current thread pointer"));
581 bool wxThread::IsMain()
583 return ::GetCurrentThreadId() == gs_idMainThread
;
590 void wxThread::Yield()
592 // 0 argument to Sleep() is special and means to just give away the rest of
597 void wxThread::Sleep(unsigned long milliseconds
)
599 ::Sleep(milliseconds
);
602 int wxThread::GetCPUCount()
607 return si
.dwNumberOfProcessors
;
610 bool wxThread::SetConcurrency(size_t level
)
612 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
614 // ok only for the default one
618 // get system affinity mask first
619 HANDLE hProcess
= ::GetCurrentProcess();
620 DWORD dwProcMask
, dwSysMask
;
621 if ( ::GetProcessAffinityMask(hProcess
, &dwProcMask
, &dwSysMask
) == 0 )
623 wxLogLastError(_T("GetProcessAffinityMask"));
628 // how many CPUs have we got?
629 if ( dwSysMask
== 1 )
631 // don't bother with all this complicated stuff - on a single
632 // processor system it doesn't make much sense anyhow
636 // calculate the process mask: it's a bit vector with one bit per
637 // processor; we want to schedule the process to run on first level
642 if ( dwSysMask
& bit
)
644 // ok, we can set this bit
647 // another process added
659 // could we set all bits?
662 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level
);
667 // set it: we can't link to SetProcessAffinityMask() because it doesn't
668 // exist in Win9x, use RT binding instead
670 typedef BOOL (*SETPROCESSAFFINITYMASK
)(HANDLE
, DWORD
);
672 // can use static var because we're always in the main thread here
673 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask
= NULL
;
675 if ( !pfnSetProcessAffinityMask
)
677 HMODULE hModKernel
= ::LoadLibrary(_T("kernel32"));
680 pfnSetProcessAffinityMask
= (SETPROCESSAFFINITYMASK
)
681 ::GetProcAddress(hModKernel
, "SetProcessAffinityMask");
684 // we've discovered a MT version of Win9x!
685 wxASSERT_MSG( pfnSetProcessAffinityMask
,
686 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
689 if ( !pfnSetProcessAffinityMask
)
691 // msg given above - do it only once
695 if ( pfnSetProcessAffinityMask(hProcess
, dwProcMask
) == 0 )
697 wxLogLastError(_T("SetProcessAffinityMask"));
708 wxThread::wxThread(wxThreadKind kind
)
710 m_internal
= new wxThreadInternal();
712 m_isDetached
= kind
== wxTHREAD_DETACHED
;
715 wxThread::~wxThread()
720 // create/start thread
721 // -------------------
723 wxThreadError
wxThread::Create()
725 wxCriticalSectionLocker
lock(m_critsect
);
727 if ( !m_internal
->Create(this) )
728 return wxTHREAD_NO_RESOURCE
;
730 return wxTHREAD_NO_ERROR
;
733 wxThreadError
wxThread::Run()
735 wxCriticalSectionLocker
lock(m_critsect
);
737 if ( m_internal
->GetState() != STATE_NEW
)
739 // actually, it may be almost any state at all, not only STATE_RUNNING
740 return wxTHREAD_RUNNING
;
743 // the thread has just been created and is still suspended - let it run
747 // suspend/resume thread
748 // ---------------------
750 wxThreadError
wxThread::Pause()
752 wxCriticalSectionLocker
lock(m_critsect
);
754 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
757 wxThreadError
wxThread::Resume()
759 wxCriticalSectionLocker
lock(m_critsect
);
761 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
767 wxThread::ExitCode
wxThread::Wait()
769 // although under Windows we can wait for any thread, it's an error to
770 // wait for a detached one in wxWin API
771 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
772 _T("can't wait for detached thread") );
774 ExitCode rc
= (ExitCode
)-1;
783 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
787 // Delete() is always safe to call, so consider all possible states
789 // we might need to resume the thread, but we might also not need to cancel
790 // it if it doesn't run yet
791 bool shouldResume
= FALSE
,
795 // check if the thread already started to run
797 wxCriticalSectionLocker
lock(m_critsect
);
799 if ( m_internal
->GetState() == STATE_NEW
)
801 // WinThreadStart() will see it and terminate immediately, no need
802 // to cancel the thread - but we still need to resume it to let it
804 m_internal
->SetState(STATE_EXITED
);
806 Resume(); // it knows about STATE_EXITED special case
808 shouldCancel
= FALSE
;
811 // shouldResume is correctly set to FALSE here
815 shouldResume
= IsPaused();
819 // resume the thread if it is paused
823 HANDLE hThread
= m_internal
->GetHandle();
825 // does is still run?
826 if ( isRunning
|| IsRunning() )
830 // set flag for wxIsWaitingForThread()
831 gs_waitingForThread
= TRUE
;
838 // ask the thread to terminate
841 wxCriticalSectionLocker
lock(m_critsect
);
843 m_internal
->Cancel();
847 // we can't just wait for the thread to terminate because it might be
848 // calling some GUI functions and so it will never terminate before we
849 // process the Windows messages that result from these functions
853 result
= ::MsgWaitForMultipleObjects
855 1, // number of objects to wait for
856 &hThread
, // the objects
857 FALSE
, // don't wait for all objects
858 INFINITE
, // no timeout
859 QS_ALLEVENTS
// return as soon as there are any events
866 wxLogSysError(_("Can not wait for thread termination"));
868 return wxTHREAD_KILLED
;
871 // thread we're waiting for terminated
874 case WAIT_OBJECT_0
+ 1:
875 // new message arrived, process it
876 if ( !wxTheApp
->DoMessage() )
878 // WM_QUIT received: kill the thread
881 return wxTHREAD_KILLED
;
886 // give the thread we're waiting for chance to exit
887 // from the GUI call it might have been in
888 if ( (gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
897 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
899 } while ( result
!= WAIT_OBJECT_0
);
901 // simply wait for the thread to terminate
903 // OTOH, even console apps create windows (in wxExecute, for WinSock
904 // &c), so may be use MsgWaitForMultipleObject() too here?
905 if ( WaitForSingleObject(hThread
, INFINITE
) != WAIT_OBJECT_0
)
907 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
909 #endif // wxUSE_GUI/!wxUSE_GUI
913 gs_waitingForThread
= FALSE
;
921 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
923 wxLogLastError(wxT("GetExitCodeThread"));
930 // if the thread exits normally, this is done in WinThreadStart, but in
931 // this case it would have been too early because
932 // MsgWaitForMultipleObject() would fail if the thread handle was
933 // closed while we were waiting on it, so we must do it here
937 wxASSERT_MSG( (DWORD
)rc
!= STILL_ACTIVE
,
938 wxT("thread must be already terminated.") );
943 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
946 wxThreadError
wxThread::Kill()
949 return wxTHREAD_NOT_RUNNING
;
951 if ( !::TerminateThread(m_internal
->GetHandle(), (DWORD
)-1) )
953 wxLogSysError(_("Couldn't terminate thread"));
955 return wxTHREAD_MISC_ERROR
;
965 return wxTHREAD_NO_ERROR
;
968 void wxThread::Exit(ExitCode status
)
977 #if defined(__VISUALC__) || \
978 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
979 (defined(__GNUG__) && defined(__MSVCRT__))
980 _endthreadex((unsigned)status
);
982 ::ExitThread((DWORD
)status
);
985 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
991 void wxThread::SetPriority(unsigned int prio
)
993 wxCriticalSectionLocker
lock(m_critsect
);
995 m_internal
->SetPriority(prio
);
998 unsigned int wxThread::GetPriority() const
1000 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1002 return m_internal
->GetPriority();
1005 unsigned long wxThread::GetId() const
1007 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1009 return (unsigned long)m_internal
->GetId();
1012 bool wxThread::IsRunning() const
1014 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1016 return m_internal
->GetState() == STATE_RUNNING
;
1019 bool wxThread::IsAlive() const
1021 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1023 return (m_internal
->GetState() == STATE_RUNNING
) ||
1024 (m_internal
->GetState() == STATE_PAUSED
);
1027 bool wxThread::IsPaused() const
1029 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1031 return m_internal
->GetState() == STATE_PAUSED
;
1034 bool wxThread::TestDestroy()
1036 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
1038 return m_internal
->GetState() == STATE_CANCELED
;
1041 // ----------------------------------------------------------------------------
1042 // Automatic initialization for thread module
1043 // ----------------------------------------------------------------------------
1045 class wxThreadModule
: public wxModule
1048 virtual bool OnInit();
1049 virtual void OnExit();
1052 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
1055 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
1057 bool wxThreadModule::OnInit()
1059 // allocate TLS index for storing the pointer to the current thread
1060 gs_tlsThisThread
= ::TlsAlloc();
1061 if ( gs_tlsThisThread
== 0xFFFFFFFF )
1063 // in normal circumstances it will only happen if all other
1064 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1065 // words, this should never happen
1066 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1071 // main thread doesn't have associated wxThread object, so store 0 in the
1073 if ( !::TlsSetValue(gs_tlsThisThread
, (LPVOID
)0) )
1075 ::TlsFree(gs_tlsThisThread
);
1076 gs_tlsThisThread
= 0xFFFFFFFF;
1078 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1083 gs_critsectWaitingForGui
= new wxCriticalSection();
1085 gs_critsectGui
= new wxCriticalSection();
1086 gs_critsectGui
->Enter();
1088 // no error return for GetCurrentThreadId()
1089 gs_idMainThread
= ::GetCurrentThreadId();
1094 void wxThreadModule::OnExit()
1096 if ( !::TlsFree(gs_tlsThisThread
) )
1098 wxLogLastError(wxT("TlsFree failed."));
1101 if ( gs_critsectGui
)
1103 gs_critsectGui
->Leave();
1104 delete gs_critsectGui
;
1105 gs_critsectGui
= NULL
;
1108 delete gs_critsectWaitingForGui
;
1109 gs_critsectWaitingForGui
= NULL
;
1112 // ----------------------------------------------------------------------------
1113 // under Windows, these functions are implemented using a critical section and
1114 // not a mutex, so the names are a bit confusing
1115 // ----------------------------------------------------------------------------
1117 void WXDLLEXPORT
wxMutexGuiEnter()
1119 // this would dead lock everything...
1120 wxASSERT_MSG( !wxThread::IsMain(),
1121 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1123 // the order in which we enter the critical sections here is crucial!!
1125 // set the flag telling to the main thread that we want to do some GUI
1127 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1129 gs_nWaitingForGui
++;
1132 wxWakeUpMainThread();
1134 // now we may block here because the main thread will soon let us in
1135 // (during the next iteration of OnIdle())
1136 gs_critsectGui
->Enter();
1139 void WXDLLEXPORT
wxMutexGuiLeave()
1141 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1143 if ( wxThread::IsMain() )
1145 gs_bGuiOwnedByMainThread
= FALSE
;
1149 // decrement the number of threads waiting for GUI access now
1150 wxASSERT_MSG( gs_nWaitingForGui
> 0,
1151 wxT("calling wxMutexGuiLeave() without entering it first?") );
1153 gs_nWaitingForGui
--;
1155 wxWakeUpMainThread();
1158 gs_critsectGui
->Leave();
1161 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
1163 wxASSERT_MSG( wxThread::IsMain(),
1164 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1166 wxCriticalSectionLocker
enter(*gs_critsectWaitingForGui
);
1168 if ( gs_nWaitingForGui
== 0 )
1170 // no threads are waiting for GUI - so we may acquire the lock without
1171 // any danger (but only if we don't already have it)
1172 if ( !wxGuiOwnedByMainThread() )
1174 gs_critsectGui
->Enter();
1176 gs_bGuiOwnedByMainThread
= TRUE
;
1178 //else: already have it, nothing to do
1182 // some threads are waiting, release the GUI lock if we have it
1183 if ( wxGuiOwnedByMainThread() )
1187 //else: some other worker thread is doing GUI
1191 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
1193 return gs_bGuiOwnedByMainThread
;
1196 // wake up the main thread if it's in ::GetMessage()
1197 void WXDLLEXPORT
wxWakeUpMainThread()
1199 // sending any message would do - hopefully WM_NULL is harmless enough
1200 if ( !::PostThreadMessage(gs_idMainThread
, WM_NULL
, 0, 0) )
1202 // should never happen
1203 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1207 bool WXDLLEXPORT
wxIsWaitingForThread()
1209 return gs_waitingForThread
;
1212 #endif // wxUSE_THREADS