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