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