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__)
38 #include "wx/module.h"
39 #include "wx/thread.h"
41 // the possible states of the thread ("=>" shows all possible transitions from
45 STATE_NEW
, // didn't start execution yet (=> RUNNING)
46 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
47 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
48 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
49 STATE_EXITED
// thread is terminating
52 // ----------------------------------------------------------------------------
54 // ----------------------------------------------------------------------------
56 // TLS index of the slot where we store the pointer to the current thread
57 static DWORD s_tlsThisThread
= 0xFFFFFFFF;
59 // id of the main thread - the one which can call GUI functions without first
60 // calling wxMutexGuiEnter()
61 static DWORD s_idMainThread
= 0;
63 // if it's FALSE, some secondary thread is holding the GUI lock
64 static bool s_bGuiOwnedByMainThread
= TRUE
;
66 // critical section which controls access to all GUI functions: any secondary
67 // thread (i.e. except the main one) must enter this crit section before doing
69 static wxCriticalSection
*s_critsectGui
= NULL
;
71 // critical section which protects s_nWaitingForGui variable
72 static wxCriticalSection
*s_critsectWaitingForGui
= NULL
;
74 // number of threads waiting for GUI in wxMutexGuiEnter()
75 static size_t s_nWaitingForGui
= 0;
77 // are we waiting for a thread termination?
78 static bool s_waitingForThread
= FALSE
;
80 // ============================================================================
81 // Windows implementation of thread classes
82 // ============================================================================
84 // ----------------------------------------------------------------------------
85 // wxMutex implementation
86 // ----------------------------------------------------------------------------
95 p_internal
= new wxMutexInternal
;
96 p_internal
->p_mutex
= CreateMutex(NULL
, FALSE
, NULL
);
97 if ( !p_internal
->p_mutex
)
99 wxLogSysError(_("Can not create mutex."));
108 wxLogDebug(_T("Warning: freeing a locked mutex (%d locks)."), m_locked
);
109 CloseHandle(p_internal
->p_mutex
);
112 wxMutexError
wxMutex::Lock()
116 ret
= WaitForSingleObject(p_internal
->p_mutex
, INFINITE
);
127 wxLogSysError(_("Couldn't acquire a mutex lock"));
128 return wxMUTEX_MISC_ERROR
;
132 wxFAIL_MSG(_T("impossible return value in wxMutex::Lock"));
136 return wxMUTEX_NO_ERROR
;
139 wxMutexError
wxMutex::TryLock()
143 ret
= WaitForSingleObject(p_internal
->p_mutex
, 0);
144 if (ret
== WAIT_TIMEOUT
|| ret
== WAIT_ABANDONED
)
148 return wxMUTEX_NO_ERROR
;
151 wxMutexError
wxMutex::Unlock()
156 BOOL ret
= ReleaseMutex(p_internal
->p_mutex
);
159 wxLogSysError(_("Couldn't release a mutex"));
160 return wxMUTEX_MISC_ERROR
;
163 return wxMUTEX_NO_ERROR
;
166 // ----------------------------------------------------------------------------
167 // wxCondition implementation
168 // ----------------------------------------------------------------------------
170 class wxConditionInternal
177 wxCondition::wxCondition()
179 p_internal
= new wxConditionInternal
;
180 p_internal
->event
= CreateEvent(NULL
, FALSE
, FALSE
, NULL
);
181 if ( !p_internal
->event
)
183 wxLogSysError(_("Can not create event object."));
186 p_internal
->waiters
= 0;
189 wxCondition::~wxCondition()
191 CloseHandle(p_internal
->event
);
194 void wxCondition::Wait(wxMutex
& mutex
)
197 p_internal
->waiters
++;
198 WaitForSingleObject(p_internal
->event
, INFINITE
);
199 p_internal
->waiters
--;
203 bool wxCondition::Wait(wxMutex
& mutex
,
210 p_internal
->waiters
++;
211 ret
= WaitForSingleObject(p_internal
->event
, (sec
*1000)+(nsec
/1000000));
212 p_internal
->waiters
--;
215 return (ret
!= WAIT_TIMEOUT
);
218 void wxCondition::Signal()
220 SetEvent(p_internal
->event
);
223 void wxCondition::Broadcast()
227 for (i
=0;i
<p_internal
->waiters
;i
++)
229 if ( SetEvent(p_internal
->event
) == 0 )
231 wxLogSysError(_("Couldn't change the state of event object."));
236 // ----------------------------------------------------------------------------
237 // wxCriticalSection implementation
238 // ----------------------------------------------------------------------------
240 class wxCriticalSectionInternal
243 // init the critical section object
244 wxCriticalSectionInternal()
245 { ::InitializeCriticalSection(&m_data
); }
247 // implicit cast to the associated data
248 operator CRITICAL_SECTION
*() { return &m_data
; }
250 // free the associated ressources
251 ~wxCriticalSectionInternal()
252 { ::DeleteCriticalSection(&m_data
); }
255 CRITICAL_SECTION m_data
;
258 wxCriticalSection::wxCriticalSection()
260 m_critsect
= new wxCriticalSectionInternal
;
263 wxCriticalSection::~wxCriticalSection()
268 void wxCriticalSection::Enter()
270 ::EnterCriticalSection(*m_critsect
);
273 void wxCriticalSection::Leave()
275 ::LeaveCriticalSection(*m_critsect
);
278 // ----------------------------------------------------------------------------
279 // wxThread implementation
280 // ----------------------------------------------------------------------------
282 // wxThreadInternal class
283 // ----------------------
285 class wxThreadInternal
292 m_priority
= WXTHREAD_DEFAULT_PRIORITY
;
295 // create a new (suspended) thread (for the given thread object)
296 bool Create(wxThread
*thread
);
298 // suspend/resume/terminate
301 void Cancel() { m_state
= STATE_CANCELED
; }
304 void SetState(wxThreadState state
) { m_state
= state
; }
305 wxThreadState
GetState() const { return m_state
; }
308 void SetPriority(unsigned int priority
) { m_priority
= priority
; }
309 unsigned int GetPriority() const { return m_priority
; }
311 // thread handle and id
312 HANDLE
GetHandle() const { return m_hThread
; }
313 DWORD
GetId() const { return m_tid
; }
316 static DWORD
WinThreadStart(wxThread
*thread
);
319 HANDLE m_hThread
; // handle of the thread
320 wxThreadState m_state
; // state, see wxThreadState enum
321 unsigned int m_priority
; // thread priority in "wx" units
322 DWORD m_tid
; // thread id
325 DWORD
wxThreadInternal::WinThreadStart(wxThread
*thread
)
327 // store the thread object in the TLS
328 if ( !::TlsSetValue(s_tlsThisThread
, thread
) )
330 wxLogSysError(_("Can not start thread: error writing TLS."));
335 DWORD ret
= (DWORD
)thread
->Entry();
336 thread
->p_internal
->SetState(STATE_EXITED
);
344 bool wxThreadInternal::Create(wxThread
*thread
)
346 m_hThread
= ::CreateThread
348 NULL
, // default security
349 0, // default stack size
350 (LPTHREAD_START_ROUTINE
) // thread entry point
351 wxThreadInternal::WinThreadStart
, //
352 (LPVOID
)thread
, // parameter
353 CREATE_SUSPENDED
, // flags
354 &m_tid
// [out] thread id
357 if ( m_hThread
== NULL
)
359 wxLogSysError(_("Can't create thread"));
364 // translate wxWindows priority to the Windows one
366 if (m_priority
<= 20)
367 win_priority
= THREAD_PRIORITY_LOWEST
;
368 else if (m_priority
<= 40)
369 win_priority
= THREAD_PRIORITY_BELOW_NORMAL
;
370 else if (m_priority
<= 60)
371 win_priority
= THREAD_PRIORITY_NORMAL
;
372 else if (m_priority
<= 80)
373 win_priority
= THREAD_PRIORITY_ABOVE_NORMAL
;
374 else if (m_priority
<= 100)
375 win_priority
= THREAD_PRIORITY_HIGHEST
;
378 wxFAIL_MSG(_T("invalid value of thread priority parameter"));
379 win_priority
= THREAD_PRIORITY_NORMAL
;
382 if ( ::SetThreadPriority(m_hThread
, win_priority
) == 0 )
384 wxLogSysError(_("Can't set thread priority"));
390 bool wxThreadInternal::Suspend()
392 DWORD nSuspendCount
= ::SuspendThread(m_hThread
);
393 if ( nSuspendCount
== (DWORD
)-1 )
395 wxLogSysError(_("Can not suspend thread %x"), m_hThread
);
400 m_state
= STATE_PAUSED
;
405 bool wxThreadInternal::Resume()
407 DWORD nSuspendCount
= ::ResumeThread(m_hThread
);
408 if ( nSuspendCount
== (DWORD
)-1 )
410 wxLogSysError(_("Can not resume thread %x"), m_hThread
);
415 m_state
= STATE_RUNNING
;
423 wxThread
*wxThread::This()
425 wxThread
*thread
= (wxThread
*)::TlsGetValue(s_tlsThisThread
);
427 // be careful, 0 may be a valid return value as well
428 if ( !thread
&& (::GetLastError() != NO_ERROR
) )
430 wxLogSysError(_("Couldn't get the current thread pointer"));
438 bool wxThread::IsMain()
440 return ::GetCurrentThreadId() == s_idMainThread
;
447 void wxThread::Yield()
449 // 0 argument to Sleep() is special
453 void wxThread::Sleep(unsigned long milliseconds
)
455 ::Sleep(milliseconds
);
458 // create/start thread
459 // -------------------
461 wxThreadError
wxThread::Create()
463 if ( !p_internal
->Create(this) )
464 return wxTHREAD_NO_RESOURCE
;
466 return wxTHREAD_NO_ERROR
;
469 wxThreadError
wxThread::Run()
471 wxCriticalSectionLocker
lock(m_critsect
);
473 if ( p_internal
->GetState() != STATE_NEW
)
475 // actually, it may be almost any state at all, not only STATE_RUNNING
476 return wxTHREAD_RUNNING
;
482 // suspend/resume thread
483 // ---------------------
485 wxThreadError
wxThread::Pause()
487 wxCriticalSectionLocker
lock(m_critsect
);
489 return p_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
492 wxThreadError
wxThread::Resume()
494 wxCriticalSectionLocker
lock(m_critsect
);
496 return p_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
502 wxThread::ExitCode
wxThread::Delete()
506 // Delete() is always safe to call, so consider all possible states
514 // set flag for wxIsWaitingForThread()
515 s_waitingForThread
= TRUE
;
522 wxCriticalSectionLocker
lock(m_critsect
);
524 p_internal
->Cancel();
525 hThread
= p_internal
->GetHandle();
528 // we can't just wait for the thread to terminate because it might be
529 // calling some GUI functions and so it will never terminate before we
530 // process the Windows messages that result from these functions
534 result
= ::MsgWaitForMultipleObjects
536 1, // number of objects to wait for
537 &hThread
, // the objects
538 FALSE
, // don't wait for all objects
539 INFINITE
, // no timeout
540 QS_ALLEVENTS
// return as soon as there are any events
547 wxLogSysError(_("Can not wait for thread termination"));
552 // thread we're waiting for terminated
555 case WAIT_OBJECT_0
+ 1:
556 // new message arrived, process it
557 if ( !wxTheApp
->DoMessage() )
559 // WM_QUIT received: kill the thread
567 // give the thread we're waiting for chance to exit
568 // from the GUI call it might have been in
569 if ( (s_nWaitingForGui
> 0) && wxGuiOwnedByMainThread() )
578 wxFAIL_MSG(_T("unexpected result of MsgWaitForMultipleObject"));
580 } while ( result
!= WAIT_OBJECT_0
);
584 s_waitingForThread
= FALSE
;
589 if ( !::GetExitCodeThread(hThread
, (LPDWORD
)&rc
) )
591 wxLogLastError("GetExitCodeThread");
596 wxASSERT_MSG( (LPVOID
)rc
!= (LPVOID
)STILL_ACTIVE
,
597 _T("thread must be already terminated.") );
599 ::CloseHandle(hThread
);
605 wxThreadError
wxThread::Kill()
608 return wxTHREAD_NOT_RUNNING
;
610 if ( !::TerminateThread(p_internal
->GetHandle(), (DWORD
)-1) )
612 wxLogSysError(_("Couldn't terminate thread"));
614 return wxTHREAD_MISC_ERROR
;
619 return wxTHREAD_NO_ERROR
;
622 void wxThread::Exit(void *status
)
626 ::ExitThread((DWORD
)status
);
628 wxFAIL_MSG(_T("Couldn't return from ExitThread()!"));
631 void wxThread::SetPriority(unsigned int prio
)
633 wxCriticalSectionLocker
lock(m_critsect
);
635 p_internal
->SetPriority(prio
);
638 unsigned int wxThread::GetPriority() const
640 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
642 return p_internal
->GetPriority();
645 unsigned long wxThread::GetID() const
647 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
649 return (unsigned long)p_internal
->GetId();
652 bool wxThread::IsRunning() const
654 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
656 return p_internal
->GetState() == STATE_RUNNING
;
659 bool wxThread::IsAlive() const
661 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
663 return (p_internal
->GetState() == STATE_RUNNING
) ||
664 (p_internal
->GetState() == STATE_PAUSED
);
667 bool wxThread::IsPaused() const
669 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
671 return (p_internal
->GetState() == STATE_PAUSED
);
674 bool wxThread::TestDestroy()
676 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
678 return p_internal
->GetState() == STATE_CANCELED
;
683 p_internal
= new wxThreadInternal();
686 wxThread::~wxThread()
691 // ----------------------------------------------------------------------------
692 // Automatic initialization for thread module
693 // ----------------------------------------------------------------------------
695 class wxThreadModule
: public wxModule
698 virtual bool OnInit();
699 virtual void OnExit();
702 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
705 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
707 bool wxThreadModule::OnInit()
709 // allocate TLS index for storing the pointer to the current thread
710 s_tlsThisThread
= ::TlsAlloc();
711 if ( s_tlsThisThread
== 0xFFFFFFFF )
713 // in normal circumstances it will only happen if all other
714 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
715 // words, this should never happen
716 wxLogSysError(_("Thread module initialization failed: "
717 "impossible to allocate index in thread "
723 // main thread doesn't have associated wxThread object, so store 0 in the
725 if ( !::TlsSetValue(s_tlsThisThread
, (LPVOID
)0) )
727 ::TlsFree(s_tlsThisThread
);
728 s_tlsThisThread
= 0xFFFFFFFF;
730 wxLogSysError(_("Thread module initialization failed: "
731 "can not store value in thread local storage"));
736 s_critsectWaitingForGui
= new wxCriticalSection();
738 s_critsectGui
= new wxCriticalSection();
739 s_critsectGui
->Enter();
741 // no error return for GetCurrentThreadId()
742 s_idMainThread
= ::GetCurrentThreadId();
747 void wxThreadModule::OnExit()
749 if ( !::TlsFree(s_tlsThisThread
) )
751 wxLogLastError("TlsFree failed.");
756 s_critsectGui
->Leave();
757 delete s_critsectGui
;
758 s_critsectGui
= NULL
;
761 wxDELETE(s_critsectWaitingForGui
);
764 // ----------------------------------------------------------------------------
765 // under Windows, these functions are implemented usign a critical section and
766 // not a mutex, so the names are a bit confusing
767 // ----------------------------------------------------------------------------
769 void WXDLLEXPORT
wxMutexGuiEnter()
771 // this would dead lock everything...
772 wxASSERT_MSG( !wxThread::IsMain(),
773 _T("main thread doesn't want to block in wxMutexGuiEnter()!") );
775 // the order in which we enter the critical sections here is crucial!!
777 // set the flag telling to the main thread that we want to do some GUI
779 wxCriticalSectionLocker
enter(*s_critsectWaitingForGui
);
784 wxWakeUpMainThread();
786 // now we may block here because the main thread will soon let us in
787 // (during the next iteration of OnIdle())
788 s_critsectGui
->Enter();
791 void WXDLLEXPORT
wxMutexGuiLeave()
793 wxCriticalSectionLocker
enter(*s_critsectWaitingForGui
);
795 if ( wxThread::IsMain() )
797 s_bGuiOwnedByMainThread
= FALSE
;
801 // decrement the number of waiters now
802 wxASSERT_MSG( s_nWaitingForGui
> 0,
803 _T("calling wxMutexGuiLeave() without entering it first?") );
807 wxWakeUpMainThread();
810 s_critsectGui
->Leave();
813 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
815 wxASSERT_MSG( wxThread::IsMain(),
816 _T("only main thread may call wxMutexGuiLeaveOrEnter()!") );
818 wxCriticalSectionLocker
enter(*s_critsectWaitingForGui
);
820 if ( s_nWaitingForGui
== 0 )
822 // no threads are waiting for GUI - so we may acquire the lock without
823 // any danger (but only if we don't already have it)
824 if ( !wxGuiOwnedByMainThread() )
826 s_critsectGui
->Enter();
828 s_bGuiOwnedByMainThread
= TRUE
;
830 //else: already have it, nothing to do
834 // some threads are waiting, release the GUI lock if we have it
835 if ( wxGuiOwnedByMainThread() )
839 //else: some other worker thread is doing GUI
843 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
845 return s_bGuiOwnedByMainThread
;
848 // wake up the main thread if it's in ::GetMessage()
849 void WXDLLEXPORT
wxWakeUpMainThread()
851 // sending any message would do - hopefully WM_NULL is harmless enough
852 if ( !::PostThreadMessage(s_idMainThread
, WM_NULL
, 0, 0) )
854 // should never happen
855 wxLogLastError("PostThreadMessage(WM_NULL)");
859 bool WXDLLEXPORT
wxIsWaitingForThread()
861 return s_waitingForThread
;
864 #endif // wxUSE_THREADS