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