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