]> git.saurik.com Git - wxWidgets.git/blob - src/msw/thread.cpp
df5e9a437f2ae0de74d3185acb2b10db8e0c730a
[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 // store the thread object in the TLS
367 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
368 {
369 wxLogSysError(_("Can not start thread: error writing TLS."));
370
371 return (DWORD)-1;
372 }
373
374 DWORD rc = (DWORD)thread->Entry();
375
376 // enter m_critsect before changing the thread state
377 thread->m_critsect.Enter();
378 bool wasCancelled = thread->m_internal->GetState() == STATE_CANCELED;
379 thread->m_internal->SetState(STATE_EXITED);
380 thread->m_critsect.Leave();
381
382 thread->OnExit();
383
384 // if the thread was cancelled (from Delete()), then it the handle is still
385 // needed there
386 if ( thread->IsDetached() && !wasCancelled )
387 {
388 // auto delete
389 delete thread;
390 }
391 //else: the joinable threads handle will be closed when Wait() is done
392
393 return rc;
394 }
395
396 void wxThreadInternal::SetPriority(unsigned int priority)
397 {
398 m_priority = priority;
399
400 // translate wxWindows priority to the Windows one
401 int win_priority;
402 if (m_priority <= 20)
403 win_priority = THREAD_PRIORITY_LOWEST;
404 else if (m_priority <= 40)
405 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
406 else if (m_priority <= 60)
407 win_priority = THREAD_PRIORITY_NORMAL;
408 else if (m_priority <= 80)
409 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
410 else if (m_priority <= 100)
411 win_priority = THREAD_PRIORITY_HIGHEST;
412 else
413 {
414 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
415 win_priority = THREAD_PRIORITY_NORMAL;
416 }
417
418 if ( !::SetThreadPriority(m_hThread, win_priority) )
419 {
420 wxLogSysError(_("Can't set thread priority"));
421 }
422 }
423
424 bool wxThreadInternal::Create(wxThread *thread)
425 {
426 // for compilers which have it, we should use C RTL function for thread
427 // creation instead of Win32 API one because otherwise we will have memory
428 // leaks if the thread uses C RTL (and most threads do)
429 #ifdef __VISUALC__
430 typedef unsigned (__stdcall *RtlThreadStart)(void *);
431
432 m_hThread = (HANDLE)_beginthreadex(NULL, 0,
433 (RtlThreadStart)
434 wxThreadInternal::WinThreadStart,
435 thread, CREATE_SUSPENDED,
436 (unsigned int *)&m_tid);
437 #else // !VC++
438 m_hThread = ::CreateThread
439 (
440 NULL, // default security
441 0, // default stack size
442 (LPTHREAD_START_ROUTINE) // thread entry point
443 wxThreadInternal::WinThreadStart, //
444 (LPVOID)thread, // parameter
445 CREATE_SUSPENDED, // flags
446 &m_tid // [out] thread id
447 );
448 #endif // VC++/!VC++
449
450 if ( m_hThread == NULL )
451 {
452 wxLogSysError(_("Can't create thread"));
453
454 return FALSE;
455 }
456
457 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
458 {
459 SetPriority(m_priority);
460 }
461
462 return TRUE;
463 }
464
465 bool wxThreadInternal::Suspend()
466 {
467 DWORD nSuspendCount = ::SuspendThread(m_hThread);
468 if ( nSuspendCount == (DWORD)-1 )
469 {
470 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
471
472 return FALSE;
473 }
474
475 m_state = STATE_PAUSED;
476
477 return TRUE;
478 }
479
480 bool wxThreadInternal::Resume()
481 {
482 DWORD nSuspendCount = ::ResumeThread(m_hThread);
483 if ( nSuspendCount == (DWORD)-1 )
484 {
485 wxLogSysError(_("Can not resume thread %x"), m_hThread);
486
487 return FALSE;
488 }
489
490 m_state = STATE_RUNNING;
491
492 return TRUE;
493 }
494
495 // static functions
496 // ----------------
497
498 wxThread *wxThread::This()
499 {
500 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
501
502 // be careful, 0 may be a valid return value as well
503 if ( !thread && (::GetLastError() != NO_ERROR) )
504 {
505 wxLogSysError(_("Couldn't get the current thread pointer"));
506
507 // return NULL...
508 }
509
510 return thread;
511 }
512
513 bool wxThread::IsMain()
514 {
515 return ::GetCurrentThreadId() == gs_idMainThread;
516 }
517
518 void wxThread::Yield()
519 {
520 // 0 argument to Sleep() is special and means to just give away the rest of
521 // our timeslice
522 ::Sleep(0);
523 }
524
525 void wxThread::Sleep(unsigned long milliseconds)
526 {
527 ::Sleep(milliseconds);
528 }
529
530 int wxThread::GetCPUCount()
531 {
532 SYSTEM_INFO si;
533 GetSystemInfo(&si);
534
535 return si.dwNumberOfProcessors;
536 }
537
538 bool wxThread::SetConcurrency(size_t level)
539 {
540 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
541
542 // ok only for the default one
543 if ( level == 0 )
544 return 0;
545
546 // get system affinity mask first
547 HANDLE hProcess = ::GetCurrentProcess();
548 DWORD dwProcMask, dwSysMask;
549 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
550 {
551 wxLogLastError(_T("GetProcessAffinityMask"));
552
553 return FALSE;
554 }
555
556 // how many CPUs have we got?
557 if ( dwSysMask == 1 )
558 {
559 // don't bother with all this complicated stuff - on a single
560 // processor system it doesn't make much sense anyhow
561 return level == 1;
562 }
563
564 // calculate the process mask: it's a bit vector with one bit per
565 // processor; we want to schedule the process to run on first level
566 // CPUs
567 DWORD bit = 1;
568 while ( bit )
569 {
570 if ( dwSysMask & bit )
571 {
572 // ok, we can set this bit
573 dwProcMask |= bit;
574
575 // another process added
576 if ( !--level )
577 {
578 // and that's enough
579 break;
580 }
581 }
582
583 // next bit
584 bit <<= 1;
585 }
586
587 // could we set all bits?
588 if ( level != 0 )
589 {
590 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level);
591
592 return FALSE;
593 }
594
595 // set it: we can't link to SetProcessAffinityMask() because it doesn't
596 // exist in Win9x, use RT binding instead
597
598 typedef BOOL (*SETPROCESSAFFINITYMASK)(HANDLE, DWORD *);
599
600 // can use static var because we're always in the main thread here
601 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
602
603 if ( !pfnSetProcessAffinityMask )
604 {
605 HMODULE hModKernel = ::LoadLibrary(_T("kernel32"));
606 if ( hModKernel )
607 {
608 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
609 ::GetProcAddress(hModKernel, _T("SetProcessAffinityMask"));
610 }
611
612 // we've discovered a MT version of Win9x!
613 wxASSERT_MSG( pfnSetProcessAffinityMask,
614 _T("this system has several CPUs but no "
615 "SetProcessAffinityMask function?") );
616 }
617
618 if ( !pfnSetProcessAffinityMask )
619 {
620 // msg given above - do it only once
621 return FALSE;
622 }
623
624 if ( pfnSetProcessAffinityMask(hProcess, &dwProcMask) == 0 )
625 {
626 wxLogLastError(_T("SetProcessAffinityMask"));
627
628 return FALSE;
629 }
630
631 return TRUE;
632 }
633
634 // ctor and dtor
635 // -------------
636
637 wxThread::wxThread(wxThreadKind kind)
638 {
639 m_internal = new wxThreadInternal();
640
641 m_isDetached = kind == wxTHREAD_DETACHED;
642 }
643
644 wxThread::~wxThread()
645 {
646 delete m_internal;
647 }
648
649 // create/start thread
650 // -------------------
651
652 wxThreadError wxThread::Create()
653 {
654 wxCriticalSectionLocker lock(m_critsect);
655
656 if ( !m_internal->Create(this) )
657 return wxTHREAD_NO_RESOURCE;
658
659 return wxTHREAD_NO_ERROR;
660 }
661
662 wxThreadError wxThread::Run()
663 {
664 wxCriticalSectionLocker lock(m_critsect);
665
666 if ( m_internal->GetState() != STATE_NEW )
667 {
668 // actually, it may be almost any state at all, not only STATE_RUNNING
669 return wxTHREAD_RUNNING;
670 }
671
672 // the thread has just been created and is still suspended - let it run
673 return Resume();
674 }
675
676 // suspend/resume thread
677 // ---------------------
678
679 wxThreadError wxThread::Pause()
680 {
681 wxCriticalSectionLocker lock(m_critsect);
682
683 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
684 }
685
686 wxThreadError wxThread::Resume()
687 {
688 wxCriticalSectionLocker lock(m_critsect);
689
690 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
691 }
692
693 // stopping thread
694 // ---------------
695
696 wxThread::ExitCode wxThread::Wait()
697 {
698 // although under Windows we can wait for any thread, it's an error to
699 // wait for a detached one in wxWin API
700 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
701 _T("can't wait for detached thread") );
702
703 ExitCode rc = (ExitCode)-1;
704
705 (void)Delete(&rc);
706
707 m_internal->Free();
708
709 return rc;
710 }
711
712 wxThreadError wxThread::Delete(ExitCode *pRc)
713 {
714 ExitCode rc = 0;
715
716 // Delete() is always safe to call, so consider all possible states
717 if ( IsPaused() )
718 Resume();
719
720 HANDLE hThread = m_internal->GetHandle();
721
722 if ( IsRunning() )
723 {
724 if ( IsMain() )
725 {
726 // set flag for wxIsWaitingForThread()
727 gs_waitingForThread = TRUE;
728
729 #if wxUSE_GUI
730 wxBeginBusyCursor();
731 #endif // wxUSE_GUI
732 }
733
734 // ask the thread to terminate
735 {
736 wxCriticalSectionLocker lock(m_critsect);
737
738 m_internal->Cancel();
739 }
740
741 #if wxUSE_GUI
742 // we can't just wait for the thread to terminate because it might be
743 // calling some GUI functions and so it will never terminate before we
744 // process the Windows messages that result from these functions
745 DWORD result;
746 do
747 {
748 result = ::MsgWaitForMultipleObjects
749 (
750 1, // number of objects to wait for
751 &hThread, // the objects
752 FALSE, // don't wait for all objects
753 INFINITE, // no timeout
754 QS_ALLEVENTS // return as soon as there are any events
755 );
756
757 switch ( result )
758 {
759 case 0xFFFFFFFF:
760 // error
761 wxLogSysError(_("Can not wait for thread termination"));
762 Kill();
763 return wxTHREAD_KILLED;
764
765 case WAIT_OBJECT_0:
766 // thread we're waiting for terminated
767 break;
768
769 case WAIT_OBJECT_0 + 1:
770 // new message arrived, process it
771 if ( !wxTheApp->DoMessage() )
772 {
773 // WM_QUIT received: kill the thread
774 Kill();
775
776 return wxTHREAD_KILLED;
777 }
778
779 if ( IsMain() )
780 {
781 // give the thread we're waiting for chance to exit
782 // from the GUI call it might have been in
783 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
784 {
785 wxMutexGuiLeave();
786 }
787 }
788
789 break;
790
791 default:
792 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
793 }
794 } while ( result != WAIT_OBJECT_0 );
795 #else // !wxUSE_GUI
796 // simply wait for the thread to terminate
797 //
798 // OTOH, even console apps create windows (in wxExecute, for WinSock
799 // &c), so may be use MsgWaitForMultipleObject() too here?
800 if ( WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0 )
801 {
802 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
803 }
804 #endif // wxUSE_GUI/!wxUSE_GUI
805
806 if ( IsMain() )
807 {
808 gs_waitingForThread = FALSE;
809
810 #if wxUSE_GUI
811 wxEndBusyCursor();
812 #endif // wxUSE_GUI
813 }
814 }
815
816 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
817 {
818 wxLogLastError("GetExitCodeThread");
819
820 rc = (ExitCode)-1;
821 }
822
823 if ( IsDetached() )
824 {
825 // if the thread exits normally, this is done in WinThreadStart, but in
826 // this case it would have been too early because
827 // MsgWaitForMultipleObject() would fail if the therad handle was
828 // closed while we were waiting on it, so we must do it here
829 delete this;
830 }
831
832 wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
833 wxT("thread must be already terminated.") );
834
835 if ( pRc )
836 *pRc = rc;
837
838 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
839 }
840
841 wxThreadError wxThread::Kill()
842 {
843 if ( !IsRunning() )
844 return wxTHREAD_NOT_RUNNING;
845
846 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
847 {
848 wxLogSysError(_("Couldn't terminate thread"));
849
850 return wxTHREAD_MISC_ERROR;
851 }
852
853 m_internal->Free();
854
855 if ( IsDetached() )
856 {
857 delete this;
858 }
859
860 return wxTHREAD_NO_ERROR;
861 }
862
863 void wxThread::Exit(ExitCode status)
864 {
865 m_internal->Free();
866
867 if ( IsDetached() )
868 {
869 delete this;
870 }
871
872 #ifdef __VISUALC__
873 _endthreadex((unsigned)status);
874 #else // !VC++
875 ::ExitThread((DWORD)status);
876 #endif // VC++/!VC++
877
878 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
879 }
880
881 // priority setting
882 // ----------------
883
884 void wxThread::SetPriority(unsigned int prio)
885 {
886 wxCriticalSectionLocker lock(m_critsect);
887
888 m_internal->SetPriority(prio);
889 }
890
891 unsigned int wxThread::GetPriority() const
892 {
893 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
894
895 return m_internal->GetPriority();
896 }
897
898 unsigned long wxThread::GetId() const
899 {
900 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
901
902 return (unsigned long)m_internal->GetId();
903 }
904
905 bool wxThread::IsRunning() const
906 {
907 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
908
909 return m_internal->GetState() == STATE_RUNNING;
910 }
911
912 bool wxThread::IsAlive() const
913 {
914 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
915
916 return (m_internal->GetState() == STATE_RUNNING) ||
917 (m_internal->GetState() == STATE_PAUSED);
918 }
919
920 bool wxThread::IsPaused() const
921 {
922 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
923
924 return m_internal->GetState() == STATE_PAUSED;
925 }
926
927 bool wxThread::TestDestroy()
928 {
929 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
930
931 return m_internal->GetState() == STATE_CANCELED;
932 }
933
934 // ----------------------------------------------------------------------------
935 // Automatic initialization for thread module
936 // ----------------------------------------------------------------------------
937
938 class wxThreadModule : public wxModule
939 {
940 public:
941 virtual bool OnInit();
942 virtual void OnExit();
943
944 private:
945 DECLARE_DYNAMIC_CLASS(wxThreadModule)
946 };
947
948 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
949
950 bool wxThreadModule::OnInit()
951 {
952 // allocate TLS index for storing the pointer to the current thread
953 gs_tlsThisThread = ::TlsAlloc();
954 if ( gs_tlsThisThread == 0xFFFFFFFF )
955 {
956 // in normal circumstances it will only happen if all other
957 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
958 // words, this should never happen
959 wxLogSysError(_("Thread module initialization failed: "
960 "impossible to allocate index in thread "
961 "local storage"));
962
963 return FALSE;
964 }
965
966 // main thread doesn't have associated wxThread object, so store 0 in the
967 // TLS instead
968 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
969 {
970 ::TlsFree(gs_tlsThisThread);
971 gs_tlsThisThread = 0xFFFFFFFF;
972
973 wxLogSysError(_("Thread module initialization failed: "
974 "can not store value in thread local storage"));
975
976 return FALSE;
977 }
978
979 gs_critsectWaitingForGui = new wxCriticalSection();
980
981 gs_critsectGui = new wxCriticalSection();
982 gs_critsectGui->Enter();
983
984 // no error return for GetCurrentThreadId()
985 gs_idMainThread = ::GetCurrentThreadId();
986
987 return TRUE;
988 }
989
990 void wxThreadModule::OnExit()
991 {
992 if ( !::TlsFree(gs_tlsThisThread) )
993 {
994 wxLogLastError("TlsFree failed.");
995 }
996
997 if ( gs_critsectGui )
998 {
999 gs_critsectGui->Leave();
1000 delete gs_critsectGui;
1001 gs_critsectGui = NULL;
1002 }
1003
1004 delete gs_critsectWaitingForGui;
1005 gs_critsectWaitingForGui = NULL;
1006 }
1007
1008 // ----------------------------------------------------------------------------
1009 // under Windows, these functions are implemented using a critical section and
1010 // not a mutex, so the names are a bit confusing
1011 // ----------------------------------------------------------------------------
1012
1013 void WXDLLEXPORT wxMutexGuiEnter()
1014 {
1015 // this would dead lock everything...
1016 wxASSERT_MSG( !wxThread::IsMain(),
1017 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1018
1019 // the order in which we enter the critical sections here is crucial!!
1020
1021 // set the flag telling to the main thread that we want to do some GUI
1022 {
1023 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1024
1025 gs_nWaitingForGui++;
1026 }
1027
1028 wxWakeUpMainThread();
1029
1030 // now we may block here because the main thread will soon let us in
1031 // (during the next iteration of OnIdle())
1032 gs_critsectGui->Enter();
1033 }
1034
1035 void WXDLLEXPORT wxMutexGuiLeave()
1036 {
1037 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1038
1039 if ( wxThread::IsMain() )
1040 {
1041 gs_bGuiOwnedByMainThread = FALSE;
1042 }
1043 else
1044 {
1045 // decrement the number of waiters now
1046 wxASSERT_MSG( gs_nWaitingForGui > 0,
1047 wxT("calling wxMutexGuiLeave() without entering it first?") );
1048
1049 gs_nWaitingForGui--;
1050
1051 wxWakeUpMainThread();
1052 }
1053
1054 gs_critsectGui->Leave();
1055 }
1056
1057 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1058 {
1059 wxASSERT_MSG( wxThread::IsMain(),
1060 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1061
1062 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1063
1064 if ( gs_nWaitingForGui == 0 )
1065 {
1066 // no threads are waiting for GUI - so we may acquire the lock without
1067 // any danger (but only if we don't already have it)
1068 if ( !wxGuiOwnedByMainThread() )
1069 {
1070 gs_critsectGui->Enter();
1071
1072 gs_bGuiOwnedByMainThread = TRUE;
1073 }
1074 //else: already have it, nothing to do
1075 }
1076 else
1077 {
1078 // some threads are waiting, release the GUI lock if we have it
1079 if ( wxGuiOwnedByMainThread() )
1080 {
1081 wxMutexGuiLeave();
1082 }
1083 //else: some other worker thread is doing GUI
1084 }
1085 }
1086
1087 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1088 {
1089 return gs_bGuiOwnedByMainThread;
1090 }
1091
1092 // wake up the main thread if it's in ::GetMessage()
1093 void WXDLLEXPORT wxWakeUpMainThread()
1094 {
1095 // sending any message would do - hopefully WM_NULL is harmless enough
1096 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
1097 {
1098 // should never happen
1099 wxLogLastError("PostThreadMessage(WM_NULL)");
1100 }
1101 }
1102
1103 bool WXDLLEXPORT wxIsWaitingForThread()
1104 {
1105 return gs_waitingForThread;
1106 }
1107
1108 #endif // wxUSE_THREADS