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