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