]> git.saurik.com Git - wxWidgets.git/blob - src/os2/thread.cpp
thread updates
[wxWidgets.git] / src / os2 / thread.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: thread.cpp
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
6 // Created: 04/22/98
7 // RCS-ID: $Id$
8 // Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998)
9 // Licence: wxWindows licence
10 /////////////////////////////////////////////////////////////////////////////
11
12 // ----------------------------------------------------------------------------
13 // headers
14 // ----------------------------------------------------------------------------
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #if wxUSE_THREADS
20
21 #include <stdio.h>
22
23 #include "wx/module.h"
24 #include "wx/thread.h"
25
26 #define INCL_DOSSEMAPHORES
27 #define INCL_DOSPROCESS
28 #define INCL_ERRORS
29 #include <os2.h>
30 #include <bseerr.h>
31
32 // the possible states of the thread ("=>" shows all possible transitions from
33 // this state)
34 enum wxThreadState
35 {
36 STATE_NEW, // didn't start execution yet (=> RUNNING)
37 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
38 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
39 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
40 STATE_EXITED // thread is terminating
41 };
42
43 // ----------------------------------------------------------------------------
44 // static variables
45 // ----------------------------------------------------------------------------
46
47 // id of the main thread - the one which can call GUI functions without first
48 // calling wxMutexGuiEnter()
49 static ULONG s_ulIdMainThread = 0;
50 wxMutex* p_wxMainMutex;
51
52 // OS2 substitute for Tls pointer the current parent thread object
53 wxThread* m_pThread; // pointer to the wxWindows thread object
54
55 // if it's FALSE, some secondary thread is holding the GUI lock
56 static bool s_bGuiOwnedByMainThread = TRUE;
57
58 // critical section which controls access to all GUI functions: any secondary
59 // thread (i.e. except the main one) must enter this crit section before doing
60 // any GUI calls
61 static wxCriticalSection *s_pCritsectGui = NULL;
62
63 // critical section which protects s_nWaitingForGui variable
64 static wxCriticalSection *s_pCritsectWaitingForGui = NULL;
65
66 // number of threads waiting for GUI in wxMutexGuiEnter()
67 static size_t s_nWaitingForGui = 0;
68
69 // are we waiting for a thread termination?
70 static bool s_bWaitingForThread = FALSE;
71
72 // ============================================================================
73 // OS/2 implementation of thread classes
74 // ============================================================================
75
76 // ----------------------------------------------------------------------------
77 // wxMutex implementation
78 // ----------------------------------------------------------------------------
79 class wxMutexInternal
80 {
81 public:
82 HMTX m_vMutex;
83 };
84
85 wxMutex::wxMutex()
86 {
87 APIRET ulrc;
88
89 p_internal = new wxMutexInternal;
90 ulrc = ::DosCreateMutexSem(NULL, &p_internal->m_vMutex, 0L, FALSE);
91 if (ulrc != 0)
92 {
93 wxLogSysError(_("Can not create mutex."));
94 }
95 m_locked = 0;
96 }
97
98 wxMutex::~wxMutex()
99 {
100 if (m_locked > 0)
101 wxLogDebug(wxT("Warning: freeing a locked mutex (%d locks)."), m_locked);
102 ::DosCloseMutexSem(p_internal->m_vMutex);
103 p_internal->m_vMutex = NULL;
104 }
105
106 wxMutexError wxMutex::Lock()
107 {
108 APIRET ulrc;
109
110 ulrc = ::DosRequestMutexSem(p_internal->m_vMutex, SEM_INDEFINITE_WAIT);
111
112 switch (ulrc)
113 {
114 case ERROR_TOO_MANY_SEM_REQUESTS:
115 return wxMUTEX_BUSY;
116
117 case NO_ERROR:
118 // ok
119 break;
120
121 case ERROR_INVALID_HANDLE:
122 case ERROR_INTERRUPT:
123 case ERROR_SEM_OWNER_DIED:
124 wxLogSysError(_("Couldn't acquire a mutex lock"));
125 return wxMUTEX_MISC_ERROR;
126
127 case ERROR_TIMEOUT:
128 default:
129 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
130 }
131 m_locked++;
132 return wxMUTEX_NO_ERROR;
133 }
134
135 wxMutexError wxMutex::TryLock()
136 {
137 ULONG ulrc;
138
139 ulrc = ::DosRequestMutexSem(p_internal->m_vMutex, SEM_IMMEDIATE_RETURN /*0L*/);
140 if (ulrc == ERROR_TIMEOUT || ulrc == ERROR_TOO_MANY_SEM_REQUESTS)
141 return wxMUTEX_BUSY;
142
143 m_locked++;
144 return wxMUTEX_NO_ERROR;
145 }
146
147 wxMutexError wxMutex::Unlock()
148 {
149 APIRET ulrc;
150
151 if (m_locked > 0)
152 m_locked--;
153
154 ulrc = ::DosReleaseMutexSem(p_internal->m_vMutex);
155 if (ulrc != 0)
156 {
157 wxLogSysError(_("Couldn't release a mutex"));
158 return wxMUTEX_MISC_ERROR;
159 }
160 return wxMUTEX_NO_ERROR;
161 }
162
163 // ----------------------------------------------------------------------------
164 // wxCondition implementation
165 // ----------------------------------------------------------------------------
166
167 class wxConditionInternal
168 {
169 public:
170 HEV m_vEvent;
171 int m_nWaiters;
172 };
173
174 wxCondition::wxCondition()
175 {
176 APIRET ulrc;
177 ULONG ulCount;
178
179 p_internal = new wxConditionInternal;
180 ulrc = ::DosCreateEventSem(NULL, &p_internal->m_vEvent, 0L, FALSE);
181 if (ulrc != 0)
182 {
183 wxLogSysError(_("Can not create event object."));
184 }
185 p_internal->m_nWaiters = 0;
186 // ?? just for good measure?
187 ::DosResetEventSem(p_internal->m_vEvent, &ulCount);
188 }
189
190 wxCondition::~wxCondition()
191 {
192 ::DosCloseEventSem(p_internal->m_vEvent);
193 delete p_internal;
194 p_internal = NULL;
195 }
196
197 void wxCondition::Wait(
198 wxMutex& rMutex
199 )
200 {
201 rMutex.Unlock();
202 p_internal->m_nWaiters++;
203 ::DosWaitEventSem(p_internal->m_vEvent, SEM_INDEFINITE_WAIT);
204 p_internal->m_nWaiters--;
205 rMutex.Lock();
206 }
207
208 bool wxCondition::Wait(
209 wxMutex& rMutex
210 , unsigned long ulSec
211 , unsigned long ulMillisec)
212 {
213 APIRET ulrc;
214
215 rMutex.Unlock();
216 p_internal->m_nWaiters++;
217 ulrc = ::DosWaitEventSem(p_internal->m_vEvent, ULONG((ulSec * 1000L) + ulMillisec));
218 p_internal->m_nWaiters--;
219 rMutex.Lock();
220
221 return (ulrc != ERROR_TIMEOUT);
222 }
223
224 void wxCondition::Signal()
225 {
226 ::DosPostEventSem(p_internal->m_vEvent);
227 }
228
229 void wxCondition::Broadcast()
230 {
231 int i;
232
233 for (i = 0; i < p_internal->m_nWaiters; i++)
234 {
235 if (::DosPostEventSem(p_internal->m_vEvent) != 0)
236 {
237 wxLogSysError(_("Couldn't change the state of event object."));
238 }
239 }
240 }
241
242 // ----------------------------------------------------------------------------
243 // wxCriticalSection implementation
244 // ----------------------------------------------------------------------------
245
246 wxCriticalSection::wxCriticalSection()
247 {
248 }
249
250 wxCriticalSection::~wxCriticalSection()
251 {
252 }
253
254 void wxCriticalSection::Enter()
255 {
256 ::DosEnterCritSec();
257 }
258
259 void wxCriticalSection::Leave()
260 {
261 ::DosExitCritSec();
262 }
263
264 // ----------------------------------------------------------------------------
265 // wxThread implementation
266 // ----------------------------------------------------------------------------
267
268 // wxThreadInternal class
269 // ----------------------
270
271 class wxThreadInternal
272 {
273 public:
274 inline wxThreadInternal()
275 {
276 m_hThread = 0;
277 m_eState = STATE_NEW;
278 m_nPriority = 0;
279 }
280
281 // create a new (suspended) thread (for the given thread object)
282 bool Create(wxThread* pThread);
283
284 // suspend/resume/terminate
285 bool Suspend();
286 bool Resume();
287 inline void Cancel() { m_eState = STATE_CANCELED; }
288
289 // thread state
290 inline void SetState(wxThreadState eState) { m_eState = eState; }
291 inline wxThreadState GetState() const { return m_eState; }
292
293 // thread priority
294 inline void SetPriority(unsigned int nPriority) { m_nPriority = nPriority; }
295 inline unsigned int GetPriority() const { return m_nPriority; }
296
297 // thread handle and id
298 inline TID GetHandle() const { return m_hThread; }
299 TID GetId() const { return m_hThread; }
300
301 // thread function
302 static DWORD OS2ThreadStart(wxThread *thread);
303
304 private:
305 // Threads in OS/2 have only an ID, so m_hThread is both it's handle and ID
306 // PM also has no real Tls mechanism to index pointers by so we'll just
307 // keep track of the wxWindows parent object here.
308 TID m_hThread; // handle and ID of the thread
309 wxThreadState m_eState; // state, see wxThreadState enum
310 unsigned int m_nPriority; // thread priority in "wx" units
311 };
312
313 ULONG wxThreadInternal::OS2ThreadStart(
314 wxThread* pThread
315 )
316 {
317 m_pThread = pThread;
318
319 DWORD dwRet = (DWORD)pThread->Entry();
320
321 pThread->p_internal->SetState(STATE_EXITED);
322 pThread->OnExit();
323
324 delete pThread;
325 m_pThread = NULL;
326 return dwRet;
327 }
328
329 bool wxThreadInternal::Create(
330 wxThread* pThread
331 )
332 {
333 APIRET ulrc;
334
335 ulrc = ::DosCreateThread( &m_hThread
336 ,(PFNTHREAD)wxThreadInternal::OS2ThreadStart
337 ,(ULONG)pThread
338 ,CREATE_SUSPENDED | STACK_SPARSE
339 ,8192L
340 );
341 if(ulrc != 0)
342 {
343 wxLogSysError(_("Can't create thread"));
344
345 return FALSE;
346 }
347
348 // translate wxWindows priority to the PM one
349 ULONG ulOS2_Priority;
350
351 if (m_nPriority <= 20)
352 ulOS2_Priority = PRTYC_NOCHANGE;
353 else if (m_nPriority <= 40)
354 ulOS2_Priority = PRTYC_IDLETIME;
355 else if (m_nPriority <= 60)
356 ulOS2_Priority = PRTYC_REGULAR;
357 else if (m_nPriority <= 80)
358 ulOS2_Priority = PRTYC_TIMECRITICAL;
359 else if (m_nPriority <= 100)
360 ulOS2_Priority = PRTYC_FOREGROUNDSERVER;
361 else
362 {
363 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
364 ulOS2_Priority = PRTYC_REGULAR;
365 }
366 ulrc = ::DosSetPriority( PRTYS_THREAD
367 ,ulOS2_Priority
368 ,0
369 ,(ULONG)m_hThread
370 );
371 if (ulrc != 0)
372 {
373 wxLogSysError(_("Can't set thread priority"));
374 }
375 return TRUE;
376 }
377
378 bool wxThreadInternal::Suspend()
379 {
380 ULONG ulrc = ::DosSuspendThread(m_hThread);
381
382 if (ulrc != 0)
383 {
384 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
385 return FALSE;
386 }
387 m_eState = STATE_PAUSED;
388 return TRUE;
389 }
390
391 bool wxThreadInternal::Resume()
392 {
393 ULONG ulrc = ::DosResumeThread(m_hThread);
394
395 if (ulrc != 0)
396 {
397 wxLogSysError(_("Can not suspend thread %lu"), m_hThread);
398 return FALSE;
399 }
400 m_eState = STATE_PAUSED;
401 return TRUE;
402 }
403
404 // static functions
405 // ----------------
406
407 wxThread *wxThread::This()
408 {
409 wxThread* pThread = m_pThread;
410 return pThread;
411 }
412
413 bool wxThread::IsMain()
414 {
415 PTIB ptib;
416 PPIB ppib;
417
418 ::DosGetInfoBlocks(&ptib, &ppib);
419
420 if (ptib->tib_ptib2->tib2_ultid == s_ulIdMainThread)
421 return TRUE;
422 return FALSE;
423 }
424
425 #ifdef Yield
426 #undef Yield
427 #endif
428
429 void wxThread::Yield()
430 {
431 ::DosSleep(0);
432 }
433
434 void wxThread::Sleep(
435 unsigned long ulMilliseconds
436 )
437 {
438 ::DosSleep(ulMilliseconds);
439 }
440
441 // create/start thread
442 // -------------------
443
444 wxThreadError wxThread::Create()
445 {
446 if ( !p_internal->Create(this) )
447 return wxTHREAD_NO_RESOURCE;
448
449 return wxTHREAD_NO_ERROR;
450 }
451
452 wxThreadError wxThread::Run()
453 {
454 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
455
456 if ( p_internal->GetState() != STATE_NEW )
457 {
458 // actually, it may be almost any state at all, not only STATE_RUNNING
459 return wxTHREAD_RUNNING;
460 }
461 return Resume();
462 }
463
464 // suspend/resume thread
465 // ---------------------
466
467 wxThreadError wxThread::Pause()
468 {
469 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
470
471 return p_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
472 }
473
474 wxThreadError wxThread::Resume()
475 {
476 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
477
478 return p_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
479 }
480
481 // stopping thread
482 // ---------------
483
484 wxThread::ExitCode wxThread::Delete()
485 {
486 ExitCode rc = 0;
487 ULONG ulrc;
488
489 // Delete() is always safe to call, so consider all possible states
490 if (IsPaused())
491 Resume();
492
493 if (IsRunning())
494 {
495 if (IsMain())
496 {
497 // set flag for wxIsWaitingForThread()
498 s_bWaitingForThread = TRUE;
499 wxBeginBusyCursor();
500 }
501
502 TID hThread;
503
504 {
505 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
506
507 p_internal->Cancel();
508 hThread = p_internal->GetHandle();
509 }
510
511 // we can't just wait for the thread to terminate because it might be
512 // calling some GUI functions and so it will never terminate before we
513 // process the Windows messages that result from these functions
514
515 do
516 {
517 ulrc = ::DosWaitThread( &hThread
518 ,DCWW_NOWAIT
519 );
520 switch (ulrc)
521 {
522 case ERROR_INTERRUPT:
523 case ERROR_INVALID_THREADID:
524 // error
525 wxLogSysError(_("Can not wait for thread termination"));
526 Kill();
527 return (ExitCode)-1;
528
529 case 0:
530 // thread we're waiting for terminated
531 break;
532
533 case ERROR_THREAD_NOT_TERMINATED:
534 // new message arrived, process it
535 if (!wxTheApp->DoMessage())
536 {
537 // WM_QUIT received: kill the thread
538 Kill();
539 return (ExitCode)-1;
540 }
541 if (IsMain())
542 {
543 // give the thread we're waiting for chance to exit
544 // from the GUI call it might have been in
545 if ((s_nWaitingForGui > 0) && wxGuiOwnedByMainThread())
546 {
547 wxMutexGuiLeave();
548 }
549 }
550 break;
551
552 default:
553 wxFAIL_MSG(wxT("unexpected result of DosWatiThread"));
554 }
555 } while (ulrc != 0);
556
557 if (IsMain())
558 {
559 s_bWaitingForThread = FALSE;
560 wxEndBusyCursor();
561 }
562
563 ::DosExit(EXIT_THREAD, ulrc);
564 }
565 rc = (ExitCode)ulrc;
566 return rc;
567 }
568
569 wxThreadError wxThread::Kill()
570 {
571 if (!IsRunning())
572 return wxTHREAD_NOT_RUNNING;
573
574 ::DosKillThread(p_internal->GetHandle());
575 delete this;
576 return wxTHREAD_NO_ERROR;
577 }
578
579 void wxThread::Exit(
580 void* pStatus
581 )
582 {
583 delete this;
584 ::DosExit(EXIT_THREAD, ULONG(pStatus));
585 wxFAIL_MSG(wxT("Couldn't return from DosExit()!"));
586 }
587
588 void wxThread::SetPriority(
589 unsigned int nPrio
590 )
591 {
592 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
593
594 p_internal->SetPriority(nPrio);
595 }
596
597 unsigned int wxThread::GetPriority() const
598 {
599 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
600
601 return p_internal->GetPriority();
602 }
603
604 unsigned long wxThread::GetID() const
605 {
606 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
607
608 return (unsigned long)p_internal->GetId();
609 }
610
611 bool wxThread::IsRunning() const
612 {
613 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
614
615 return p_internal->GetState() == STATE_RUNNING;
616 }
617
618 bool wxThread::IsAlive() const
619 {
620 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
621
622 return (p_internal->GetState() == STATE_RUNNING) ||
623 (p_internal->GetState() == STATE_PAUSED);
624 }
625
626 bool wxThread::IsPaused() const
627 {
628 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
629
630 return (p_internal->GetState() == STATE_PAUSED);
631 }
632
633 bool wxThread::TestDestroy()
634 {
635 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
636
637 return p_internal->GetState() == STATE_CANCELED;
638 }
639
640 wxThread::wxThread()
641 {
642 p_internal = new wxThreadInternal();
643 }
644
645 wxThread::~wxThread()
646 {
647 delete p_internal;
648 }
649
650 // ----------------------------------------------------------------------------
651 // Automatic initialization for thread module
652 // ----------------------------------------------------------------------------
653
654 class wxThreadModule : public wxModule
655 {
656 public:
657 virtual bool OnInit();
658 virtual void OnExit();
659
660 private:
661 DECLARE_DYNAMIC_CLASS(wxThreadModule)
662 };
663
664 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
665
666 bool wxThreadModule::OnInit()
667 {
668 s_pCritsectWaitingForGui = new wxCriticalSection();
669
670 s_pCritsectGui = new wxCriticalSection();
671 s_pCritsectGui->Enter();
672
673 PTIB ptib;
674 PPIB ppib;
675
676 ::DosGetInfoBlocks(&ptib, &ppib);
677
678 s_ulIdMainThread = ptib->tib_ptib2->tib2_ultid;
679 return TRUE;
680 }
681
682 void wxThreadModule::OnExit()
683 {
684 if (s_pCritsectGui)
685 {
686 s_pCritsectGui->Leave();
687 delete s_pCritsectGui;
688 s_pCritsectGui = NULL;
689 }
690
691 wxDELETE(s_pCritsectWaitingForGui);
692 }
693
694 // ----------------------------------------------------------------------------
695 // Helper functions
696 // ----------------------------------------------------------------------------
697
698 // Does nothing under OS/2 [for now]
699 void WXDLLEXPORT wxWakeUpMainThread()
700 {
701 }
702
703 void WXDLLEXPORT wxMutexGuiLeave()
704 {
705 wxCriticalSectionLocker enter(*s_pCritsectWaitingForGui);
706
707 if ( wxThread::IsMain() )
708 {
709 s_bGuiOwnedByMainThread = FALSE;
710 }
711 else
712 {
713 // decrement the number of waiters now
714 wxASSERT_MSG( s_nWaitingForGui > 0,
715 wxT("calling wxMutexGuiLeave() without entering it first?") );
716
717 s_nWaitingForGui--;
718
719 wxWakeUpMainThread();
720 }
721
722 s_pCritsectGui->Leave();
723 }
724
725 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
726 {
727 wxASSERT_MSG( wxThread::IsMain(),
728 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
729
730 wxCriticalSectionLocker enter(*s_pCritsectWaitingForGui);
731
732 if ( s_nWaitingForGui == 0 )
733 {
734 // no threads are waiting for GUI - so we may acquire the lock without
735 // any danger (but only if we don't already have it)
736 if (!wxGuiOwnedByMainThread())
737 {
738 s_pCritsectGui->Enter();
739
740 s_bGuiOwnedByMainThread = TRUE;
741 }
742 //else: already have it, nothing to do
743 }
744 else
745 {
746 // some threads are waiting, release the GUI lock if we have it
747 if (wxGuiOwnedByMainThread())
748 {
749 wxMutexGuiLeave();
750 }
751 //else: some other worker thread is doing GUI
752 }
753 }
754
755 bool WXDLLEXPORT wxGuiOwnedByMainThread()
756 {
757 return s_bGuiOwnedByMainThread;
758 }
759
760 bool WXDLLEXPORT wxIsWaitingForThread()
761 {
762 return s_bWaitingForThread;
763 }
764
765 #endif
766 // wxUSE_THREADS