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