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