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