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