]> git.saurik.com Git - wxWidgets.git/blame_incremental - src/msw/thread.cpp
Committing in .
[wxWidgets.git] / src / msw / thread.cpp
... / ...
CommitLineData
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.cpp
3// Purpose: wxThread Implementation
4// Author: Original from Wolfram Gloger/Guilhem Lavaux
5// Modified by: Vadim Zeitlin to make it work :-)
6// Created: 04/22/98
7// RCS-ID: $Id$
8// Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
9// Vadim Zeitlin (1999)
10// Licence: wxWindows licence
11/////////////////////////////////////////////////////////////////////////////
12
13#ifdef __GNUG__
14 #pragma implementation "thread.h"
15#endif
16
17// ----------------------------------------------------------------------------
18// headers
19// ----------------------------------------------------------------------------
20
21// For compilers that support precompilation, includes "wx.h".
22#include "wx/wxprec.h"
23
24#if defined(__BORLANDC__)
25 #pragma hdrstop
26#endif
27
28#ifndef WX_PRECOMP
29 #include "wx/wx.h"
30#endif
31
32#if wxUSE_THREADS
33
34#include "wx/msw/private.h"
35
36#include "wx/module.h"
37#include "wx/thread.h"
38
39// the possible states of the thread ("=>" shows all possible transitions from
40// this state)
41enum wxThreadState
42{
43 STATE_NEW, // didn't start execution yet (=> RUNNING)
44 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
45 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
46 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
47 STATE_EXITED // thread is terminating
48};
49
50// ----------------------------------------------------------------------------
51// static variables
52// ----------------------------------------------------------------------------
53
54// TLS index of the slot where we store the pointer to the current thread
55static DWORD s_tlsThisThread = 0xFFFFFFFF;
56
57// id of the main thread - the one which can call GUI functions without first
58// calling wxMutexGuiEnter()
59static DWORD s_idMainThread = 0;
60
61// if it's FALSE, some secondary thread is holding the GUI lock
62static bool s_bGuiOwnedByMainThread = TRUE;
63
64// critical section which controls access to all GUI functions: any secondary
65// thread (i.e. except the main one) must enter this crit section before doing
66// any GUI calls
67static wxCriticalSection *s_critsectGui = NULL;
68
69// critical section which protects s_nWaitingForGui variable
70static wxCriticalSection *s_critsectWaitingForGui = NULL;
71
72// number of threads waiting for GUI in wxMutexGuiEnter()
73static size_t s_nWaitingForGui = 0;
74
75// are we waiting for a thread termination?
76static bool s_waitingForThread = FALSE;
77
78// ============================================================================
79// Windows implementation of thread classes
80// ============================================================================
81
82// ----------------------------------------------------------------------------
83// wxMutex implementation
84// ----------------------------------------------------------------------------
85
86class wxMutexInternal
87{
88public:
89 HANDLE p_mutex;
90};
91
92wxMutex::wxMutex()
93{
94 p_internal = new wxMutexInternal;
95 p_internal->p_mutex = CreateMutex(NULL, FALSE, NULL);
96 if ( !p_internal->p_mutex )
97 {
98 wxLogSysError(_("Can not create mutex."));
99 }
100
101 m_locked = 0;
102}
103
104wxMutex::~wxMutex()
105{
106 if (m_locked > 0)
107 wxLogDebug(wxT("Warning: freeing a locked mutex (%d locks)."), m_locked);
108 CloseHandle(p_internal->p_mutex);
109}
110
111wxMutexError wxMutex::Lock()
112{
113 DWORD ret;
114
115 ret = WaitForSingleObject(p_internal->p_mutex, INFINITE);
116 switch ( ret )
117 {
118 case WAIT_ABANDONED:
119 return wxMUTEX_BUSY;
120
121 case WAIT_OBJECT_0:
122 // ok
123 break;
124
125 case WAIT_FAILED:
126 wxLogSysError(_("Couldn't acquire a mutex lock"));
127 return wxMUTEX_MISC_ERROR;
128
129 case WAIT_TIMEOUT:
130 default:
131 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
132 }
133
134 m_locked++;
135 return wxMUTEX_NO_ERROR;
136}
137
138wxMutexError wxMutex::TryLock()
139{
140 DWORD ret;
141
142 ret = WaitForSingleObject(p_internal->p_mutex, 0);
143 if (ret == WAIT_TIMEOUT || ret == WAIT_ABANDONED)
144 return wxMUTEX_BUSY;
145
146 m_locked++;
147 return wxMUTEX_NO_ERROR;
148}
149
150wxMutexError wxMutex::Unlock()
151{
152 if (m_locked > 0)
153 m_locked--;
154
155 BOOL ret = ReleaseMutex(p_internal->p_mutex);
156 if ( ret == 0 )
157 {
158 wxLogSysError(_("Couldn't release a mutex"));
159 return wxMUTEX_MISC_ERROR;
160 }
161
162 return wxMUTEX_NO_ERROR;
163}
164
165// ----------------------------------------------------------------------------
166// wxCondition implementation
167// ----------------------------------------------------------------------------
168
169class wxConditionInternal
170{
171public:
172 HANDLE event;
173 int waiters;
174};
175
176wxCondition::wxCondition()
177{
178 p_internal = new wxConditionInternal;
179 p_internal->event = CreateEvent(NULL, FALSE, FALSE, NULL);
180 if ( !p_internal->event )
181 {
182 wxLogSysError(_("Can not create event object."));
183 }
184
185 p_internal->waiters = 0;
186}
187
188wxCondition::~wxCondition()
189{
190 CloseHandle(p_internal->event);
191}
192
193void wxCondition::Wait(wxMutex& mutex)
194{
195 mutex.Unlock();
196 p_internal->waiters++;
197 WaitForSingleObject(p_internal->event, INFINITE);
198 p_internal->waiters--;
199 mutex.Lock();
200}
201
202bool wxCondition::Wait(wxMutex& mutex,
203 unsigned long sec,
204 unsigned long nsec)
205{
206 DWORD ret;
207
208 mutex.Unlock();
209 p_internal->waiters++;
210 ret = WaitForSingleObject(p_internal->event, (sec*1000)+(nsec/1000000));
211 p_internal->waiters--;
212 mutex.Lock();
213
214 return (ret != WAIT_TIMEOUT);
215}
216
217void wxCondition::Signal()
218{
219 SetEvent(p_internal->event);
220}
221
222void wxCondition::Broadcast()
223{
224 int i;
225
226 for (i=0;i<p_internal->waiters;i++)
227 {
228 if ( SetEvent(p_internal->event) == 0 )
229 {
230 wxLogSysError(_("Couldn't change the state of event object."));
231 }
232 }
233}
234
235// ----------------------------------------------------------------------------
236// wxCriticalSection implementation
237// ----------------------------------------------------------------------------
238
239wxCriticalSection::wxCriticalSection()
240{
241 wxASSERT_MSG( sizeof(CRITICAL_SECTION) == sizeof(m_buffer),
242 _T("must increase buffer size in wx/thread.h") );
243
244 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
245}
246
247wxCriticalSection::~wxCriticalSection()
248{
249 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
250}
251
252void wxCriticalSection::Enter()
253{
254 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
255}
256
257void wxCriticalSection::Leave()
258{
259 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
260}
261
262// ----------------------------------------------------------------------------
263// wxThread implementation
264// ----------------------------------------------------------------------------
265
266// wxThreadInternal class
267// ----------------------
268
269class wxThreadInternal
270{
271public:
272 wxThreadInternal()
273 {
274 m_hThread = 0;
275 m_state = STATE_NEW;
276 m_priority = WXTHREAD_DEFAULT_PRIORITY;
277 }
278
279 // create a new (suspended) thread (for the given thread object)
280 bool Create(wxThread *thread);
281
282 // suspend/resume/terminate
283 bool Suspend();
284 bool Resume();
285 void Cancel() { m_state = STATE_CANCELED; }
286
287 // thread state
288 void SetState(wxThreadState state) { m_state = state; }
289 wxThreadState GetState() const { return m_state; }
290
291 // thread priority
292 void SetPriority(unsigned int priority) { m_priority = priority; }
293 unsigned int GetPriority() const { return m_priority; }
294
295 // thread handle and id
296 HANDLE GetHandle() const { return m_hThread; }
297 DWORD GetId() const { return m_tid; }
298
299 // thread function
300 static DWORD WinThreadStart(wxThread *thread);
301
302private:
303 HANDLE m_hThread; // handle of the thread
304 wxThreadState m_state; // state, see wxThreadState enum
305 unsigned int m_priority; // thread priority in "wx" units
306 DWORD m_tid; // thread id
307};
308
309DWORD wxThreadInternal::WinThreadStart(wxThread *thread)
310{
311 // store the thread object in the TLS
312 if ( !::TlsSetValue(s_tlsThisThread, thread) )
313 {
314 wxLogSysError(_("Can not start thread: error writing TLS."));
315
316 return (DWORD)-1;
317 }
318
319 DWORD ret = (DWORD)thread->Entry();
320 thread->p_internal->SetState(STATE_EXITED);
321 thread->OnExit();
322
323 delete thread;
324
325 return ret;
326}
327
328bool wxThreadInternal::Create(wxThread *thread)
329{
330 m_hThread = ::CreateThread
331 (
332 NULL, // default security
333 0, // default stack size
334 (LPTHREAD_START_ROUTINE) // thread entry point
335 wxThreadInternal::WinThreadStart, //
336 (LPVOID)thread, // parameter
337 CREATE_SUSPENDED, // flags
338 &m_tid // [out] thread id
339 );
340
341 if ( m_hThread == NULL )
342 {
343 wxLogSysError(_("Can't create thread"));
344
345 return FALSE;
346 }
347
348 // translate wxWindows priority to the Windows one
349 int win_priority;
350 if (m_priority <= 20)
351 win_priority = THREAD_PRIORITY_LOWEST;
352 else if (m_priority <= 40)
353 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
354 else if (m_priority <= 60)
355 win_priority = THREAD_PRIORITY_NORMAL;
356 else if (m_priority <= 80)
357 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
358 else if (m_priority <= 100)
359 win_priority = THREAD_PRIORITY_HIGHEST;
360 else
361 {
362 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
363 win_priority = THREAD_PRIORITY_NORMAL;
364 }
365
366 if ( ::SetThreadPriority(m_hThread, win_priority) == 0 )
367 {
368 wxLogSysError(_("Can't set thread priority"));
369 }
370
371 return TRUE;
372}
373
374bool wxThreadInternal::Suspend()
375{
376 DWORD nSuspendCount = ::SuspendThread(m_hThread);
377 if ( nSuspendCount == (DWORD)-1 )
378 {
379 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
380
381 return FALSE;
382 }
383
384 m_state = STATE_PAUSED;
385
386 return TRUE;
387}
388
389bool wxThreadInternal::Resume()
390{
391 DWORD nSuspendCount = ::ResumeThread(m_hThread);
392 if ( nSuspendCount == (DWORD)-1 )
393 {
394 wxLogSysError(_("Can not resume thread %x"), m_hThread);
395
396 return FALSE;
397 }
398
399 m_state = STATE_RUNNING;
400
401 return TRUE;
402}
403
404// static functions
405// ----------------
406
407wxThread *wxThread::This()
408{
409 wxThread *thread = (wxThread *)::TlsGetValue(s_tlsThisThread);
410
411 // be careful, 0 may be a valid return value as well
412 if ( !thread && (::GetLastError() != NO_ERROR) )
413 {
414 wxLogSysError(_("Couldn't get the current thread pointer"));
415
416 // return NULL...
417 }
418
419 return thread;
420}
421
422bool wxThread::IsMain()
423{
424 return ::GetCurrentThreadId() == s_idMainThread;
425}
426
427#ifdef Yield
428 #undef Yield
429#endif
430
431void wxThread::Yield()
432{
433 // 0 argument to Sleep() is special
434 ::Sleep(0);
435}
436
437void wxThread::Sleep(unsigned long milliseconds)
438{
439 ::Sleep(milliseconds);
440}
441
442// create/start thread
443// -------------------
444
445wxThreadError wxThread::Create()
446{
447 if ( !p_internal->Create(this) )
448 return wxTHREAD_NO_RESOURCE;
449
450 return wxTHREAD_NO_ERROR;
451}
452
453wxThreadError wxThread::Run()
454{
455 wxCriticalSectionLocker lock(m_critsect);
456
457 if ( p_internal->GetState() != STATE_NEW )
458 {
459 // actually, it may be almost any state at all, not only STATE_RUNNING
460 return wxTHREAD_RUNNING;
461 }
462
463 return Resume();
464}
465
466// suspend/resume thread
467// ---------------------
468
469wxThreadError wxThread::Pause()
470{
471 wxCriticalSectionLocker lock(m_critsect);
472
473 return p_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
474}
475
476wxThreadError wxThread::Resume()
477{
478 wxCriticalSectionLocker lock(m_critsect);
479
480 return p_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
481}
482
483// stopping thread
484// ---------------
485
486wxThread::ExitCode wxThread::Delete()
487{
488 ExitCode rc = 0;
489
490 // Delete() is always safe to call, so consider all possible states
491 if ( IsPaused() )
492 Resume();
493
494 if ( IsRunning() )
495 {
496 if ( IsMain() )
497 {
498 // set flag for wxIsWaitingForThread()
499 s_waitingForThread = TRUE;
500
501 wxBeginBusyCursor();
502 }
503
504 HANDLE hThread;
505 {
506 wxCriticalSectionLocker lock(m_critsect);
507
508 p_internal->Cancel();
509 hThread = p_internal->GetHandle();
510 }
511
512 // we can't just wait for the thread to terminate because it might be
513 // calling some GUI functions and so it will never terminate before we
514 // process the Windows messages that result from these functions
515 DWORD result;
516 do
517 {
518 result = ::MsgWaitForMultipleObjects
519 (
520 1, // number of objects to wait for
521 &hThread, // the objects
522 FALSE, // don't wait for all objects
523 INFINITE, // no timeout
524 QS_ALLEVENTS // return as soon as there are any events
525 );
526
527 switch ( result )
528 {
529 case 0xFFFFFFFF:
530 // error
531 wxLogSysError(_("Can not wait for thread termination"));
532 Kill();
533 return (ExitCode)-1;
534
535 case WAIT_OBJECT_0:
536 // thread we're waiting for terminated
537 break;
538
539 case WAIT_OBJECT_0 + 1:
540 // new message arrived, process it
541 if ( !wxTheApp->DoMessage() )
542 {
543 // WM_QUIT received: kill the thread
544 Kill();
545
546 return (ExitCode)-1;
547 }
548
549 if ( IsMain() )
550 {
551 // give the thread we're waiting for chance to exit
552 // from the GUI call it might have been in
553 if ( (s_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
554 {
555 wxMutexGuiLeave();
556 }
557 }
558
559 break;
560
561 default:
562 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
563 }
564 } while ( result != WAIT_OBJECT_0 );
565
566 if ( IsMain() )
567 {
568 s_waitingForThread = FALSE;
569
570 wxEndBusyCursor();
571 }
572
573 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
574 {
575 wxLogLastError("GetExitCodeThread");
576
577 rc = (ExitCode)-1;
578 }
579
580 wxASSERT_MSG( (LPVOID)rc != (LPVOID)STILL_ACTIVE,
581 wxT("thread must be already terminated.") );
582
583 ::CloseHandle(hThread);
584 }
585
586 return rc;
587}
588
589wxThreadError wxThread::Kill()
590{
591 if ( !IsRunning() )
592 return wxTHREAD_NOT_RUNNING;
593
594 if ( !::TerminateThread(p_internal->GetHandle(), (DWORD)-1) )
595 {
596 wxLogSysError(_("Couldn't terminate thread"));
597
598 return wxTHREAD_MISC_ERROR;
599 }
600
601 delete this;
602
603 return wxTHREAD_NO_ERROR;
604}
605
606void wxThread::Exit(void *status)
607{
608 delete this;
609
610 ::ExitThread((DWORD)status);
611
612 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
613}
614
615void wxThread::SetPriority(unsigned int prio)
616{
617 wxCriticalSectionLocker lock(m_critsect);
618
619 p_internal->SetPriority(prio);
620}
621
622unsigned int wxThread::GetPriority() const
623{
624 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
625
626 return p_internal->GetPriority();
627}
628
629unsigned long wxThread::GetID() const
630{
631 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
632
633 return (unsigned long)p_internal->GetId();
634}
635
636bool wxThread::IsRunning() const
637{
638 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
639
640 return p_internal->GetState() == STATE_RUNNING;
641}
642
643bool wxThread::IsAlive() const
644{
645 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
646
647 return (p_internal->GetState() == STATE_RUNNING) ||
648 (p_internal->GetState() == STATE_PAUSED);
649}
650
651bool wxThread::IsPaused() const
652{
653 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
654
655 return (p_internal->GetState() == STATE_PAUSED);
656}
657
658bool wxThread::TestDestroy()
659{
660 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
661
662 return p_internal->GetState() == STATE_CANCELED;
663}
664
665wxThread::wxThread()
666{
667 p_internal = new wxThreadInternal();
668}
669
670wxThread::~wxThread()
671{
672 delete p_internal;
673}
674
675// ----------------------------------------------------------------------------
676// Automatic initialization for thread module
677// ----------------------------------------------------------------------------
678
679class wxThreadModule : public wxModule
680{
681public:
682 virtual bool OnInit();
683 virtual void OnExit();
684
685private:
686 DECLARE_DYNAMIC_CLASS(wxThreadModule)
687};
688
689IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
690
691bool wxThreadModule::OnInit()
692{
693 // allocate TLS index for storing the pointer to the current thread
694 s_tlsThisThread = ::TlsAlloc();
695 if ( s_tlsThisThread == 0xFFFFFFFF )
696 {
697 // in normal circumstances it will only happen if all other
698 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
699 // words, this should never happen
700 wxLogSysError(_("Thread module initialization failed: "
701 "impossible to allocate index in thread "
702 "local storage"));
703
704 return FALSE;
705 }
706
707 // main thread doesn't have associated wxThread object, so store 0 in the
708 // TLS instead
709 if ( !::TlsSetValue(s_tlsThisThread, (LPVOID)0) )
710 {
711 ::TlsFree(s_tlsThisThread);
712 s_tlsThisThread = 0xFFFFFFFF;
713
714 wxLogSysError(_("Thread module initialization failed: "
715 "can not store value in thread local storage"));
716
717 return FALSE;
718 }
719
720 s_critsectWaitingForGui = new wxCriticalSection();
721
722 s_critsectGui = new wxCriticalSection();
723 s_critsectGui->Enter();
724
725 // no error return for GetCurrentThreadId()
726 s_idMainThread = ::GetCurrentThreadId();
727
728 return TRUE;
729}
730
731void wxThreadModule::OnExit()
732{
733 if ( !::TlsFree(s_tlsThisThread) )
734 {
735 wxLogLastError("TlsFree failed.");
736 }
737
738 if ( s_critsectGui )
739 {
740 s_critsectGui->Leave();
741 delete s_critsectGui;
742 s_critsectGui = NULL;
743 }
744
745 wxDELETE(s_critsectWaitingForGui);
746}
747
748// ----------------------------------------------------------------------------
749// under Windows, these functions are implemented usign a critical section and
750// not a mutex, so the names are a bit confusing
751// ----------------------------------------------------------------------------
752
753void WXDLLEXPORT wxMutexGuiEnter()
754{
755 // this would dead lock everything...
756 wxASSERT_MSG( !wxThread::IsMain(),
757 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
758
759 // the order in which we enter the critical sections here is crucial!!
760
761 // set the flag telling to the main thread that we want to do some GUI
762 {
763 wxCriticalSectionLocker enter(*s_critsectWaitingForGui);
764
765 s_nWaitingForGui++;
766 }
767
768 wxWakeUpMainThread();
769
770 // now we may block here because the main thread will soon let us in
771 // (during the next iteration of OnIdle())
772 s_critsectGui->Enter();
773}
774
775void WXDLLEXPORT wxMutexGuiLeave()
776{
777 wxCriticalSectionLocker enter(*s_critsectWaitingForGui);
778
779 if ( wxThread::IsMain() )
780 {
781 s_bGuiOwnedByMainThread = FALSE;
782 }
783 else
784 {
785 // decrement the number of waiters now
786 wxASSERT_MSG( s_nWaitingForGui > 0,
787 wxT("calling wxMutexGuiLeave() without entering it first?") );
788
789 s_nWaitingForGui--;
790
791 wxWakeUpMainThread();
792 }
793
794 s_critsectGui->Leave();
795}
796
797void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
798{
799 wxASSERT_MSG( wxThread::IsMain(),
800 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
801
802 wxCriticalSectionLocker enter(*s_critsectWaitingForGui);
803
804 if ( s_nWaitingForGui == 0 )
805 {
806 // no threads are waiting for GUI - so we may acquire the lock without
807 // any danger (but only if we don't already have it)
808 if ( !wxGuiOwnedByMainThread() )
809 {
810 s_critsectGui->Enter();
811
812 s_bGuiOwnedByMainThread = TRUE;
813 }
814 //else: already have it, nothing to do
815 }
816 else
817 {
818 // some threads are waiting, release the GUI lock if we have it
819 if ( wxGuiOwnedByMainThread() )
820 {
821 wxMutexGuiLeave();
822 }
823 //else: some other worker thread is doing GUI
824 }
825}
826
827bool WXDLLEXPORT wxGuiOwnedByMainThread()
828{
829 return s_bGuiOwnedByMainThread;
830}
831
832// wake up the main thread if it's in ::GetMessage()
833void WXDLLEXPORT wxWakeUpMainThread()
834{
835 // sending any message would do - hopefully WM_NULL is harmless enough
836 if ( !::PostThreadMessage(s_idMainThread, WM_NULL, 0, 0) )
837 {
838 // should never happen
839 wxLogLastError("PostThreadMessage(WM_NULL)");
840 }
841}
842
843bool WXDLLEXPORT wxIsWaitingForThread()
844{
845 return s_waitingForThread;
846}
847
848#endif // wxUSE_THREADS