correction to exception handling in threads: call wxThread::OnExit() always
[wxWidgets.git] / src / msw / thread.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name: src/msw/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-2002)
10 // Licence: wxWindows licence
11 /////////////////////////////////////////////////////////////////////////////
12
13 // ----------------------------------------------------------------------------
14 // headers
15 // ----------------------------------------------------------------------------
16
17 // For compilers that support precompilation, includes "wx.h".
18 #include "wx/wxprec.h"
19
20 #if defined(__BORLANDC__)
21 #pragma hdrstop
22 #endif
23
24 #ifndef WX_PRECOMP
25 #include "wx/intl.h"
26 #include "wx/app.h"
27 #endif
28
29 #if wxUSE_THREADS
30
31 #include "wx/apptrait.h"
32 #include "wx/scopeguard.h"
33
34 #include "wx/msw/private.h"
35 #include "wx/msw/missing.h"
36 #include "wx/msw/seh.h"
37
38 #include "wx/except.h"
39 #include "wx/module.h"
40 #include "wx/thread.h"
41
42 // must have this symbol defined to get _beginthread/_endthread declarations
43 #ifndef _MT
44 #define _MT
45 #endif
46
47 #if defined(__BORLANDC__)
48 #if !defined(__MT__)
49 // I can't set -tWM in the IDE (anyone?) so have to do this
50 #define __MT__
51 #endif
52
53 #if !defined(__MFC_COMPAT__)
54 // Needed to know about _beginthreadex etc..
55 #define __MFC_COMPAT__
56 #endif
57 #endif // BC++
58
59 // define wxUSE_BEGIN_THREAD if the compiler has _beginthreadex() function
60 // which should be used instead of Win32 ::CreateThread() if possible
61 #if defined(__VISUALC__) || \
62 (defined(__BORLANDC__) && (__BORLANDC__ >= 0x500)) || \
63 (defined(__GNUG__) && defined(__MSVCRT__)) || \
64 defined(__WATCOMC__) || defined(__MWERKS__)
65
66 #ifndef __WXWINCE__
67 #undef wxUSE_BEGIN_THREAD
68 #define wxUSE_BEGIN_THREAD
69 #endif
70
71 #endif
72
73 #ifdef wxUSE_BEGIN_THREAD
74 // this is where _beginthreadex() is declared
75 #include <process.h>
76
77 // the return type of the thread function entry point
78 typedef unsigned THREAD_RETVAL;
79
80 // the calling convention of the thread function entry point
81 #define THREAD_CALLCONV __stdcall
82 #else
83 // the settings for CreateThread()
84 typedef DWORD THREAD_RETVAL;
85 #define THREAD_CALLCONV WINAPI
86 #endif
87
88 // ----------------------------------------------------------------------------
89 // constants
90 // ----------------------------------------------------------------------------
91
92 // the possible states of the thread ("=>" shows all possible transitions from
93 // this state)
94 enum wxThreadState
95 {
96 STATE_NEW, // didn't start execution yet (=> RUNNING)
97 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
98 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
99 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
100 STATE_EXITED // thread is terminating
101 };
102
103 // ----------------------------------------------------------------------------
104 // this module globals
105 // ----------------------------------------------------------------------------
106
107 // TLS index of the slot where we store the pointer to the current thread
108 static DWORD gs_tlsThisThread = 0xFFFFFFFF;
109
110 // id of the main thread - the one which can call GUI functions without first
111 // calling wxMutexGuiEnter()
112 static DWORD gs_idMainThread = 0;
113
114 // if it's false, some secondary thread is holding the GUI lock
115 static bool gs_bGuiOwnedByMainThread = true;
116
117 // critical section which controls access to all GUI functions: any secondary
118 // thread (i.e. except the main one) must enter this crit section before doing
119 // any GUI calls
120 static wxCriticalSection *gs_critsectGui = NULL;
121
122 // critical section which protects gs_nWaitingForGui variable
123 static wxCriticalSection *gs_critsectWaitingForGui = NULL;
124
125 // critical section which serializes WinThreadStart() and WaitForTerminate()
126 // (this is a potential bottleneck, we use a single crit sect for all threads
127 // in the system, but normally time spent inside it should be quite short)
128 static wxCriticalSection *gs_critsectThreadDelete = NULL;
129
130 // number of threads waiting for GUI in wxMutexGuiEnter()
131 static size_t gs_nWaitingForGui = 0;
132
133 // are we waiting for a thread termination?
134 static bool gs_waitingForThread = false;
135
136 // ============================================================================
137 // Windows implementation of thread and related classes
138 // ============================================================================
139
140 // ----------------------------------------------------------------------------
141 // wxCriticalSection
142 // ----------------------------------------------------------------------------
143
144 wxCriticalSection::wxCriticalSection()
145 {
146 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION) <= sizeof(wxCritSectBuffer),
147 wxCriticalSectionBufferTooSmall );
148
149 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
150 }
151
152 wxCriticalSection::~wxCriticalSection()
153 {
154 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
155 }
156
157 void wxCriticalSection::Enter()
158 {
159 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
160 }
161
162 void wxCriticalSection::Leave()
163 {
164 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
165 }
166
167 // ----------------------------------------------------------------------------
168 // wxMutex
169 // ----------------------------------------------------------------------------
170
171 class wxMutexInternal
172 {
173 public:
174 wxMutexInternal(wxMutexType mutexType);
175 ~wxMutexInternal();
176
177 bool IsOk() const { return m_mutex != NULL; }
178
179 wxMutexError Lock() { return LockTimeout(INFINITE); }
180 wxMutexError TryLock() { return LockTimeout(0); }
181 wxMutexError Unlock();
182
183 private:
184 wxMutexError LockTimeout(DWORD milliseconds);
185
186 HANDLE m_mutex;
187
188 DECLARE_NO_COPY_CLASS(wxMutexInternal)
189 };
190
191 // all mutexes are recursive under Win32 so we don't use mutexType
192 wxMutexInternal::wxMutexInternal(wxMutexType WXUNUSED(mutexType))
193 {
194 // create a nameless (hence intra process and always private) mutex
195 m_mutex = ::CreateMutex
196 (
197 NULL, // default secutiry attributes
198 false, // not initially locked
199 NULL // no name
200 );
201
202 if ( !m_mutex )
203 {
204 wxLogLastError(_T("CreateMutex()"));
205 }
206 }
207
208 wxMutexInternal::~wxMutexInternal()
209 {
210 if ( m_mutex )
211 {
212 if ( !::CloseHandle(m_mutex) )
213 {
214 wxLogLastError(_T("CloseHandle(mutex)"));
215 }
216 }
217 }
218
219 wxMutexError wxMutexInternal::LockTimeout(DWORD milliseconds)
220 {
221 DWORD rc = ::WaitForSingleObject(m_mutex, milliseconds);
222 if ( rc == WAIT_ABANDONED )
223 {
224 // the previous caller died without releasing the mutex, but now we can
225 // really lock it
226 wxLogDebug(_T("WaitForSingleObject() returned WAIT_ABANDONED"));
227
228 // use 0 timeout, normally we should always get it
229 rc = ::WaitForSingleObject(m_mutex, 0);
230 }
231
232 switch ( rc )
233 {
234 case WAIT_OBJECT_0:
235 // ok
236 break;
237
238 case WAIT_TIMEOUT:
239 return wxMUTEX_BUSY;
240
241 case WAIT_ABANDONED: // checked for above
242 default:
243 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
244 // fall through
245
246 case WAIT_FAILED:
247 wxLogLastError(_T("WaitForSingleObject(mutex)"));
248 return wxMUTEX_MISC_ERROR;
249 }
250
251 return wxMUTEX_NO_ERROR;
252 }
253
254 wxMutexError wxMutexInternal::Unlock()
255 {
256 if ( !::ReleaseMutex(m_mutex) )
257 {
258 wxLogLastError(_T("ReleaseMutex()"));
259
260 return wxMUTEX_MISC_ERROR;
261 }
262
263 return wxMUTEX_NO_ERROR;
264 }
265
266 // --------------------------------------------------------------------------
267 // wxSemaphore
268 // --------------------------------------------------------------------------
269
270 // a trivial wrapper around Win32 semaphore
271 class wxSemaphoreInternal
272 {
273 public:
274 wxSemaphoreInternal(int initialcount, int maxcount);
275 ~wxSemaphoreInternal();
276
277 bool IsOk() const { return m_semaphore != NULL; }
278
279 wxSemaError Wait() { return WaitTimeout(INFINITE); }
280
281 wxSemaError TryWait()
282 {
283 wxSemaError rc = WaitTimeout(0);
284 if ( rc == wxSEMA_TIMEOUT )
285 rc = wxSEMA_BUSY;
286
287 return rc;
288 }
289
290 wxSemaError WaitTimeout(unsigned long milliseconds);
291
292 wxSemaError Post();
293
294 private:
295 HANDLE m_semaphore;
296
297 DECLARE_NO_COPY_CLASS(wxSemaphoreInternal)
298 };
299
300 wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
301 {
302 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
303 if ( maxcount == 0 )
304 {
305 // make it practically infinite
306 maxcount = INT_MAX;
307 }
308
309 m_semaphore = ::CreateSemaphore
310 (
311 NULL, // default security attributes
312 initialcount,
313 maxcount,
314 NULL // no name
315 );
316 #endif
317 if ( !m_semaphore )
318 {
319 wxLogLastError(_T("CreateSemaphore()"));
320 }
321 }
322
323 wxSemaphoreInternal::~wxSemaphoreInternal()
324 {
325 if ( m_semaphore )
326 {
327 if ( !::CloseHandle(m_semaphore) )
328 {
329 wxLogLastError(_T("CloseHandle(semaphore)"));
330 }
331 }
332 }
333
334 wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds)
335 {
336 DWORD rc = ::WaitForSingleObject( m_semaphore, milliseconds );
337
338 switch ( rc )
339 {
340 case WAIT_OBJECT_0:
341 return wxSEMA_NO_ERROR;
342
343 case WAIT_TIMEOUT:
344 return wxSEMA_TIMEOUT;
345
346 default:
347 wxLogLastError(_T("WaitForSingleObject(semaphore)"));
348 }
349
350 return wxSEMA_MISC_ERROR;
351 }
352
353 wxSemaError wxSemaphoreInternal::Post()
354 {
355 #if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
356 if ( !::ReleaseSemaphore(m_semaphore, 1, NULL /* ptr to previous count */) )
357 #endif
358 {
359 wxLogLastError(_T("ReleaseSemaphore"));
360
361 return wxSEMA_MISC_ERROR;
362 }
363
364 return wxSEMA_NO_ERROR;
365 }
366
367 // ----------------------------------------------------------------------------
368 // wxThread implementation
369 // ----------------------------------------------------------------------------
370
371 // wxThreadInternal class
372 // ----------------------
373
374 class wxThreadInternal
375 {
376 public:
377 wxThreadInternal(wxThread *thread)
378 {
379 m_thread = thread;
380 m_hThread = 0;
381 m_state = STATE_NEW;
382 m_priority = WXTHREAD_DEFAULT_PRIORITY;
383 m_nRef = 1;
384 }
385
386 ~wxThreadInternal()
387 {
388 Free();
389 }
390
391 void Free()
392 {
393 if ( m_hThread )
394 {
395 if ( !::CloseHandle(m_hThread) )
396 {
397 wxLogLastError(wxT("CloseHandle(thread)"));
398 }
399
400 m_hThread = 0;
401 }
402 }
403
404 // create a new (suspended) thread (for the given thread object)
405 bool Create(wxThread *thread, unsigned int stackSize);
406
407 // wait for the thread to terminate, either by itself, or by asking it
408 // (politely, this is not Kill()!) to do it
409 wxThreadError WaitForTerminate(wxCriticalSection& cs,
410 wxThread::ExitCode *pRc,
411 wxThread *threadToDelete = NULL);
412
413 // kill the thread unconditionally
414 wxThreadError Kill();
415
416 // suspend/resume/terminate
417 bool Suspend();
418 bool Resume();
419 void Cancel() { m_state = STATE_CANCELED; }
420
421 // thread state
422 void SetState(wxThreadState state) { m_state = state; }
423 wxThreadState GetState() const { return m_state; }
424
425 // thread priority
426 void SetPriority(unsigned int priority);
427 unsigned int GetPriority() const { return m_priority; }
428
429 // thread handle and id
430 HANDLE GetHandle() const { return m_hThread; }
431 DWORD GetId() const { return m_tid; }
432
433 // the thread function forwarding to DoThreadStart
434 static THREAD_RETVAL THREAD_CALLCONV WinThreadStart(void *thread);
435
436 // really start the thread (if it's not already dead)
437 static THREAD_RETVAL DoThreadStart(wxThread *thread);
438
439 // call OnExit() on the thread
440 static void DoThreadOnExit(wxThread *thread);
441
442
443 void KeepAlive()
444 {
445 if ( m_thread->IsDetached() )
446 ::InterlockedIncrement(&m_nRef);
447 }
448
449 void LetDie()
450 {
451 if ( m_thread->IsDetached() && !::InterlockedDecrement(&m_nRef) )
452 delete m_thread;
453 }
454
455 private:
456 // the thread we're associated with
457 wxThread *m_thread;
458
459 HANDLE m_hThread; // handle of the thread
460 wxThreadState m_state; // state, see wxThreadState enum
461 unsigned int m_priority; // thread priority in "wx" units
462 DWORD m_tid; // thread id
463
464 // number of threads which need this thread to remain alive, when the count
465 // reaches 0 we kill the owning wxThread -- and die ourselves with it
466 LONG m_nRef;
467
468 DECLARE_NO_COPY_CLASS(wxThreadInternal)
469 };
470
471 // small class which keeps a thread alive during its lifetime
472 class wxThreadKeepAlive
473 {
474 public:
475 wxThreadKeepAlive(wxThreadInternal& thrImpl) : m_thrImpl(thrImpl)
476 { m_thrImpl.KeepAlive(); }
477 ~wxThreadKeepAlive()
478 { m_thrImpl.LetDie(); }
479
480 private:
481 wxThreadInternal& m_thrImpl;
482 };
483
484 /* static */
485 void wxThreadInternal::DoThreadOnExit(wxThread *thread)
486 {
487 wxTRY
488 {
489 thread->OnExit();
490 }
491 wxCATCH_ALL( wxTheApp->OnUnhandledException(); )
492 }
493
494 /* static */
495 THREAD_RETVAL wxThreadInternal::DoThreadStart(wxThread *thread)
496 {
497 wxON_BLOCK_EXIT1(DoThreadOnExit, thread);
498
499 THREAD_RETVAL rc = (THREAD_RETVAL)-1;
500
501 wxTRY
502 {
503 // store the thread object in the TLS
504 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
505 {
506 wxLogSysError(_("Can not start thread: error writing TLS."));
507
508 return (THREAD_RETVAL)-1;
509 }
510
511 rc = (THREAD_RETVAL)thread->Entry();
512 }
513 wxCATCH_ALL( wxTheApp->OnUnhandledException(); )
514
515 return rc;
516 }
517
518 /* static */
519 THREAD_RETVAL THREAD_CALLCONV wxThreadInternal::WinThreadStart(void *param)
520 {
521 THREAD_RETVAL rc = (THREAD_RETVAL)-1;
522
523 wxThread * const thread = (wxThread *)param;
524
525 // each thread has its own SEH translator so install our own a.s.a.p.
526 DisableAutomaticSETranslator();
527
528 // first of all, check whether we hadn't been cancelled already and don't
529 // start the user code at all then
530 const bool hasExited = thread->m_internal->GetState() == STATE_EXITED;
531
532 // run the thread function itself inside a SEH try/except block
533 wxSEH_TRY
534 {
535 if ( hasExited )
536 DoThreadOnExit(thread);
537 else
538 rc = DoThreadStart(thread);
539 }
540 wxSEH_HANDLE((THREAD_RETVAL)-1)
541
542
543 // save IsDetached because thread object can be deleted by joinable
544 // threads after state is changed to STATE_EXITED.
545 const bool isDetached = thread->IsDetached();
546 if ( !hasExited )
547 {
548 // enter m_critsect before changing the thread state
549 //
550 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
551 // incompatible with C++ object dtors
552 thread->m_critsect.Enter();
553 thread->m_internal->SetState(STATE_EXITED);
554 thread->m_critsect.Leave();
555 }
556
557 // the thread may delete itself now if it wants, we don't need it any more
558 if ( isDetached )
559 thread->m_internal->LetDie();
560
561 return rc;
562 }
563
564 void wxThreadInternal::SetPriority(unsigned int priority)
565 {
566 m_priority = priority;
567
568 // translate wxWidgets priority to the Windows one
569 int win_priority;
570 if (m_priority <= 20)
571 win_priority = THREAD_PRIORITY_LOWEST;
572 else if (m_priority <= 40)
573 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
574 else if (m_priority <= 60)
575 win_priority = THREAD_PRIORITY_NORMAL;
576 else if (m_priority <= 80)
577 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
578 else if (m_priority <= 100)
579 win_priority = THREAD_PRIORITY_HIGHEST;
580 else
581 {
582 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
583 win_priority = THREAD_PRIORITY_NORMAL;
584 }
585
586 if ( !::SetThreadPriority(m_hThread, win_priority) )
587 {
588 wxLogSysError(_("Can't set thread priority"));
589 }
590 }
591
592 bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
593 {
594 wxASSERT_MSG( m_state == STATE_NEW && !m_hThread,
595 _T("Create()ing thread twice?") );
596
597 // for compilers which have it, we should use C RTL function for thread
598 // creation instead of Win32 API one because otherwise we will have memory
599 // leaks if the thread uses C RTL (and most threads do)
600 #ifdef wxUSE_BEGIN_THREAD
601
602 // Watcom is reported to not like 0 stack size (which means "use default"
603 // for the other compilers and is also the default value for stackSize)
604 #ifdef __WATCOMC__
605 if ( !stackSize )
606 stackSize = 10240;
607 #endif // __WATCOMC__
608
609 m_hThread = (HANDLE)_beginthreadex
610 (
611 NULL, // default security
612 stackSize,
613 wxThreadInternal::WinThreadStart, // entry point
614 thread,
615 CREATE_SUSPENDED,
616 (unsigned int *)&m_tid
617 );
618 #else // compiler doesn't have _beginthreadex
619 m_hThread = ::CreateThread
620 (
621 NULL, // default security
622 stackSize, // stack size
623 wxThreadInternal::WinThreadStart, // thread entry point
624 (LPVOID)thread, // parameter
625 CREATE_SUSPENDED, // flags
626 &m_tid // [out] thread id
627 );
628 #endif // _beginthreadex/CreateThread
629
630 if ( m_hThread == NULL )
631 {
632 wxLogSysError(_("Can't create thread"));
633
634 return false;
635 }
636
637 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
638 {
639 SetPriority(m_priority);
640 }
641
642 return true;
643 }
644
645 wxThreadError wxThreadInternal::Kill()
646 {
647 if ( !::TerminateThread(m_hThread, (DWORD)-1) )
648 {
649 wxLogSysError(_("Couldn't terminate thread"));
650
651 return wxTHREAD_MISC_ERROR;
652 }
653
654 Free();
655
656 return wxTHREAD_NO_ERROR;
657 }
658
659 wxThreadError
660 wxThreadInternal::WaitForTerminate(wxCriticalSection& cs,
661 wxThread::ExitCode *pRc,
662 wxThread *threadToDelete)
663 {
664 // prevent the thread C++ object from disappearing as long as we are using
665 // it here
666 wxThreadKeepAlive keepAlive(*this);
667
668
669 // we may either wait passively for the thread to terminate (when called
670 // from Wait()) or ask it to terminate (when called from Delete())
671 bool shouldDelete = threadToDelete != NULL;
672
673 wxThread::ExitCode rc = 0;
674
675 // we might need to resume the thread if it's currently stopped
676 bool shouldResume = false;
677
678 // as Delete() (which calls us) is always safe to call we need to consider
679 // all possible states
680 {
681 wxCriticalSectionLocker lock(cs);
682
683 if ( m_state == STATE_NEW )
684 {
685 if ( shouldDelete )
686 {
687 // WinThreadStart() will see it and terminate immediately, no
688 // need to cancel the thread -- but we still need to resume it
689 // to let it run
690 m_state = STATE_EXITED;
691
692 // we must call Resume() as the thread hasn't been initially
693 // resumed yet (and as Resume() it knows about STATE_EXITED
694 // special case, it won't touch it and WinThreadStart() will
695 // just exit immediately)
696 shouldResume = true;
697 shouldDelete = false;
698 }
699 //else: shouldResume is correctly set to false here, wait until
700 // someone else runs the thread and it finishes
701 }
702 else // running, paused, cancelled or even exited
703 {
704 shouldResume = m_state == STATE_PAUSED;
705 }
706 }
707
708 // resume the thread if it is paused
709 if ( shouldResume )
710 Resume();
711
712 // ask the thread to terminate
713 if ( shouldDelete )
714 {
715 wxCriticalSectionLocker lock(cs);
716
717 Cancel();
718 }
719
720
721 // now wait for thread to finish
722 if ( wxThread::IsMain() )
723 {
724 // set flag for wxIsWaitingForThread()
725 gs_waitingForThread = true;
726 }
727
728 // we can't just wait for the thread to terminate because it might be
729 // calling some GUI functions and so it will never terminate before we
730 // process the Windows messages that result from these functions
731 // (note that even in console applications we might have to process
732 // messages if we use wxExecute() or timers or ...)
733 DWORD result wxDUMMY_INITIALIZE(0);
734 do
735 {
736 if ( wxThread::IsMain() )
737 {
738 // give the thread we're waiting for chance to do the GUI call
739 // it might be in
740 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
741 {
742 wxMutexGuiLeave();
743 }
744 }
745
746 #if !defined(QS_ALLPOSTMESSAGE)
747 #define QS_ALLPOSTMESSAGE 0
748 #endif
749
750 result = ::MsgWaitForMultipleObjects
751 (
752 1, // number of objects to wait for
753 &m_hThread, // the objects
754 false, // don't wait for all objects
755 INFINITE, // no timeout
756 QS_ALLINPUT|QS_ALLPOSTMESSAGE // return as soon as there are any events
757 );
758
759 switch ( result )
760 {
761 case 0xFFFFFFFF:
762 // error
763 wxLogSysError(_("Can not wait for thread termination"));
764 Kill();
765 return wxTHREAD_KILLED;
766
767 case WAIT_OBJECT_0:
768 // thread we're waiting for terminated
769 break;
770
771 case WAIT_OBJECT_0 + 1:
772 // new message arrived, process it -- but only if we're the
773 // main thread as we don't support processing messages in
774 // the other ones
775 //
776 // NB: we still must include QS_ALLINPUT even when waiting
777 // in a secondary thread because if it had created some
778 // window somehow (possible not even using wxWidgets)
779 // the system might dead lock then
780 if ( wxThread::IsMain() )
781 {
782 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits()
783 : NULL;
784
785 if ( traits && !traits->DoMessageFromThreadWait() )
786 {
787 // WM_QUIT received: kill the thread
788 Kill();
789
790 return wxTHREAD_KILLED;
791 }
792 }
793 break;
794
795 default:
796 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
797 }
798 } while ( result != WAIT_OBJECT_0 );
799
800 if ( wxThread::IsMain() )
801 {
802 gs_waitingForThread = false;
803 }
804
805
806 // although the thread might be already in the EXITED state it might not
807 // have terminated yet and so we are not sure that it has actually
808 // terminated if the "if" above hadn't been taken
809 for ( ;; )
810 {
811 if ( !::GetExitCodeThread(m_hThread, (LPDWORD)&rc) )
812 {
813 wxLogLastError(wxT("GetExitCodeThread"));
814
815 rc = (wxThread::ExitCode)-1;
816
817 break;
818 }
819
820 if ( (DWORD)rc != STILL_ACTIVE )
821 break;
822
823 // give the other thread some time to terminate, otherwise we may be
824 // starving it
825 ::Sleep(1);
826 }
827
828 if ( pRc )
829 *pRc = rc;
830
831 // we don't need the thread handle any more in any case
832 Free();
833
834
835 return rc == (wxThread::ExitCode)-1 ? wxTHREAD_MISC_ERROR
836 : wxTHREAD_NO_ERROR;
837 }
838
839 bool wxThreadInternal::Suspend()
840 {
841 DWORD nSuspendCount = ::SuspendThread(m_hThread);
842 if ( nSuspendCount == (DWORD)-1 )
843 {
844 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
845
846 return false;
847 }
848
849 m_state = STATE_PAUSED;
850
851 return true;
852 }
853
854 bool wxThreadInternal::Resume()
855 {
856 DWORD nSuspendCount = ::ResumeThread(m_hThread);
857 if ( nSuspendCount == (DWORD)-1 )
858 {
859 wxLogSysError(_("Can not resume thread %x"), m_hThread);
860
861 return false;
862 }
863
864 // don't change the state from STATE_EXITED because it's special and means
865 // we are going to terminate without running any user code - if we did it,
866 // the code in WaitForTerminate() wouldn't work
867 if ( m_state != STATE_EXITED )
868 {
869 m_state = STATE_RUNNING;
870 }
871
872 return true;
873 }
874
875 // static functions
876 // ----------------
877
878 wxThread *wxThread::This()
879 {
880 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
881
882 // be careful, 0 may be a valid return value as well
883 if ( !thread && (::GetLastError() != NO_ERROR) )
884 {
885 wxLogSysError(_("Couldn't get the current thread pointer"));
886
887 // return NULL...
888 }
889
890 return thread;
891 }
892
893 bool wxThread::IsMain()
894 {
895 return ::GetCurrentThreadId() == gs_idMainThread || gs_idMainThread == 0;
896 }
897
898 void wxThread::Yield()
899 {
900 // 0 argument to Sleep() is special and means to just give away the rest of
901 // our timeslice
902 ::Sleep(0);
903 }
904
905 void wxThread::Sleep(unsigned long milliseconds)
906 {
907 ::Sleep(milliseconds);
908 }
909
910 int wxThread::GetCPUCount()
911 {
912 SYSTEM_INFO si;
913 GetSystemInfo(&si);
914
915 return si.dwNumberOfProcessors;
916 }
917
918 unsigned long wxThread::GetCurrentId()
919 {
920 return (unsigned long)::GetCurrentThreadId();
921 }
922
923 bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level))
924 {
925 #ifdef __WXWINCE__
926 return false;
927 #else
928 wxASSERT_MSG( IsMain(), _T("should only be called from the main thread") );
929
930 // ok only for the default one
931 if ( level == 0 )
932 return 0;
933
934 // get system affinity mask first
935 HANDLE hProcess = ::GetCurrentProcess();
936 DWORD_PTR dwProcMask, dwSysMask;
937 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
938 {
939 wxLogLastError(_T("GetProcessAffinityMask"));
940
941 return false;
942 }
943
944 // how many CPUs have we got?
945 if ( dwSysMask == 1 )
946 {
947 // don't bother with all this complicated stuff - on a single
948 // processor system it doesn't make much sense anyhow
949 return level == 1;
950 }
951
952 // calculate the process mask: it's a bit vector with one bit per
953 // processor; we want to schedule the process to run on first level
954 // CPUs
955 DWORD bit = 1;
956 while ( bit )
957 {
958 if ( dwSysMask & bit )
959 {
960 // ok, we can set this bit
961 dwProcMask |= bit;
962
963 // another process added
964 if ( --level == 0 )
965 {
966 // and that's enough
967 break;
968 }
969 }
970
971 // next bit
972 bit <<= 1;
973 }
974
975 // could we set all bits?
976 if ( level != 0 )
977 {
978 wxLogDebug(_T("bad level %u in wxThread::SetConcurrency()"), level);
979
980 return false;
981 }
982
983 // set it: we can't link to SetProcessAffinityMask() because it doesn't
984 // exist in Win9x, use RT binding instead
985
986 typedef BOOL (*SETPROCESSAFFINITYMASK)(HANDLE, DWORD);
987
988 // can use static var because we're always in the main thread here
989 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
990
991 if ( !pfnSetProcessAffinityMask )
992 {
993 HMODULE hModKernel = ::LoadLibrary(_T("kernel32"));
994 if ( hModKernel )
995 {
996 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
997 ::GetProcAddress(hModKernel, "SetProcessAffinityMask");
998 }
999
1000 // we've discovered a MT version of Win9x!
1001 wxASSERT_MSG( pfnSetProcessAffinityMask,
1002 _T("this system has several CPUs but no SetProcessAffinityMask function?") );
1003 }
1004
1005 if ( !pfnSetProcessAffinityMask )
1006 {
1007 // msg given above - do it only once
1008 return false;
1009 }
1010
1011 if ( pfnSetProcessAffinityMask(hProcess, dwProcMask) == 0 )
1012 {
1013 wxLogLastError(_T("SetProcessAffinityMask"));
1014
1015 return false;
1016 }
1017
1018 return true;
1019 #endif // __WXWINCE__/!__WXWINCE__
1020 }
1021
1022 // ctor and dtor
1023 // -------------
1024
1025 wxThread::wxThread(wxThreadKind kind)
1026 {
1027 m_internal = new wxThreadInternal(this);
1028
1029 m_isDetached = kind == wxTHREAD_DETACHED;
1030 }
1031
1032 wxThread::~wxThread()
1033 {
1034 delete m_internal;
1035 }
1036
1037 // create/start thread
1038 // -------------------
1039
1040 wxThreadError wxThread::Create(unsigned int stackSize)
1041 {
1042 wxCriticalSectionLocker lock(m_critsect);
1043
1044 if ( !m_internal->Create(this, stackSize) )
1045 return wxTHREAD_NO_RESOURCE;
1046
1047 return wxTHREAD_NO_ERROR;
1048 }
1049
1050 wxThreadError wxThread::Run()
1051 {
1052 wxCriticalSectionLocker lock(m_critsect);
1053
1054 if ( m_internal->GetState() != STATE_NEW )
1055 {
1056 // actually, it may be almost any state at all, not only STATE_RUNNING
1057 return wxTHREAD_RUNNING;
1058 }
1059
1060 // the thread has just been created and is still suspended - let it run
1061 return Resume();
1062 }
1063
1064 // suspend/resume thread
1065 // ---------------------
1066
1067 wxThreadError wxThread::Pause()
1068 {
1069 wxCriticalSectionLocker lock(m_critsect);
1070
1071 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
1072 }
1073
1074 wxThreadError wxThread::Resume()
1075 {
1076 wxCriticalSectionLocker lock(m_critsect);
1077
1078 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
1079 }
1080
1081 // stopping thread
1082 // ---------------
1083
1084 wxThread::ExitCode wxThread::Wait()
1085 {
1086 // although under Windows we can wait for any thread, it's an error to
1087 // wait for a detached one in wxWin API
1088 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
1089 _T("wxThread::Wait(): can't wait for detached thread") );
1090
1091 ExitCode rc = (ExitCode)-1;
1092
1093 (void)m_internal->WaitForTerminate(m_critsect, &rc);
1094
1095 return rc;
1096 }
1097
1098 wxThreadError wxThread::Delete(ExitCode *pRc)
1099 {
1100 return m_internal->WaitForTerminate(m_critsect, pRc, this);
1101 }
1102
1103 wxThreadError wxThread::Kill()
1104 {
1105 if ( !IsRunning() )
1106 return wxTHREAD_NOT_RUNNING;
1107
1108 wxThreadError rc = m_internal->Kill();
1109
1110 if ( IsDetached() )
1111 {
1112 delete this;
1113 }
1114 else // joinable
1115 {
1116 // update the status of the joinable thread
1117 wxCriticalSectionLocker lock(m_critsect);
1118 m_internal->SetState(STATE_EXITED);
1119 }
1120
1121 return rc;
1122 }
1123
1124 void wxThread::Exit(ExitCode status)
1125 {
1126 m_internal->Free();
1127
1128 if ( IsDetached() )
1129 {
1130 delete this;
1131 }
1132 else // joinable
1133 {
1134 // update the status of the joinable thread
1135 wxCriticalSectionLocker lock(m_critsect);
1136 m_internal->SetState(STATE_EXITED);
1137 }
1138
1139 #ifdef wxUSE_BEGIN_THREAD
1140 _endthreadex((unsigned)status);
1141 #else // !VC++
1142 ::ExitThread((DWORD)status);
1143 #endif // VC++/!VC++
1144
1145 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1146 }
1147
1148 // priority setting
1149 // ----------------
1150
1151 void wxThread::SetPriority(unsigned int prio)
1152 {
1153 wxCriticalSectionLocker lock(m_critsect);
1154
1155 m_internal->SetPriority(prio);
1156 }
1157
1158 unsigned int wxThread::GetPriority() const
1159 {
1160 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1161
1162 return m_internal->GetPriority();
1163 }
1164
1165 unsigned long wxThread::GetId() const
1166 {
1167 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1168
1169 return (unsigned long)m_internal->GetId();
1170 }
1171
1172 bool wxThread::IsRunning() const
1173 {
1174 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1175
1176 return m_internal->GetState() == STATE_RUNNING;
1177 }
1178
1179 bool wxThread::IsAlive() const
1180 {
1181 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1182
1183 return (m_internal->GetState() == STATE_RUNNING) ||
1184 (m_internal->GetState() == STATE_PAUSED);
1185 }
1186
1187 bool wxThread::IsPaused() const
1188 {
1189 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1190
1191 return m_internal->GetState() == STATE_PAUSED;
1192 }
1193
1194 bool wxThread::TestDestroy()
1195 {
1196 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1197
1198 return m_internal->GetState() == STATE_CANCELED;
1199 }
1200
1201 // ----------------------------------------------------------------------------
1202 // Automatic initialization for thread module
1203 // ----------------------------------------------------------------------------
1204
1205 class wxThreadModule : public wxModule
1206 {
1207 public:
1208 virtual bool OnInit();
1209 virtual void OnExit();
1210
1211 private:
1212 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1213 };
1214
1215 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1216
1217 bool wxThreadModule::OnInit()
1218 {
1219 // allocate TLS index for storing the pointer to the current thread
1220 gs_tlsThisThread = ::TlsAlloc();
1221 if ( gs_tlsThisThread == 0xFFFFFFFF )
1222 {
1223 // in normal circumstances it will only happen if all other
1224 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1225 // words, this should never happen
1226 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1227
1228 return false;
1229 }
1230
1231 // main thread doesn't have associated wxThread object, so store 0 in the
1232 // TLS instead
1233 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
1234 {
1235 ::TlsFree(gs_tlsThisThread);
1236 gs_tlsThisThread = 0xFFFFFFFF;
1237
1238 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1239
1240 return false;
1241 }
1242
1243 gs_critsectWaitingForGui = new wxCriticalSection();
1244
1245 gs_critsectGui = new wxCriticalSection();
1246 gs_critsectGui->Enter();
1247
1248 gs_critsectThreadDelete = new wxCriticalSection;
1249
1250 // no error return for GetCurrentThreadId()
1251 gs_idMainThread = ::GetCurrentThreadId();
1252
1253 return true;
1254 }
1255
1256 void wxThreadModule::OnExit()
1257 {
1258 if ( !::TlsFree(gs_tlsThisThread) )
1259 {
1260 wxLogLastError(wxT("TlsFree failed."));
1261 }
1262
1263 delete gs_critsectThreadDelete;
1264 gs_critsectThreadDelete = NULL;
1265
1266 if ( gs_critsectGui )
1267 {
1268 gs_critsectGui->Leave();
1269 delete gs_critsectGui;
1270 gs_critsectGui = NULL;
1271 }
1272
1273 delete gs_critsectWaitingForGui;
1274 gs_critsectWaitingForGui = NULL;
1275 }
1276
1277 // ----------------------------------------------------------------------------
1278 // under Windows, these functions are implemented using a critical section and
1279 // not a mutex, so the names are a bit confusing
1280 // ----------------------------------------------------------------------------
1281
1282 void WXDLLIMPEXP_BASE wxMutexGuiEnter()
1283 {
1284 // this would dead lock everything...
1285 wxASSERT_MSG( !wxThread::IsMain(),
1286 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1287
1288 // the order in which we enter the critical sections here is crucial!!
1289
1290 // set the flag telling to the main thread that we want to do some GUI
1291 {
1292 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1293
1294 gs_nWaitingForGui++;
1295 }
1296
1297 wxWakeUpMainThread();
1298
1299 // now we may block here because the main thread will soon let us in
1300 // (during the next iteration of OnIdle())
1301 gs_critsectGui->Enter();
1302 }
1303
1304 void WXDLLIMPEXP_BASE wxMutexGuiLeave()
1305 {
1306 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1307
1308 if ( wxThread::IsMain() )
1309 {
1310 gs_bGuiOwnedByMainThread = false;
1311 }
1312 else
1313 {
1314 // decrement the number of threads waiting for GUI access now
1315 wxASSERT_MSG( gs_nWaitingForGui > 0,
1316 wxT("calling wxMutexGuiLeave() without entering it first?") );
1317
1318 gs_nWaitingForGui--;
1319
1320 wxWakeUpMainThread();
1321 }
1322
1323 gs_critsectGui->Leave();
1324 }
1325
1326 void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
1327 {
1328 wxASSERT_MSG( wxThread::IsMain(),
1329 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1330
1331 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1332
1333 if ( gs_nWaitingForGui == 0 )
1334 {
1335 // no threads are waiting for GUI - so we may acquire the lock without
1336 // any danger (but only if we don't already have it)
1337 if ( !wxGuiOwnedByMainThread() )
1338 {
1339 gs_critsectGui->Enter();
1340
1341 gs_bGuiOwnedByMainThread = true;
1342 }
1343 //else: already have it, nothing to do
1344 }
1345 else
1346 {
1347 // some threads are waiting, release the GUI lock if we have it
1348 if ( wxGuiOwnedByMainThread() )
1349 {
1350 wxMutexGuiLeave();
1351 }
1352 //else: some other worker thread is doing GUI
1353 }
1354 }
1355
1356 bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
1357 {
1358 return gs_bGuiOwnedByMainThread;
1359 }
1360
1361 // wake up the main thread if it's in ::GetMessage()
1362 void WXDLLIMPEXP_BASE wxWakeUpMainThread()
1363 {
1364 // sending any message would do - hopefully WM_NULL is harmless enough
1365 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
1366 {
1367 // should never happen
1368 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1369 }
1370 }
1371
1372 bool WXDLLIMPEXP_BASE wxIsWaitingForThread()
1373 {
1374 return gs_waitingForThread;
1375 }
1376
1377 // ----------------------------------------------------------------------------
1378 // include common implementation code
1379 // ----------------------------------------------------------------------------
1380
1381 #include "wx/thrimpl.cpp"
1382
1383 #endif // wxUSE_THREADS
1384