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