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