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
);
322 // suspend/resume/terminate
325 inline void Cancel() { m_eState
= STATE_CANCELED
; }
328 inline void SetState(wxThreadState eState
) { m_eState
= eState
; }
329 inline wxThreadState
GetState() const { return m_eState
; }
332 void SetPriority(unsigned int nPriority
);
333 inline unsigned int GetPriority() const { return m_nPriority
; }
335 // thread handle and id
336 inline TID
GetHandle() const { return m_hThread
; }
337 TID
GetId() const { return m_hThread
; }
340 static DWORD
OS2ThreadStart(wxThread
*thread
);
343 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
344 // PM also has no real Tls mechanism to index pointers by so we'll just
345 // keep track of the wxWindows parent object here.
346 TID m_hThread
; // handle and ID of the thread
347 wxThreadState m_eState
; // state, see wxThreadState enum
348 unsigned int m_nPriority
; // thread priority in "wx" units
351 ULONG
wxThreadInternal::OS2ThreadStart(
357 DWORD dwRet
= (DWORD
)pThread
->Entry();
359 // enter m_critsect before changing the thread state
360 pThread
->m_critsect
.Enter();
362 bool bWasCancelled
= pThread
->m_internal
->GetState() == STATE_CANCELED
;
364 pThread
->m_internal
->SetState(STATE_EXITED
);
365 pThread
->m_critsect
.Leave();
369 // if the thread was cancelled (from Delete()), then it the handle is still
371 if (pThread
->IsDetached() && !bWasCancelled
)
376 //else: the joinable threads handle will be closed when Wait() is done
380 void wxThreadInternal::SetPriority(
381 unsigned int nPriority
384 // translate wxWindows priority to the PM one
385 ULONG ulOS2_Priority
;
388 m_nPriority
= nPriority
;
390 if (m_nPriority
<= 20)
391 ulOS2_Priority
= PRTYC_NOCHANGE
;
392 else if (m_nPriority
<= 40)
393 ulOS2_Priority
= PRTYC_IDLETIME
;
394 else if (m_nPriority
<= 60)
395 ulOS2_Priority
= PRTYC_REGULAR
;
396 else if (m_nPriority
<= 80)
397 ulOS2_Priority
= PRTYC_TIMECRITICAL
;
398 else if (m_nPriority
<= 100)
399 ulOS2_Priority
= PRTYC_FOREGROUNDSERVER
;
402 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
403 ulOS2_Priority
= PRTYC_REGULAR
;
405 ulrc
= ::DosSetPriority( PRTYS_THREAD
412 wxLogSysError(_("Can't set thread priority"));
416 bool wxThreadInternal::Create(
422 ulrc
= ::DosCreateThread( &m_hThread
423 ,(PFNTHREAD
)wxThreadInternal::OS2ThreadStart
425 ,CREATE_SUSPENDED
| STACK_SPARSE
430 wxLogSysError(_("Can't create thread"));
434 if (m_nPriority
!= WXTHREAD_DEFAULT_PRIORITY
)
436 SetPriority(m_nPriority
);
441 bool wxThreadInternal::Suspend()
443 ULONG ulrc
= ::DosSuspendThread(m_hThread
);
447 wxLogSysError(_("Can not suspend thread %lu"), m_hThread
);
450 m_eState
= STATE_PAUSED
;
454 bool wxThreadInternal::Resume()
456 ULONG ulrc
= ::DosResumeThread(m_hThread
);
460 wxLogSysError(_("Can not suspend thread %lu"), m_hThread
);
463 m_eState
= STATE_PAUSED
;
470 wxThread
*wxThread::This()
472 wxThread
* pThread
= m_pThread
;
476 bool wxThread::IsMain()
481 ::DosGetInfoBlocks(&ptib
, &ppib
);
483 if (ptib
->tib_ptib2
->tib2_ultid
== s_ulIdMainThread
)
492 void wxThread::Yield()
497 void wxThread::Sleep(
498 unsigned long ulMilliseconds
501 ::DosSleep(ulMilliseconds
);
507 wxThread::wxThread(wxThreadKind kind
)
509 m_internal
= new wxThreadInternal();
511 m_isDetached
= kind
== wxTHREAD_DETACHED
;
514 wxThread::~wxThread()
519 // create/start thread
520 // -------------------
522 wxThreadError
wxThread::Create()
524 if ( !m_internal
->Create(this) )
525 return wxTHREAD_NO_RESOURCE
;
527 return wxTHREAD_NO_ERROR
;
530 wxThreadError
wxThread::Run()
532 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
534 if ( m_internal
->GetState() != STATE_NEW
)
536 // actually, it may be almost any state at all, not only STATE_RUNNING
537 return wxTHREAD_RUNNING
;
542 // suspend/resume thread
543 // ---------------------
545 wxThreadError
wxThread::Pause()
547 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
549 return m_internal
->Suspend() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
552 wxThreadError
wxThread::Resume()
554 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
556 return m_internal
->Resume() ? wxTHREAD_NO_ERROR
: wxTHREAD_MISC_ERROR
;
562 wxThread::ExitCode
wxThread::Wait()
564 // although under Windows we can wait for any thread, it's an error to
565 // wait for a detached one in wxWin API
566 wxCHECK_MSG( !IsDetached(), (ExitCode
)-1,
567 _T("can't wait for detached thread") );
568 ExitCode rc
= (ExitCode
)-1;
574 wxThreadError
wxThread::Delete(ExitCode
*pRc
)
578 // Delete() is always safe to call, so consider all possible states
582 TID hThread
= m_internal
->GetHandle();
588 // set flag for wxIsWaitingForThread()
589 gs_bWaitingForThread
= TRUE
;
596 // ask the thread to terminate
598 wxCriticalSectionLocker
lock(m_critsect
);
599 m_internal
->Cancel();
603 // need a way to finish GUI processing before killing the thread
604 // until then we just exit
606 if ((gs_nWaitingForGui
> 0) && wxGuiOwnedByMainThread())
612 // can't wait for yourself to end under OS/2 so just quit
614 #endif // wxUSE_GUI/!wxUSE_GUI
618 gs_bWaitingForThread
= FALSE
;
627 // probably won't get this far, but
636 return rc
== (ExitCode
)-1 ? wxTHREAD_MISC_ERROR
: wxTHREAD_NO_ERROR
;
639 wxThreadError
wxThread::Kill()
642 return wxTHREAD_NOT_RUNNING
;
644 ::DosKillThread(m_internal
->GetHandle());
650 return wxTHREAD_NO_ERROR
;
659 ::DosExit(EXIT_THREAD
, ULONG(pStatus
));
660 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
663 void wxThread::SetPriority(
667 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
669 m_internal
->SetPriority(nPrio
);
672 unsigned int wxThread::GetPriority() const
674 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
676 return m_internal
->GetPriority();
679 unsigned long wxThread::GetId() const
681 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
); // const_cast
683 return (unsigned long)m_internal
->GetId();
686 bool wxThread::IsRunning() const
688 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
690 return(m_internal
->GetState() == STATE_RUNNING
);
693 bool wxThread::IsAlive() const
695 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
697 return (m_internal
->GetState() == STATE_RUNNING
) ||
698 (m_internal
->GetState() == STATE_PAUSED
);
701 bool wxThread::IsPaused() const
703 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
705 return (m_internal
->GetState() == STATE_PAUSED
);
708 bool wxThread::TestDestroy()
710 wxCriticalSectionLocker
lock((wxCriticalSection
&)m_critsect
);
712 return m_internal
->GetState() == STATE_CANCELED
;
715 // ----------------------------------------------------------------------------
716 // Automatic initialization for thread module
717 // ----------------------------------------------------------------------------
719 class wxThreadModule
: public wxModule
722 virtual bool OnInit();
723 virtual void OnExit();
726 DECLARE_DYNAMIC_CLASS(wxThreadModule
)
729 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule
, wxModule
)
731 bool wxThreadModule::OnInit()
733 gs_pCritsectWaitingForGui
= new wxCriticalSection();
735 gs_pCritsectGui
= new wxCriticalSection();
736 gs_pCritsectGui
->Enter();
741 ::DosGetInfoBlocks(&ptib
, &ppib
);
743 s_ulIdMainThread
= ptib
->tib_ptib2
->tib2_ultid
;
747 void wxThreadModule::OnExit()
751 gs_pCritsectGui
->Leave();
752 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
753 delete gs_pCritsectGui
;
755 gs_pCritsectGui
= NULL
;
758 #if (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
759 wxDELETE(gs_pCritsectWaitingForGui
);
763 // ----------------------------------------------------------------------------
765 // ----------------------------------------------------------------------------
767 // Does nothing under OS/2 [for now]
768 void WXDLLEXPORT
wxWakeUpMainThread()
772 void WXDLLEXPORT
wxMutexGuiLeave()
774 wxCriticalSectionLocker
enter(*gs_pCritsectWaitingForGui
);
776 if ( wxThread::IsMain() )
778 gs_bGuiOwnedByMainThread
= FALSE
;
782 // decrement the number of waiters now
783 wxASSERT_MSG(gs_nWaitingForGui
> 0,
784 wxT("calling wxMutexGuiLeave() without entering it first?") );
788 wxWakeUpMainThread();
791 gs_pCritsectGui
->Leave();
794 void WXDLLEXPORT
wxMutexGuiLeaveOrEnter()
796 wxASSERT_MSG( wxThread::IsMain(),
797 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
799 wxCriticalSectionLocker
enter(*gs_pCritsectWaitingForGui
);
801 if (gs_nWaitingForGui
== 0)
803 // no threads are waiting for GUI - so we may acquire the lock without
804 // any danger (but only if we don't already have it)
805 if (!wxGuiOwnedByMainThread())
807 gs_pCritsectGui
->Enter();
809 gs_bGuiOwnedByMainThread
= TRUE
;
811 //else: already have it, nothing to do
815 // some threads are waiting, release the GUI lock if we have it
816 if (wxGuiOwnedByMainThread())
820 //else: some other worker thread is doing GUI
824 bool WXDLLEXPORT
wxGuiOwnedByMainThread()
826 return gs_bGuiOwnedByMainThread
;
829 bool WXDLLEXPORT
wxIsWaitingForThread()
831 return gs_bWaitingForThread
;