changed wxCondition API to take a reference, not pointer, to wxMutex
[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 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
1139 {
1140 wxLogLastError(wxT("GetExitCodeThread"));
1141
1142 rc = (ExitCode)-1;
1143 }
1144
1145 if ( IsDetached() )
1146 {
1147 // if the thread exits normally, this is done in WinThreadStart, but in
1148 // this case it would have been too early because
1149 // MsgWaitForMultipleObject() would fail if the thread handle was
1150 // closed while we were waiting on it, so we must do it here
1151 delete this;
1152 }
1153
1154 wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
1155 wxT("thread must be already terminated.") );
1156
1157 if ( pRc )
1158 *pRc = rc;
1159
1160 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
1161 }
1162
1163 wxThreadError wxThread::Kill()
1164 {
1165 if ( !IsRunning() )
1166 return wxTHREAD_NOT_RUNNING;
1167
1168 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
1169 {
1170 wxLogSysError(_("Couldn't terminate thread"));
1171
1172 return wxTHREAD_MISC_ERROR;
1173 }
1174
1175 m_internal->Free();
1176
1177 if ( IsDetached() )
1178 {
1179 delete this;
1180 }
1181
1182 return wxTHREAD_NO_ERROR;
1183 }
1184
1185 void wxThread::Exit(ExitCode status)
1186 {
1187 m_internal->Free();
1188
1189 if ( IsDetached() )
1190 {
1191 delete this;
1192 }
1193
1194 #ifdef wxUSE_BEGIN_THREAD
1195 _endthreadex((unsigned)status);
1196 #else // !VC++
1197 ::ExitThread((DWORD)status);
1198 #endif // VC++/!VC++
1199
1200 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1201 }
1202
1203 // priority setting
1204 // ----------------
1205
1206 void wxThread::SetPriority(unsigned int prio)
1207 {
1208 wxCriticalSectionLocker lock(m_critsect);
1209
1210 m_internal->SetPriority(prio);
1211 }
1212
1213 unsigned int wxThread::GetPriority() const
1214 {
1215 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1216
1217 return m_internal->GetPriority();
1218 }
1219
1220 unsigned long wxThread::GetId() const
1221 {
1222 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1223
1224 return (unsigned long)m_internal->GetId();
1225 }
1226
1227 bool wxThread::IsRunning() const
1228 {
1229 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1230
1231 return m_internal->GetState() == STATE_RUNNING;
1232 }
1233
1234 bool wxThread::IsAlive() const
1235 {
1236 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1237
1238 return (m_internal->GetState() == STATE_RUNNING) ||
1239 (m_internal->GetState() == STATE_PAUSED);
1240 }
1241
1242 bool wxThread::IsPaused() const
1243 {
1244 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1245
1246 return m_internal->GetState() == STATE_PAUSED;
1247 }
1248
1249 bool wxThread::TestDestroy()
1250 {
1251 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1252
1253 return m_internal->GetState() == STATE_CANCELED;
1254 }
1255
1256 // ----------------------------------------------------------------------------
1257 // Automatic initialization for thread module
1258 // ----------------------------------------------------------------------------
1259
1260 class wxThreadModule : public wxModule
1261 {
1262 public:
1263 virtual bool OnInit();
1264 virtual void OnExit();
1265
1266 private:
1267 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1268 };
1269
1270 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1271
1272 bool wxThreadModule::OnInit()
1273 {
1274 // allocate TLS index for storing the pointer to the current thread
1275 gs_tlsThisThread = ::TlsAlloc();
1276 if ( gs_tlsThisThread == 0xFFFFFFFF )
1277 {
1278 // in normal circumstances it will only happen if all other
1279 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1280 // words, this should never happen
1281 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1282
1283 return FALSE;
1284 }
1285
1286 // main thread doesn't have associated wxThread object, so store 0 in the
1287 // TLS instead
1288 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
1289 {
1290 ::TlsFree(gs_tlsThisThread);
1291 gs_tlsThisThread = 0xFFFFFFFF;
1292
1293 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1294
1295 return FALSE;
1296 }
1297
1298 gs_critsectWaitingForGui = new wxCriticalSection();
1299
1300 gs_critsectGui = new wxCriticalSection();
1301 gs_critsectGui->Enter();
1302
1303 // no error return for GetCurrentThreadId()
1304 gs_idMainThread = ::GetCurrentThreadId();
1305
1306 return TRUE;
1307 }
1308
1309 void wxThreadModule::OnExit()
1310 {
1311 if ( !::TlsFree(gs_tlsThisThread) )
1312 {
1313 wxLogLastError(wxT("TlsFree failed."));
1314 }
1315
1316 if ( gs_critsectGui )
1317 {
1318 gs_critsectGui->Leave();
1319 delete gs_critsectGui;
1320 gs_critsectGui = NULL;
1321 }
1322
1323 delete gs_critsectWaitingForGui;
1324 gs_critsectWaitingForGui = NULL;
1325 }
1326
1327 // ----------------------------------------------------------------------------
1328 // under Windows, these functions are implemented using a critical section and
1329 // not a mutex, so the names are a bit confusing
1330 // ----------------------------------------------------------------------------
1331
1332 void WXDLLEXPORT wxMutexGuiEnter()
1333 {
1334 // this would dead lock everything...
1335 wxASSERT_MSG( !wxThread::IsMain(),
1336 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1337
1338 // the order in which we enter the critical sections here is crucial!!
1339
1340 // set the flag telling to the main thread that we want to do some GUI
1341 {
1342 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1343
1344 gs_nWaitingForGui++;
1345 }
1346
1347 wxWakeUpMainThread();
1348
1349 // now we may block here because the main thread will soon let us in
1350 // (during the next iteration of OnIdle())
1351 gs_critsectGui->Enter();
1352 }
1353
1354 void WXDLLEXPORT wxMutexGuiLeave()
1355 {
1356 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1357
1358 if ( wxThread::IsMain() )
1359 {
1360 gs_bGuiOwnedByMainThread = FALSE;
1361 }
1362 else
1363 {
1364 // decrement the number of threads waiting for GUI access now
1365 wxASSERT_MSG( gs_nWaitingForGui > 0,
1366 wxT("calling wxMutexGuiLeave() without entering it first?") );
1367
1368 gs_nWaitingForGui--;
1369
1370 wxWakeUpMainThread();
1371 }
1372
1373 gs_critsectGui->Leave();
1374 }
1375
1376 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1377 {
1378 wxASSERT_MSG( wxThread::IsMain(),
1379 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1380
1381 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1382
1383 if ( gs_nWaitingForGui == 0 )
1384 {
1385 // no threads are waiting for GUI - so we may acquire the lock without
1386 // any danger (but only if we don't already have it)
1387 if ( !wxGuiOwnedByMainThread() )
1388 {
1389 gs_critsectGui->Enter();
1390
1391 gs_bGuiOwnedByMainThread = TRUE;
1392 }
1393 //else: already have it, nothing to do
1394 }
1395 else
1396 {
1397 // some threads are waiting, release the GUI lock if we have it
1398 if ( wxGuiOwnedByMainThread() )
1399 {
1400 wxMutexGuiLeave();
1401 }
1402 //else: some other worker thread is doing GUI
1403 }
1404 }
1405
1406 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1407 {
1408 return gs_bGuiOwnedByMainThread;
1409 }
1410
1411 // wake up the main thread if it's in ::GetMessage()
1412 void WXDLLEXPORT wxWakeUpMainThread()
1413 {
1414 // sending any message would do - hopefully WM_NULL is harmless enough
1415 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
1416 {
1417 // should never happen
1418 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1419 }
1420 }
1421
1422 bool WXDLLEXPORT wxIsWaitingForThread()
1423 {
1424 return gs_waitingForThread;
1425 }
1426
1427 #endif // wxUSE_THREADS
1428
1429 // vi:sts=4:sw=4:et