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