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