]> git.saurik.com Git - wxWidgets.git/blob - src/msw/thread.cpp
472d1916e3d72ca31c6fd3dbdcb9578e78d03b6f
[wxWidgets.git] / src / msw / thread.cpp
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 // must have this symbol defined to get _beginthread/_endthread declarations
40 #ifndef _MT
41 #define _MT
42 #endif
43
44 #ifdef __VISUALC__
45 #include <process.h>
46 #endif
47
48 // ----------------------------------------------------------------------------
49 // constants
50 // ----------------------------------------------------------------------------
51
52 // the possible states of the thread ("=>" shows all possible transitions from
53 // this state)
54 enum wxThreadState
55 {
56 STATE_NEW, // didn't start execution yet (=> RUNNING)
57 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
58 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
59 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
60 STATE_EXITED // thread is terminating
61 };
62
63 // ----------------------------------------------------------------------------
64 // this module globals
65 // ----------------------------------------------------------------------------
66
67 // TLS index of the slot where we store the pointer to the current thread
68 static DWORD gs_tlsThisThread = 0xFFFFFFFF;
69
70 // id of the main thread - the one which can call GUI functions without first
71 // calling wxMutexGuiEnter()
72 static DWORD gs_idMainThread = 0;
73
74 // if it's FALSE, some secondary thread is holding the GUI lock
75 static bool gs_bGuiOwnedByMainThread = TRUE;
76
77 // critical section which controls access to all GUI functions: any secondary
78 // thread (i.e. except the main one) must enter this crit section before doing
79 // any GUI calls
80 static wxCriticalSection *gs_critsectGui = NULL;
81
82 // critical section which protects gs_nWaitingForGui variable
83 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
84
85 // number of threads waiting for GUI in wxMutexGuiEnter()
86 static size_t gs_nWaitingForGui = 0;
87
88 // are we waiting for a thread termination?
89 static bool gs_waitingForThread = FALSE;
90
91 // ============================================================================
92 // Windows implementation of thread classes
93 // ============================================================================
94
95 // ----------------------------------------------------------------------------
96 // wxMutex implementation
97 // ----------------------------------------------------------------------------
98
99 class wxMutexInternal
100 {
101 public:
102 HANDLE p_mutex;
103 };
104
105 wxMutex::wxMutex()
106 {
107 m_internal = new wxMutexInternal;
108 m_internal->p_mutex = CreateMutex(NULL, FALSE, NULL);
109 if ( !m_internal->p_mutex )
110 {
111 wxLogSysError(_("Can not create mutex."));
112 }
113
114 m_locked = 0;
115 }
116
117 wxMutex::~wxMutex()
118 {
119 if (m_locked > 0)
120 wxLogDebug(wxT("Warning: freeing a locked mutex (%d locks)."), m_locked);
121 CloseHandle(m_internal->p_mutex);
122 }
123
124 wxMutexError wxMutex::Lock()
125 {
126 DWORD ret;
127
128 ret = WaitForSingleObject(m_internal->p_mutex, INFINITE);
129 switch ( ret )
130 {
131 case WAIT_ABANDONED:
132 return wxMUTEX_BUSY;
133
134 case WAIT_OBJECT_0:
135 // ok
136 break;
137
138 case WAIT_FAILED:
139 wxLogSysError(_("Couldn't acquire a mutex lock"));
140 return wxMUTEX_MISC_ERROR;
141
142 case WAIT_TIMEOUT:
143 default:
144 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
145 }
146
147 m_locked++;
148 return wxMUTEX_NO_ERROR;
149 }
150
151 wxMutexError wxMutex::TryLock()
152 {
153 DWORD ret;
154
155 ret = WaitForSingleObject(m_internal->p_mutex, 0);
156 if (ret == WAIT_TIMEOUT || ret == WAIT_ABANDONED)
157 return wxMUTEX_BUSY;
158
159 m_locked++;
160 return wxMUTEX_NO_ERROR;
161 }
162
163 wxMutexError wxMutex::Unlock()
164 {
165 if (m_locked > 0)
166 m_locked--;
167
168 BOOL ret = ReleaseMutex(m_internal->p_mutex);
169 if ( ret == 0 )
170 {
171 wxLogSysError(_("Couldn't release a mutex"));
172 return wxMUTEX_MISC_ERROR;
173 }
174
175 return wxMUTEX_NO_ERROR;
176 }
177
178 // ----------------------------------------------------------------------------
179 // wxCondition implementation
180 // ----------------------------------------------------------------------------
181
182 class wxConditionInternal
183 {
184 public:
185 wxConditionInternal()
186 {
187 event = ::CreateEvent(
188 NULL, // default secutiry
189 FALSE, // not manual reset
190 FALSE, // nonsignaled initially
191 NULL // nameless event
192 );
193 if ( !event )
194 {
195 wxLogSysError(_("Can not create event object."));
196 }
197 waiters = 0;
198 }
199
200 bool Wait(DWORD timeout)
201 {
202 waiters++;
203
204 // FIXME this should be MsgWaitForMultipleObjects() as well probably
205 DWORD rc = ::WaitForSingleObject(event, timeout);
206
207 waiters--;
208
209 return rc != WAIT_TIMEOUT;
210 }
211
212 ~wxConditionInternal()
213 {
214 if ( event )
215 {
216 if ( !::CloseHandle(event) )
217 {
218 wxLogLastError("CloseHandle(event)");
219 }
220 }
221 }
222
223 HANDLE event;
224 int waiters;
225 };
226
227 wxCondition::wxCondition()
228 {
229 m_internal = new wxConditionInternal;
230 }
231
232 wxCondition::~wxCondition()
233 {
234 delete m_internal;
235 }
236
237 void wxCondition::Wait()
238 {
239 (void)m_internal->Wait(INFINITE);
240 }
241
242 bool wxCondition::Wait(unsigned long sec,
243 unsigned long nsec)
244 {
245 return m_internal->Wait(sec*1000 + nsec/1000000);
246 }
247
248 void wxCondition::Signal()
249 {
250 // set the event to signaled: if a thread is already waiting on it, it will
251 // be woken up, otherwise the event will remain in the signaled state until
252 // someone waits on it. In any case, the system will return it to a non
253 // signalled state afterwards. If multiple threads are waiting, only one
254 // will be woken up.
255 if ( !::SetEvent(m_internal->event) )
256 {
257 wxLogLastError("SetEvent");
258 }
259 }
260
261 void wxCondition::Broadcast()
262 {
263 // this works because all these threads are already waiting and so each
264 // SetEvent() inside Signal() is really a PulseEvent() because the event
265 // state is immediately returned to non-signaled
266 for ( int i = 0; i < m_internal->waiters; i++ )
267 {
268 Signal();
269 }
270 }
271
272 // ----------------------------------------------------------------------------
273 // wxCriticalSection implementation
274 // ----------------------------------------------------------------------------
275
276 wxCriticalSection::wxCriticalSection()
277 {
278 wxASSERT_MSG( sizeof(CRITICAL_SECTION) <= sizeof(m_buffer),
279 _T("must increase buffer size in wx/thread.h") );
280
281 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
282 }
283
284 wxCriticalSection::~wxCriticalSection()
285 {
286 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
287 }
288
289 void wxCriticalSection::Enter()
290 {
291 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
292 }
293
294 void wxCriticalSection::Leave()
295 {
296 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
297 }
298
299 // ----------------------------------------------------------------------------
300 // wxThread implementation
301 // ----------------------------------------------------------------------------
302
303 // wxThreadInternal class
304 // ----------------------
305
306 class wxThreadInternal
307 {
308 public:
309 wxThreadInternal()
310 {
311 m_hThread = 0;
312 m_state = STATE_NEW;
313 m_priority = WXTHREAD_DEFAULT_PRIORITY;
314 }
315
316 ~wxThreadInternal()
317 {
318 Free();
319 }
320
321 void Free()
322 {
323 if ( m_hThread )
324 {
325 if ( !::CloseHandle(m_hThread) )
326 {
327 wxLogLastError("CloseHandle(thread)");
328 }
329
330 m_hThread = 0;
331 }
332 }
333
334 // create a new (suspended) thread (for the given thread object)
335 bool Create(wxThread *thread);
336
337 // suspend/resume/terminate
338 bool Suspend();
339 bool Resume();
340 void Cancel() { m_state = STATE_CANCELED; }
341
342 // thread state
343 void SetState(wxThreadState state) { m_state = state; }
344 wxThreadState GetState() const { return m_state; }
345
346 // thread priority
347 void SetPriority(unsigned int priority);
348 unsigned int GetPriority() const { return m_priority; }
349
350 // thread handle and id
351 HANDLE GetHandle() const { return m_hThread; }
352 DWORD GetId() const { return m_tid; }
353
354 // thread function
355 static DWORD WinThreadStart(wxThread *thread);
356
357 private:
358 HANDLE m_hThread; // handle of the thread
359 wxThreadState m_state; // state, see wxThreadState enum
360 unsigned int m_priority; // thread priority in "wx" units
361 DWORD m_tid; // thread id
362 };
363
364 DWORD wxThreadInternal::WinThreadStart(wxThread *thread)
365 {
366 // first of all, check whether we hadn't been cancelled already
367 if ( thread->m_internal->GetState() == STATE_EXITED )
368 {
369 return (DWORD)-1;
370 }
371
372 // store the thread object in the TLS
373 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
374 {
375 wxLogSysError(_("Can not start thread: error writing TLS."));
376
377 return (DWORD)-1;
378 }
379
380 DWORD rc = (DWORD)thread->Entry();
381
382 // enter m_critsect before changing the thread state
383 thread->m_critsect.Enter();
384 bool wasCancelled = thread->m_internal->GetState() == STATE_CANCELED;
385 thread->m_internal->SetState(STATE_EXITED);
386 thread->m_critsect.Leave();
387
388 thread->OnExit();
389
390 // if the thread was cancelled (from Delete()), then it the handle is still
391 // needed there
392 if ( thread->IsDetached() && !wasCancelled )
393 {
394 // auto delete
395 delete thread;
396 }
397 //else: the joinable threads handle will be closed when Wait() is done
398
399 return rc;
400 }
401
402 void wxThreadInternal::SetPriority(unsigned int priority)
403 {
404 m_priority = priority;
405
406 // translate wxWindows priority to the Windows one
407 int win_priority;
408 if (m_priority <= 20)
409 win_priority = THREAD_PRIORITY_LOWEST;
410 else if (m_priority <= 40)
411 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
412 else if (m_priority <= 60)
413 win_priority = THREAD_PRIORITY_NORMAL;
414 else if (m_priority <= 80)
415 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
416 else if (m_priority <= 100)
417 win_priority = THREAD_PRIORITY_HIGHEST;
418 else
419 {
420 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
421 win_priority = THREAD_PRIORITY_NORMAL;
422 }
423
424 if ( !::SetThreadPriority(m_hThread, win_priority) )
425 {
426 wxLogSysError(_("Can't set thread priority"));
427 }
428 }
429
430 bool wxThreadInternal::Create(wxThread *thread)
431 {
432 // for compilers which have it, we should use C RTL function for thread
433 // creation instead of Win32 API one because otherwise we will have memory
434 // leaks if the thread uses C RTL (and most threads do)
435 #ifdef __VISUALC__
436 typedef unsigned (__stdcall *RtlThreadStart)(void *);
437
438 m_hThread = (HANDLE)_beginthreadex(NULL, 0,
439 (RtlThreadStart)
440 wxThreadInternal::WinThreadStart,
441 thread, CREATE_SUSPENDED,
442 (unsigned int *)&m_tid);
443 #else // !VC++
444 m_hThread = ::CreateThread
445 (
446 NULL, // default security
447 0, // default stack size
448 (LPTHREAD_START_ROUTINE) // thread entry point
449 wxThreadInternal::WinThreadStart, //
450 (LPVOID)thread, // parameter
451 CREATE_SUSPENDED, // flags
452 &m_tid // [out] thread id
453 );
454 #endif // VC++/!VC++
455
456 if ( m_hThread == NULL )
457 {
458 wxLogSysError(_("Can't create thread"));
459
460 return FALSE;
461 }
462
463 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
464 {
465 SetPriority(m_priority);
466 }
467
468 return TRUE;
469 }
470
471 bool wxThreadInternal::Suspend()
472 {
473 DWORD nSuspendCount = ::SuspendThread(m_hThread);
474 if ( nSuspendCount == (DWORD)-1 )
475 {
476 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
477
478 return FALSE;
479 }
480
481 m_state = STATE_PAUSED;
482
483 return TRUE;
484 }
485
486 bool wxThreadInternal::Resume()
487 {
488 DWORD nSuspendCount = ::ResumeThread(m_hThread);
489 if ( nSuspendCount == (DWORD)-1 )
490 {
491 wxLogSysError(_("Can not resume thread %x"), m_hThread);
492
493 return FALSE;
494 }
495
496 m_state = STATE_RUNNING;
497
498 return TRUE;
499 }
500
501 // static functions
502 // ----------------
503
504 wxThread *wxThread::This()
505 {
506 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
507
508 // be careful, 0 may be a valid return value as well
509 if ( !thread && (::GetLastError() != NO_ERROR) )
510 {
511 wxLogSysError(_("Couldn't get the current thread pointer"));
512
513 // return NULL...
514 }
515
516 return thread;
517 }
518
519 bool wxThread::IsMain()
520 {
521 return ::GetCurrentThreadId() == gs_idMainThread;
522 }
523
524 #ifdef Yield
525 #undef Yield
526 #endif
527
528 void wxThread::Yield()
529 {
530 // 0 argument to Sleep() is special and means to just give away the rest of
531 // our timeslice
532 ::Sleep(0);
533 }
534
535 void wxThread::Sleep(unsigned long milliseconds)
536 {
537 ::Sleep(milliseconds);
538 }
539
540 int wxThread::GetCPUCount()
541 {
542 SYSTEM_INFO si;
543 GetSystemInfo(&si);
544
545 return si.dwNumberOfProcessors;
546 }
547
548 bool wxThread::SetConcurrency(size_t level)
549 {
550 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
551
552 // ok only for the default one
553 if ( level == 0 )
554 return 0;
555
556 // get system affinity mask first
557 HANDLE hProcess = ::GetCurrentProcess();
558 DWORD dwProcMask, dwSysMask;
559 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
560 {
561 wxLogLastError(_T("GetProcessAffinityMask"));
562
563 return FALSE;
564 }
565
566 // how many CPUs have we got?
567 if ( dwSysMask == 1 )
568 {
569 // don't bother with all this complicated stuff - on a single
570 // processor system it doesn't make much sense anyhow
571 return level == 1;
572 }
573
574 // calculate the process mask: it's a bit vector with one bit per
575 // processor; we want to schedule the process to run on first level
576 // CPUs
577 DWORD bit = 1;
578 while ( bit )
579 {
580 if ( dwSysMask & bit )
581 {
582 // ok, we can set this bit
583 dwProcMask |= bit;
584
585 // another process added
586 if ( !--level )
587 {
588 // and that's enough
589 break;
590 }
591 }
592
593 // next bit
594 bit <<= 1;
595 }
596
597 // could we set all bits?
598 if ( level != 0 )
599 {
600 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level);
601
602 return FALSE;
603 }
604
605 // set it: we can't link to SetProcessAffinityMask() because it doesn't
606 // exist in Win9x, use RT binding instead
607
608 typedef BOOL (*SETPROCESSAFFINITYMASK)(HANDLE, DWORD);
609
610 // can use static var because we're always in the main thread here
611 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
612
613 if ( !pfnSetProcessAffinityMask )
614 {
615 HMODULE hModKernel = ::LoadLibrary(_T("kernel32"));
616 if ( hModKernel )
617 {
618 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
619 ::GetProcAddress(hModKernel, _T("SetProcessAffinityMask"));
620 }
621
622 // we've discovered a MT version of Win9x!
623 wxASSERT_MSG( pfnSetProcessAffinityMask,
624 _T("this system has several CPUs but no "
625 "SetProcessAffinityMask function?") );
626 }
627
628 if ( !pfnSetProcessAffinityMask )
629 {
630 // msg given above - do it only once
631 return FALSE;
632 }
633
634 if ( pfnSetProcessAffinityMask(hProcess, dwProcMask) == 0 )
635 {
636 wxLogLastError(_T("SetProcessAffinityMask"));
637
638 return FALSE;
639 }
640
641 return TRUE;
642 }
643
644 // ctor and dtor
645 // -------------
646
647 wxThread::wxThread(wxThreadKind kind)
648 {
649 m_internal = new wxThreadInternal();
650
651 m_isDetached = kind == wxTHREAD_DETACHED;
652 }
653
654 wxThread::~wxThread()
655 {
656 delete m_internal;
657 }
658
659 // create/start thread
660 // -------------------
661
662 wxThreadError wxThread::Create()
663 {
664 wxCriticalSectionLocker lock(m_critsect);
665
666 if ( !m_internal->Create(this) )
667 return wxTHREAD_NO_RESOURCE;
668
669 return wxTHREAD_NO_ERROR;
670 }
671
672 wxThreadError wxThread::Run()
673 {
674 wxCriticalSectionLocker lock(m_critsect);
675
676 if ( m_internal->GetState() != STATE_NEW )
677 {
678 // actually, it may be almost any state at all, not only STATE_RUNNING
679 return wxTHREAD_RUNNING;
680 }
681
682 // the thread has just been created and is still suspended - let it run
683 return Resume();
684 }
685
686 // suspend/resume thread
687 // ---------------------
688
689 wxThreadError wxThread::Pause()
690 {
691 wxCriticalSectionLocker lock(m_critsect);
692
693 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
694 }
695
696 wxThreadError wxThread::Resume()
697 {
698 wxCriticalSectionLocker lock(m_critsect);
699
700 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
701 }
702
703 // stopping thread
704 // ---------------
705
706 wxThread::ExitCode wxThread::Wait()
707 {
708 // although under Windows we can wait for any thread, it's an error to
709 // wait for a detached one in wxWin API
710 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
711 _T("can't wait for detached thread") );
712
713 ExitCode rc = (ExitCode)-1;
714
715 (void)Delete(&rc);
716
717 m_internal->Free();
718
719 return rc;
720 }
721
722 wxThreadError wxThread::Delete(ExitCode *pRc)
723 {
724 ExitCode rc = 0;
725
726 // Delete() is always safe to call, so consider all possible states
727
728 // has the thread started to run?
729 bool shouldResume = FALSE;
730
731 {
732 wxCriticalSectionLocker lock(m_critsect);
733
734 if ( m_internal->GetState() == STATE_NEW )
735 {
736 // WinThreadStart() will see it and terminate immediately
737 m_internal->SetState(STATE_EXITED);
738
739 shouldResume = TRUE;
740 }
741 }
742
743 // is the thread paused?
744 if ( shouldResume || IsPaused() )
745 Resume();
746
747 HANDLE hThread = m_internal->GetHandle();
748
749 // does is still run?
750 if ( IsRunning() )
751 {
752 if ( IsMain() )
753 {
754 // set flag for wxIsWaitingForThread()
755 gs_waitingForThread = TRUE;
756
757 #if wxUSE_GUI
758 wxBeginBusyCursor();
759 #endif // wxUSE_GUI
760 }
761
762 // ask the thread to terminate
763 {
764 wxCriticalSectionLocker lock(m_critsect);
765
766 m_internal->Cancel();
767 }
768
769 #if wxUSE_GUI
770 // we can't just wait for the thread to terminate because it might be
771 // calling some GUI functions and so it will never terminate before we
772 // process the Windows messages that result from these functions
773 DWORD result;
774 do
775 {
776 result = ::MsgWaitForMultipleObjects
777 (
778 1, // number of objects to wait for
779 &hThread, // the objects
780 FALSE, // don't wait for all objects
781 INFINITE, // no timeout
782 QS_ALLEVENTS // return as soon as there are any events
783 );
784
785 switch ( result )
786 {
787 case 0xFFFFFFFF:
788 // error
789 wxLogSysError(_("Can not wait for thread termination"));
790 Kill();
791 return wxTHREAD_KILLED;
792
793 case WAIT_OBJECT_0:
794 // thread we're waiting for terminated
795 break;
796
797 case WAIT_OBJECT_0 + 1:
798 // new message arrived, process it
799 if ( !wxTheApp->DoMessage() )
800 {
801 // WM_QUIT received: kill the thread
802 Kill();
803
804 return wxTHREAD_KILLED;
805 }
806
807 if ( IsMain() )
808 {
809 // give the thread we're waiting for chance to exit
810 // from the GUI call it might have been in
811 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
812 {
813 wxMutexGuiLeave();
814 }
815 }
816
817 break;
818
819 default:
820 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
821 }
822 } while ( result != WAIT_OBJECT_0 );
823 #else // !wxUSE_GUI
824 // simply wait for the thread to terminate
825 //
826 // OTOH, even console apps create windows (in wxExecute, for WinSock
827 // &c), so may be use MsgWaitForMultipleObject() too here?
828 if ( WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0 )
829 {
830 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
831 }
832 #endif // wxUSE_GUI/!wxUSE_GUI
833
834 if ( IsMain() )
835 {
836 gs_waitingForThread = FALSE;
837
838 #if wxUSE_GUI
839 wxEndBusyCursor();
840 #endif // wxUSE_GUI
841 }
842 }
843
844 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
845 {
846 wxLogLastError("GetExitCodeThread");
847
848 rc = (ExitCode)-1;
849 }
850
851 if ( IsDetached() )
852 {
853 // if the thread exits normally, this is done in WinThreadStart, but in
854 // this case it would have been too early because
855 // MsgWaitForMultipleObject() would fail if the therad handle was
856 // closed while we were waiting on it, so we must do it here
857 delete this;
858 }
859
860 wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
861 wxT("thread must be already terminated.") );
862
863 if ( pRc )
864 *pRc = rc;
865
866 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
867 }
868
869 wxThreadError wxThread::Kill()
870 {
871 if ( !IsRunning() )
872 return wxTHREAD_NOT_RUNNING;
873
874 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
875 {
876 wxLogSysError(_("Couldn't terminate thread"));
877
878 return wxTHREAD_MISC_ERROR;
879 }
880
881 m_internal->Free();
882
883 if ( IsDetached() )
884 {
885 delete this;
886 }
887
888 return wxTHREAD_NO_ERROR;
889 }
890
891 void wxThread::Exit(ExitCode status)
892 {
893 m_internal->Free();
894
895 if ( IsDetached() )
896 {
897 delete this;
898 }
899
900 #ifdef __VISUALC__
901 _endthreadex((unsigned)status);
902 #else // !VC++
903 ::ExitThread((DWORD)status);
904 #endif // VC++/!VC++
905
906 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
907 }
908
909 // priority setting
910 // ----------------
911
912 void wxThread::SetPriority(unsigned int prio)
913 {
914 wxCriticalSectionLocker lock(m_critsect);
915
916 m_internal->SetPriority(prio);
917 }
918
919 unsigned int wxThread::GetPriority() const
920 {
921 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
922
923 return m_internal->GetPriority();
924 }
925
926 unsigned long wxThread::GetId() const
927 {
928 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
929
930 return (unsigned long)m_internal->GetId();
931 }
932
933 bool wxThread::IsRunning() const
934 {
935 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
936
937 return m_internal->GetState() == STATE_RUNNING;
938 }
939
940 bool wxThread::IsAlive() const
941 {
942 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
943
944 return (m_internal->GetState() == STATE_RUNNING) ||
945 (m_internal->GetState() == STATE_PAUSED);
946 }
947
948 bool wxThread::IsPaused() const
949 {
950 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
951
952 return m_internal->GetState() == STATE_PAUSED;
953 }
954
955 bool wxThread::TestDestroy()
956 {
957 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
958
959 return m_internal->GetState() == STATE_CANCELED;
960 }
961
962 // ----------------------------------------------------------------------------
963 // Automatic initialization for thread module
964 // ----------------------------------------------------------------------------
965
966 class wxThreadModule : public wxModule
967 {
968 public:
969 virtual bool OnInit();
970 virtual void OnExit();
971
972 private:
973 DECLARE_DYNAMIC_CLASS(wxThreadModule)
974 };
975
976 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
977
978 bool wxThreadModule::OnInit()
979 {
980 // allocate TLS index for storing the pointer to the current thread
981 gs_tlsThisThread = ::TlsAlloc();
982 if ( gs_tlsThisThread == 0xFFFFFFFF )
983 {
984 // in normal circumstances it will only happen if all other
985 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
986 // words, this should never happen
987 wxLogSysError(_("Thread module initialization failed: "
988 "impossible to allocate index in thread "
989 "local storage"));
990
991 return FALSE;
992 }
993
994 // main thread doesn't have associated wxThread object, so store 0 in the
995 // TLS instead
996 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
997 {
998 ::TlsFree(gs_tlsThisThread);
999 gs_tlsThisThread = 0xFFFFFFFF;
1000
1001 wxLogSysError(_("Thread module initialization failed: "
1002 "can not store value in thread local storage"));
1003
1004 return FALSE;
1005 }
1006
1007 gs_critsectWaitingForGui = new wxCriticalSection();
1008
1009 gs_critsectGui = new wxCriticalSection();
1010 gs_critsectGui->Enter();
1011
1012 // no error return for GetCurrentThreadId()
1013 gs_idMainThread = ::GetCurrentThreadId();
1014
1015 return TRUE;
1016 }
1017
1018 void wxThreadModule::OnExit()
1019 {
1020 if ( !::TlsFree(gs_tlsThisThread) )
1021 {
1022 wxLogLastError("TlsFree failed.");
1023 }
1024
1025 if ( gs_critsectGui )
1026 {
1027 gs_critsectGui->Leave();
1028 delete gs_critsectGui;
1029 gs_critsectGui = NULL;
1030 }
1031
1032 delete gs_critsectWaitingForGui;
1033 gs_critsectWaitingForGui = NULL;
1034 }
1035
1036 // ----------------------------------------------------------------------------
1037 // under Windows, these functions are implemented using a critical section and
1038 // not a mutex, so the names are a bit confusing
1039 // ----------------------------------------------------------------------------
1040
1041 void WXDLLEXPORT wxMutexGuiEnter()
1042 {
1043 // this would dead lock everything...
1044 wxASSERT_MSG( !wxThread::IsMain(),
1045 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1046
1047 // the order in which we enter the critical sections here is crucial!!
1048
1049 // set the flag telling to the main thread that we want to do some GUI
1050 {
1051 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1052
1053 gs_nWaitingForGui++;
1054 }
1055
1056 wxWakeUpMainThread();
1057
1058 // now we may block here because the main thread will soon let us in
1059 // (during the next iteration of OnIdle())
1060 gs_critsectGui->Enter();
1061 }
1062
1063 void WXDLLEXPORT wxMutexGuiLeave()
1064 {
1065 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1066
1067 if ( wxThread::IsMain() )
1068 {
1069 gs_bGuiOwnedByMainThread = FALSE;
1070 }
1071 else
1072 {
1073 // decrement the number of waiters now
1074 wxASSERT_MSG( gs_nWaitingForGui > 0,
1075 wxT("calling wxMutexGuiLeave() without entering it first?") );
1076
1077 gs_nWaitingForGui--;
1078
1079 wxWakeUpMainThread();
1080 }
1081
1082 gs_critsectGui->Leave();
1083 }
1084
1085 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1086 {
1087 wxASSERT_MSG( wxThread::IsMain(),
1088 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1089
1090 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1091
1092 if ( gs_nWaitingForGui == 0 )
1093 {
1094 // no threads are waiting for GUI - so we may acquire the lock without
1095 // any danger (but only if we don't already have it)
1096 if ( !wxGuiOwnedByMainThread() )
1097 {
1098 gs_critsectGui->Enter();
1099
1100 gs_bGuiOwnedByMainThread = TRUE;
1101 }
1102 //else: already have it, nothing to do
1103 }
1104 else
1105 {
1106 // some threads are waiting, release the GUI lock if we have it
1107 if ( wxGuiOwnedByMainThread() )
1108 {
1109 wxMutexGuiLeave();
1110 }
1111 //else: some other worker thread is doing GUI
1112 }
1113 }
1114
1115 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1116 {
1117 return gs_bGuiOwnedByMainThread;
1118 }
1119
1120 // wake up the main thread if it's in ::GetMessage()
1121 void WXDLLEXPORT wxWakeUpMainThread()
1122 {
1123 // sending any message would do - hopefully WM_NULL is harmless enough
1124 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
1125 {
1126 // should never happen
1127 wxLogLastError("PostThreadMessage(WM_NULL)");
1128 }
1129 }
1130
1131 bool WXDLLEXPORT wxIsWaitingForThread()
1132 {
1133 return gs_waitingForThread;
1134 }
1135
1136 #endif // wxUSE_THREADS