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