1 /////////////////////////////////////////////////////////////////////////////
3 // Purpose: wxThread Implementation. For Unix ports, see e.g. src/gtk
4 // Author: Original from Wolfram Gloger/Guilhem Lavaux
5 // Modified by: David Webster
8 // Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
12 // ----------------------------------------------------------------------------
14 // ----------------------------------------------------------------------------
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
23 #include "wx/module.h"
27 #include "wx/thread.h"
29 #define INCL_DOSSEMAPHORES
30 #define INCL_DOSPROCESS
35 // the possible states of the thread ("=>" shows all possible transitions from
39 STATE_NEW
, // didn't start execution yet (=> RUNNING)
40 STATE_RUNNING
, // thread is running (=> PAUSED, CANCELED)
41 STATE_PAUSED
, // thread is temporarily suspended (=> RUNNING)
42 STATE_CANCELED
, // thread should terminate a.s.a.p. (=> EXITED)
43 STATE_EXITED
// thread is terminating
46 // ----------------------------------------------------------------------------
48 // ----------------------------------------------------------------------------
50 // id of the main thread - the one which can call GUI functions without first
51 // calling wxMutexGuiEnter()
52 static ULONG s_ulIdMainThread
= 0;
53 wxMutex
* p_wxMainMutex
;
55 // OS2 substitute for Tls pointer the current parent thread object
56 wxThread
* m_pThread
; // pointer to the wxWindows thread object
58 // if it's FALSE, some secondary thread is holding the GUI lock
59 static bool gs_bGuiOwnedByMainThread
= TRUE
;
61 // critical section which controls access to all GUI functions: any secondary
62 // thread (i.e. except the main one) must enter this crit section before doing
64 static wxCriticalSection
*gs_pCritsectGui
= NULL
;
66 // critical section which protects s_nWaitingForGui variable
67 static wxCriticalSection
*gs_pCritsectWaitingForGui
= NULL
;
69 // number of threads waiting for GUI in wxMutexGuiEnter()
70 static size_t gs_nWaitingForGui
= 0;
72 // are we waiting for a thread termination?
73 static bool gs_bWaitingForThread
= FALSE
;
75 // ============================================================================
76 // OS/2 implementation of thread classes
77 // ============================================================================
79 // ----------------------------------------------------------------------------
80 // wxMutex implementation
81 // ----------------------------------------------------------------------------
92 m_internal
= new wxMutexInternal
;
93 ulrc
= ::DosCreateMutexSem(NULL
, &m_internal
->m_vMutex
, 0L, FALSE
);
96 wxLogSysError(_("Can not create mutex."));
104 wxLogDebug(wxT("Warning: freeing a locked mutex (%d locks)."), m_locked
);
105 ::DosCloseMutexSem(m_internal
->m_vMutex
);
106 m_internal
->m_vMutex
= NULL
;
109 wxMutexError
wxMutex::Lock()
113 ulrc
= ::DosRequestMutexSem(m_internal
->m_vMutex
, SEM_INDEFINITE_WAIT
);
117 case ERROR_TOO_MANY_SEM_REQUESTS
:
124 case ERROR_INVALID_HANDLE
:
125 case ERROR_INTERRUPT
:
126 case ERROR_SEM_OWNER_DIED
:
127 wxLogSysError(_("Couldn't acquire a mutex lock"));
128 return wxMUTEX_MISC_ERROR
;
132 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
135 return wxMUTEX_NO_ERROR
;
138 wxMutexError
wxMutex::TryLock()
142 ulrc
= ::DosRequestMutexSem(m_internal
->m_vMutex
, SEM_IMMEDIATE_RETURN
/*0L*/);
143 if (ulrc
== ERROR_TIMEOUT
|| ulrc
== ERROR_TOO_MANY_SEM_REQUESTS
)
147 return wxMUTEX_NO_ERROR
;
150 wxMutexError
wxMutex::Unlock()
157 ulrc
= ::DosReleaseMutexSem(m_internal
->m_vMutex
);
160 wxLogSysError(_("Couldn't release a mutex"));
161 return wxMUTEX_MISC_ERROR
;
163 return wxMUTEX_NO_ERROR
;
166 // ----------------------------------------------------------------------------
167 // wxCondition implementation
168 // ----------------------------------------------------------------------------
170 class wxConditionInternal
173 inline wxConditionInternal ()
175 ::DosCreateEventSem(NULL
, &m_vEvent
, DC_SEM_SHARED
, FALSE
);
178 wxLogSysError(_("Can not create event semaphore."));
184 unsigned long ulTimeout
190 ulrc
= ::DosWaitEventSem(m_vEvent
, ulTimeout
);
192 return (ulrc
!= ERROR_TIMEOUT
);
195 inline ~wxConditionInternal ()
201 ulrc
= ::DosCloseEventSem(m_vEvent
);
204 wxLogLastError("DosCloseEventSem(m_vEvent)");
213 wxCondition::wxCondition()
218 m_internal
= new wxConditionInternal
;
219 ulrc
= ::DosCreateEventSem(NULL
, &m_internal
->m_vEvent
, 0L, FALSE
);
222 wxLogSysError(_("Can not create event object."));
224 m_internal
->m_nWaiters
= 0;
225 // ?? just for good measure?
226 ::DosResetEventSem(m_internal
->m_vEvent
, &ulCount
);
229 wxCondition::~wxCondition()
231 ::DosCloseEventSem(m_internal
->m_vEvent
);
236 void wxCondition::Wait()
238 (void)m_internal
->Wait(SEM_INDEFINITE_WAIT
);
241 bool wxCondition::Wait(
243 , unsigned long lNsec
)
245 return m_internal
->Wait(lSec
*1000 + lNsec
/1000000);
248 void wxCondition::Signal()
250 ::DosPostEventSem(m_internal
->m_vEvent
);
253 void wxCondition::Broadcast()
257 for (i
= 0; i
< m_internal
->m_nWaiters
; i
++)
259 if (::DosPostEventSem(m_internal
->m_vEvent
) != 0)
261 wxLogSysError(_("Couldn't change the state of event object."));
266 // ----------------------------------------------------------------------------
267 // wxCriticalSection implementation
268 // ----------------------------------------------------------------------------
270 wxCriticalSection::wxCriticalSection()
274 wxCriticalSection::~wxCriticalSection()
278 void wxCriticalSection::Enter()
283 void wxCriticalSection::Leave()
288 // ----------------------------------------------------------------------------
289 // wxThread implementation
290 // ----------------------------------------------------------------------------
292 // wxThreadInternal class
293 // ----------------------
295 class wxThreadInternal
298 inline wxThreadInternal()
301 m_eState
= STATE_NEW
;
319 // create a new (suspended) thread (for the given thread object)
320 bool Create( wxThread
* pThread
321 ,unsigned int uStackSize
324 // suspend/resume/terminate
327 inline void Cancel() { m_eState
= STATE_CANCELED
; }
330 inline void SetState(wxThreadState eState
) { m_eState
= eState
; }
331 inline wxThreadState
GetState() const { return m_eState
; }
334 void SetPriority(unsigned int nPriority
);
335 inline unsigned int GetPriority() const { return m_nPriority
; }
337 // thread handle and id
338 inline TID
GetHandle() const { return m_hThread
; }
339 TID
GetId() const { return m_hThread
; }
342 static DWORD
OS2ThreadStart(wxThread
*thread
);
345 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
346 // PM also has no real Tls mechanism to index pointers by so we'll just
347 // keep track of the wxWindows parent object here.
348 TID m_hThread
; // handle and ID of the thread
349 wxThreadState m_eState
; // state, see wxThreadState enum
350 unsigned int m_nPriority
; // thread priority in "wx" units
353 ULONG
wxThreadInternal::OS2ThreadStart(
359 DWORD dwRet
= (DWORD
)pThread
->Entry();
361 // enter m_critsect before changing the thread state
362 pThread
->m_critsect
.Enter();
364 bool bWasCancelled
= pThread
->m_internal
->GetState() == STATE_CANCELED
;
366 pThread
->m_internal
->SetState(STATE_EXITED
);
367 pThread
->m_critsect
.Leave();
371 // if the thread was cancelled (from Delete()), then it the handle is still
373 if (pThread
->IsDetached() && !bWasCancelled
)
378 //else: the joinable threads handle will be closed when Wait() is done
382 void wxThreadInternal::SetPriority(
383 unsigned int nPriority
386 // translate wxWindows priority to the PM one
387 ULONG ulOS2_Priority
;
390 m_nPriority
= nPriority
;
392 if (m_nPriority
<= 20)
393 ulOS2_Priority
= PRTYC_NOCHANGE
;
394 else if (m_nPriority
<= 40)
395 ulOS2_Priority
= PRTYC_IDLETIME
;
396 else if (m_nPriority
<= 60)
397 ulOS2_Priority
= PRTYC_REGULAR
;
398 else if (m_nPriority
<= 80)
399 ulOS2_Priority
= PRTYC_TIMECRITICAL
;
400 else if (m_nPriority
<= 100)
401 ulOS2_Priority
= PRTYC_FOREGROUNDSERVER
;
404 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
405 ulOS2_Priority
= PRTYC_REGULAR
;
407 ulrc
= ::DosSetPriority( PRTYS_THREAD
414 wxLogSysError(_("Can't set thread priority"));
418 bool wxThreadInternal::Create(
420 , unsigned int uStackSize
425 ulrc
= ::DosCreateThread( &m_hThread
426 ,(PFNTHREAD
)wxThreadInternal::OS2ThreadStart
428 ,CREATE_SUSPENDED
| STACK_SPARSE
433 wxLogSysError(_("Can't create thread"));
437 if (m_nPriority
!= WXTHREAD_DEFAULT_PRIORITY
)
439 SetPriority(m_nPriority
);
444 bool wxThreadInternal::Suspend()
446 ULONG ulrc
= ::DosSuspendThread(m_hThread
);
450 wxLogSysError(_("Can not suspend thread %lu"), m_hThread
);
453 m_eState
= STATE_PAUSED
;
457 bool wxThreadInternal::Resume()
459 ULONG ulrc
= ::DosResumeThread(m_hThread
);
463 wxLogSysError(_("Can not suspend thread %lu"), m_hThread
);
466 m_eState
= STATE_PAUSED
;
473 wxThread
*wxThread::This()
475 wxThread
* pThread
= m_pThread
;
479 bool wxThread::IsMain()
484 ::DosGetInfoBlocks(&ptib
, &ppib
);
486 if (ptib
->tib_ptib2
->tib2_ultid
== s_ulIdMainThread
)
495 void wxThread::Yield()
500 void wxThread::Sleep(
501 unsigned long ulMilliseconds
504 ::DosSleep(ulMilliseconds
);
510 wxThread::wxThread(wxThreadKind kind
)
512 m_internal
= new wxThreadInternal();
514 m_isDetached
= kind
== wxTHREAD_DETACHED
;
517 wxThread::~wxThread()
522 // create/start thread
523 // -------------------
525 wxThreadError
wxThread::Create(
526 unsigned int uStackSize
529 if ( !m_internal
->Create(this, uStackSize
) )
530 return wxTHREAD_NO_RESOURCE
;
532 return wxTHREAD_NO_ERROR
;
535 wxThreadError
wxThread::Run()
537 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
539 if ( m_internal
->GetState() != STATE_NEW
)
541 // actually, it may be almost any state at all, not only STATE_RUNNING
542 return wxTHREAD_RUNNING
;
547 // suspend/resume thread
548 // ---------------------
550 wxThreadError
wxThread::Pause()
552 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
554 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
557 wxThreadError
wxThread::Resume()
559 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
561 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
567 wxThread::ExitCode
wxThread::Wait()
569 // although under Windows we can wait for any thread, it's an error to
570 // wait for a detached one in wxWin API
571 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
572 _T("can't wait for detached thread") );
573 ExitCode rc
= (ExitCode
)-1;
579 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
583 // Delete() is always safe to call, so consider all possible states
587 TID hThread
= m_internal
->GetHandle();
593 // set flag for wxIsWaitingForThread()
594 gs_bWaitingForThread
= TRUE
;
601 // ask the thread to terminate
603 wxCriticalSectionLocker
lock(m_critsect
);
604 m_internal
->Cancel();
608 // need a way to finish GUI processing before killing the thread
609 // until then we just exit
611 if ((gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread())
617 // can't wait for yourself to end under OS/2 so just quit
619 #endif // wxUSE_GUI/!wxUSE_GUI
623 gs_bWaitingForThread
= FALSE
;
632 // probably won't get this far, but
641 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
644 wxThreadError
wxThread::Kill()
647 return wxTHREAD_NOT_RUNNING
;
649 ::DosKillThread(m_internal
->GetHandle());
655 return wxTHREAD_NO_ERROR
;
664 ::DosExit(EXIT_THREAD
, ULONG(pStatus
));
665 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
668 void wxThread::SetPriority(
672 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
674 m_internal
->SetPriority(nPrio
);
677 unsigned int wxThread::GetPriority() const
679 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
681 return m_internal
->GetPriority();
684 unsigned long wxThread::GetId() const
686 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
688 return (unsigned long)m_internal
->GetId();
691 bool wxThread::IsRunning() const
693 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
695 return(m_internal
->GetState() == STATE_RUNNING
);
698 bool wxThread::IsAlive() const
700 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
702 return (m_internal
->GetState() == STATE_RUNNING
) ||
703 (m_internal
->GetState() == STATE_PAUSED
);
706 bool wxThread::IsPaused() const
708 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
710 return (m_internal
->GetState() == STATE_PAUSED
);
713 bool wxThread::TestDestroy()
715 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
717 return m_internal
->GetState() == STATE_CANCELED
;
720 // ----------------------------------------------------------------------------
721 // Automatic initialization for thread module
722 // ----------------------------------------------------------------------------
724 class wxThreadModule
: public wxModule
727 virtual bool OnInit();
728 virtual void OnExit();
731 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
734 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
736 bool wxThreadModule::OnInit()
738 gs_pCritsectWaitingForGui
= new wxCriticalSection();
740 gs_pCritsectGui
= new wxCriticalSection();
741 gs_pCritsectGui
->Enter();
746 ::DosGetInfoBlocks(&ptib
, &ppib
);
748 s_ulIdMainThread
= ptib
->tib_ptib2
->tib2_ultid
;
752 void wxThreadModule::OnExit()
756 gs_pCritsectGui
->Leave();
757 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
758 delete gs_pCritsectGui
;
760 gs_pCritsectGui
= NULL
;
763 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
764 wxDELETE(gs_pCritsectWaitingForGui
);
768 // ----------------------------------------------------------------------------
770 // ----------------------------------------------------------------------------
772 // Does nothing under OS/2 [for now]
773 void WXDLLEXPORT
wxWakeUpMainThread()
777 void WXDLLEXPORT
wxMutexGuiLeave()
779 wxCriticalSectionLocker
enter(*gs_pCritsectWaitingForGui
);
781 if ( wxThread::IsMain() )
783 gs_bGuiOwnedByMainThread
= FALSE
;
787 // decrement the number of waiters now
788 wxASSERT_MSG(gs_nWaitingForGui
> 0,
789 wxT("calling wxMutexGuiLeave() without entering it first?") );
793 wxWakeUpMainThread();
796 gs_pCritsectGui
->Leave();
799 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
801 wxASSERT_MSG( wxThread::IsMain(),
802 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
804 wxCriticalSectionLocker
enter(*gs_pCritsectWaitingForGui
);
806 if (gs_nWaitingForGui
== 0)
808 // no threads are waiting for GUI - so we may acquire the lock without
809 // any danger (but only if we don't already have it)
810 if (!wxGuiOwnedByMainThread())
812 gs_pCritsectGui
->Enter();
814 gs_bGuiOwnedByMainThread
= TRUE
;
816 //else: already have it, nothing to do
820 // some threads are waiting, release the GUI lock if we have it
821 if (wxGuiOwnedByMainThread())
825 //else: some other worker thread is doing GUI
829 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
831 return gs_bGuiOwnedByMainThread
;
834 bool WXDLLEXPORT
wxIsWaitingForThread()
836 return gs_bWaitingForThread
;