]> git.saurik.com Git - wxWidgets.git/blob - src/msw/thread.cpp
Changes needed to allow compilation with SunCC.
[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(m_buffer),
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 #if wxUSE_GUI
976 wxBeginBusyCursor();
977 #endif // wxUSE_GUI
978 }
979
980 // ask the thread to terminate
981 if ( shouldCancel )
982 {
983 wxCriticalSectionLocker lock(m_critsect);
984
985 m_internal->Cancel();
986 }
987
988 #if wxUSE_GUI
989 // we can't just wait for the thread to terminate because it might be
990 // calling some GUI functions and so it will never terminate before we
991 // process the Windows messages that result from these functions
992 DWORD result;
993 do
994 {
995 result = ::MsgWaitForMultipleObjects
996 (
997 1, // number of objects to wait for
998 &hThread, // the objects
999 FALSE, // don't wait for all objects
1000 INFINITE, // no timeout
1001 QS_ALLEVENTS // return as soon as there are any events
1002 );
1003
1004 switch ( result )
1005 {
1006 case 0xFFFFFFFF:
1007 // error
1008 wxLogSysError(_("Can not wait for thread termination"));
1009 Kill();
1010 return wxTHREAD_KILLED;
1011
1012 case WAIT_OBJECT_0:
1013 // thread we're waiting for terminated
1014 break;
1015
1016 case WAIT_OBJECT_0 + 1:
1017 // new message arrived, process it
1018 if ( !wxTheApp->DoMessage() )
1019 {
1020 // WM_QUIT received: kill the thread
1021 Kill();
1022
1023 return wxTHREAD_KILLED;
1024 }
1025
1026 if ( IsMain() )
1027 {
1028 // give the thread we're waiting for chance to exit
1029 // from the GUI call it might have been in
1030 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
1031 {
1032 wxMutexGuiLeave();
1033 }
1034 }
1035
1036 break;
1037
1038 default:
1039 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
1040 }
1041 } while ( result != WAIT_OBJECT_0 );
1042 #else // !wxUSE_GUI
1043 // simply wait for the thread to terminate
1044 //
1045 // OTOH, even console apps create windows (in wxExecute, for WinSock
1046 // &c), so may be use MsgWaitForMultipleObject() too here?
1047 if ( WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0 )
1048 {
1049 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
1050 }
1051 #endif // wxUSE_GUI/!wxUSE_GUI
1052
1053 if ( IsMain() )
1054 {
1055 gs_waitingForThread = FALSE;
1056
1057 #if wxUSE_GUI
1058 wxEndBusyCursor();
1059 #endif // wxUSE_GUI
1060 }
1061 }
1062
1063 // although the thread might be already in the EXITED state it might not
1064 // have terminated yet and so we are not sure that it has actually
1065 // terminated if the "if" above hadn't been taken
1066 do
1067 {
1068 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
1069 {
1070 wxLogLastError(wxT("GetExitCodeThread"));
1071
1072 rc = (ExitCode)-1;
1073 }
1074 } while ( (DWORD)rc == STILL_ACTIVE );
1075
1076 if ( IsDetached() )
1077 {
1078 // if the thread exits normally, this is done in WinThreadStart, but in
1079 // this case it would have been too early because
1080 // MsgWaitForMultipleObject() would fail if the thread handle was
1081 // closed while we were waiting on it, so we must do it here
1082 delete this;
1083 }
1084
1085 if ( pRc )
1086 *pRc = rc;
1087
1088 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
1089 }
1090
1091 wxThreadError wxThread::Kill()
1092 {
1093 if ( !IsRunning() )
1094 return wxTHREAD_NOT_RUNNING;
1095
1096 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
1097 {
1098 wxLogSysError(_("Couldn't terminate thread"));
1099
1100 return wxTHREAD_MISC_ERROR;
1101 }
1102
1103 m_internal->Free();
1104
1105 if ( IsDetached() )
1106 {
1107 delete this;
1108 }
1109
1110 return wxTHREAD_NO_ERROR;
1111 }
1112
1113 void wxThread::Exit(ExitCode status)
1114 {
1115 m_internal->Free();
1116
1117 if ( IsDetached() )
1118 {
1119 delete this;
1120 }
1121
1122 #ifdef wxUSE_BEGIN_THREAD
1123 _endthreadex((unsigned)status);
1124 #else // !VC++
1125 ::ExitThread((DWORD)status);
1126 #endif // VC++/!VC++
1127
1128 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
1129 }
1130
1131 // priority setting
1132 // ----------------
1133
1134 void wxThread::SetPriority(unsigned int prio)
1135 {
1136 wxCriticalSectionLocker lock(m_critsect);
1137
1138 m_internal->SetPriority(prio);
1139 }
1140
1141 unsigned int wxThread::GetPriority() const
1142 {
1143 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1144
1145 return m_internal->GetPriority();
1146 }
1147
1148 unsigned long wxThread::GetId() const
1149 {
1150 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1151
1152 return (unsigned long)m_internal->GetId();
1153 }
1154
1155 bool wxThread::IsRunning() const
1156 {
1157 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1158
1159 return m_internal->GetState() == STATE_RUNNING;
1160 }
1161
1162 bool wxThread::IsAlive() const
1163 {
1164 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1165
1166 return (m_internal->GetState() == STATE_RUNNING) ||
1167 (m_internal->GetState() == STATE_PAUSED);
1168 }
1169
1170 bool wxThread::IsPaused() const
1171 {
1172 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1173
1174 return m_internal->GetState() == STATE_PAUSED;
1175 }
1176
1177 bool wxThread::TestDestroy()
1178 {
1179 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
1180
1181 return m_internal->GetState() == STATE_CANCELED;
1182 }
1183
1184 // ----------------------------------------------------------------------------
1185 // Automatic initialization for thread module
1186 // ----------------------------------------------------------------------------
1187
1188 class wxThreadModule : public wxModule
1189 {
1190 public:
1191 virtual bool OnInit();
1192 virtual void OnExit();
1193
1194 private:
1195 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1196 };
1197
1198 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1199
1200 bool wxThreadModule::OnInit()
1201 {
1202 // allocate TLS index for storing the pointer to the current thread
1203 gs_tlsThisThread = ::TlsAlloc();
1204 if ( gs_tlsThisThread == 0xFFFFFFFF )
1205 {
1206 // in normal circumstances it will only happen if all other
1207 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1208 // words, this should never happen
1209 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
1210
1211 return FALSE;
1212 }
1213
1214 // main thread doesn't have associated wxThread object, so store 0 in the
1215 // TLS instead
1216 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
1217 {
1218 ::TlsFree(gs_tlsThisThread);
1219 gs_tlsThisThread = 0xFFFFFFFF;
1220
1221 wxLogSysError(_("Thread module initialization failed: can not store value in thread local storage"));
1222
1223 return FALSE;
1224 }
1225
1226 gs_critsectWaitingForGui = new wxCriticalSection();
1227
1228 gs_critsectGui = new wxCriticalSection();
1229 gs_critsectGui->Enter();
1230
1231 // no error return for GetCurrentThreadId()
1232 gs_idMainThread = ::GetCurrentThreadId();
1233
1234 return TRUE;
1235 }
1236
1237 void wxThreadModule::OnExit()
1238 {
1239 if ( !::TlsFree(gs_tlsThisThread) )
1240 {
1241 wxLogLastError(wxT("TlsFree failed."));
1242 }
1243
1244 if ( gs_critsectGui )
1245 {
1246 gs_critsectGui->Leave();
1247 delete gs_critsectGui;
1248 gs_critsectGui = NULL;
1249 }
1250
1251 delete gs_critsectWaitingForGui;
1252 gs_critsectWaitingForGui = NULL;
1253 }
1254
1255 // ----------------------------------------------------------------------------
1256 // under Windows, these functions are implemented using a critical section and
1257 // not a mutex, so the names are a bit confusing
1258 // ----------------------------------------------------------------------------
1259
1260 void WXDLLEXPORT wxMutexGuiEnter()
1261 {
1262 // this would dead lock everything...
1263 wxASSERT_MSG( !wxThread::IsMain(),
1264 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
1265
1266 // the order in which we enter the critical sections here is crucial!!
1267
1268 // set the flag telling to the main thread that we want to do some GUI
1269 {
1270 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1271
1272 gs_nWaitingForGui++;
1273 }
1274
1275 wxWakeUpMainThread();
1276
1277 // now we may block here because the main thread will soon let us in
1278 // (during the next iteration of OnIdle())
1279 gs_critsectGui->Enter();
1280 }
1281
1282 void WXDLLEXPORT wxMutexGuiLeave()
1283 {
1284 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1285
1286 if ( wxThread::IsMain() )
1287 {
1288 gs_bGuiOwnedByMainThread = FALSE;
1289 }
1290 else
1291 {
1292 // decrement the number of threads waiting for GUI access now
1293 wxASSERT_MSG( gs_nWaitingForGui > 0,
1294 wxT("calling wxMutexGuiLeave() without entering it first?") );
1295
1296 gs_nWaitingForGui--;
1297
1298 wxWakeUpMainThread();
1299 }
1300
1301 gs_critsectGui->Leave();
1302 }
1303
1304 void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
1305 {
1306 wxASSERT_MSG( wxThread::IsMain(),
1307 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
1308
1309 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
1310
1311 if ( gs_nWaitingForGui == 0 )
1312 {
1313 // no threads are waiting for GUI - so we may acquire the lock without
1314 // any danger (but only if we don't already have it)
1315 if ( !wxGuiOwnedByMainThread() )
1316 {
1317 gs_critsectGui->Enter();
1318
1319 gs_bGuiOwnedByMainThread = TRUE;
1320 }
1321 //else: already have it, nothing to do
1322 }
1323 else
1324 {
1325 // some threads are waiting, release the GUI lock if we have it
1326 if ( wxGuiOwnedByMainThread() )
1327 {
1328 wxMutexGuiLeave();
1329 }
1330 //else: some other worker thread is doing GUI
1331 }
1332 }
1333
1334 bool WXDLLEXPORT wxGuiOwnedByMainThread()
1335 {
1336 return gs_bGuiOwnedByMainThread;
1337 }
1338
1339 // wake up the main thread if it's in ::GetMessage()
1340 void WXDLLEXPORT wxWakeUpMainThread()
1341 {
1342 // sending any message would do - hopefully WM_NULL is harmless enough
1343 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
1344 {
1345 // should never happen
1346 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
1347 }
1348 }
1349
1350 bool WXDLLEXPORT wxIsWaitingForThread()
1351 {
1352 return gs_waitingForThread;
1353 }
1354
1355 // ----------------------------------------------------------------------------
1356 // include common implementation code
1357 // ----------------------------------------------------------------------------
1358
1359 #include "wx/thrimpl.cpp"
1360
1361 #endif // wxUSE_THREADS
1362