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