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