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