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