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