]> git.saurik.com Git - wxWidgets.git/blame - src/msw/thread.cpp
Various small fixes and tweaks
[wxWidgets.git] / src / msw / thread.cpp
CommitLineData
2bda0e17
KB
1/////////////////////////////////////////////////////////////////////////////
2// Name: thread.cpp
3// Purpose: wxThread Implementation
4// Author: Original from Wolfram Gloger/Guilhem Lavaux
bee503b0 5// Modified by: Vadim Zeitlin to make it work :-)
2bda0e17
KB
6// Created: 04/22/98
7// RCS-ID: $Id$
bee503b0
VZ
8// Copyright: (c) Wolfram Gloger (1996, 1997); Guilhem Lavaux (1998),
9// Vadim Zeitlin (1999)
2bda0e17
KB
10// Licence: wxWindows licence
11/////////////////////////////////////////////////////////////////////////////
12
13#ifdef __GNUG__
3222fde2 14 #pragma implementation "thread.h"
2bda0e17
KB
15#endif
16
3222fde2
VZ
17// ----------------------------------------------------------------------------
18// headers
19// ----------------------------------------------------------------------------
20
a3b46648 21// For compilers that support precompilation, includes "wx.h".
2bda0e17
KB
22#include "wx/wxprec.h"
23
24#if defined(__BORLANDC__)
3222fde2 25 #pragma hdrstop
2bda0e17
KB
26#endif
27
28#ifndef WX_PRECOMP
3222fde2 29 #include "wx/wx.h"
2bda0e17
KB
30#endif
31
3222fde2
VZ
32#if wxUSE_THREADS
33
0d0512bd 34#include "wx/msw/private.h"
3222fde2 35
2bda0e17
KB
36#include "wx/module.h"
37#include "wx/thread.h"
38
b568d04f
VZ
39// must have this symbol defined to get _beginthread/_endthread declarations
40#ifndef _MT
41 #define _MT
42#endif
43
44#ifdef __VISUALC__
45 #include <process.h>
46#endif
47
48// ----------------------------------------------------------------------------
49// constants
50// ----------------------------------------------------------------------------
51
bf1852e1
VZ
52// the possible states of the thread ("=>" shows all possible transitions from
53// this state)
54enum wxThreadState
55{
56 STATE_NEW, // didn't start execution yet (=> RUNNING)
57 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
58 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
59 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
60 STATE_EXITED // thread is terminating
2bda0e17
KB
61};
62
3222fde2 63// ----------------------------------------------------------------------------
b568d04f 64// this module globals
3222fde2 65// ----------------------------------------------------------------------------
2bda0e17 66
bf1852e1 67// TLS index of the slot where we store the pointer to the current thread
b568d04f 68static DWORD gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 69
3222fde2
VZ
70// id of the main thread - the one which can call GUI functions without first
71// calling wxMutexGuiEnter()
b568d04f 72static DWORD gs_idMainThread = 0;
bee503b0
VZ
73
74// if it's FALSE, some secondary thread is holding the GUI lock
b568d04f 75static bool gs_bGuiOwnedByMainThread = TRUE;
2bda0e17 76
3222fde2
VZ
77// critical section which controls access to all GUI functions: any secondary
78// thread (i.e. except the main one) must enter this crit section before doing
79// any GUI calls
b568d04f 80static wxCriticalSection *gs_critsectGui = NULL;
bee503b0 81
b568d04f
VZ
82// critical section which protects gs_nWaitingForGui variable
83static wxCriticalSection *gs_critsectWaitingForGui = NULL;
bee503b0
VZ
84
85// number of threads waiting for GUI in wxMutexGuiEnter()
b568d04f 86static size_t gs_nWaitingForGui = 0;
2bda0e17 87
bf1852e1 88// are we waiting for a thread termination?
b568d04f 89static bool gs_waitingForThread = FALSE;
bf1852e1 90
3222fde2
VZ
91// ============================================================================
92// Windows implementation of thread classes
93// ============================================================================
94
95// ----------------------------------------------------------------------------
96// wxMutex implementation
97// ----------------------------------------------------------------------------
0d0512bd 98
3222fde2
VZ
99class wxMutexInternal
100{
2bda0e17 101public:
3222fde2 102 HANDLE p_mutex;
2bda0e17
KB
103};
104
ee4f8c2a 105wxMutex::wxMutex()
2bda0e17 106{
9fc3ad34
VZ
107 m_internal = new wxMutexInternal;
108 m_internal->p_mutex = CreateMutex(NULL, FALSE, NULL);
109 if ( !m_internal->p_mutex )
3222fde2
VZ
110 {
111 wxLogSysError(_("Can not create mutex."));
112 }
a6b0bd49 113
3222fde2 114 m_locked = 0;
2bda0e17
KB
115}
116
ee4f8c2a 117wxMutex::~wxMutex()
2bda0e17 118{
3222fde2 119 if (m_locked > 0)
223d09f6 120 wxLogDebug(wxT("Warning: freeing a locked mutex (%d locks)."), m_locked);
9fc3ad34 121 CloseHandle(m_internal->p_mutex);
2bda0e17
KB
122}
123
ee4f8c2a 124wxMutexError wxMutex::Lock()
2bda0e17 125{
3222fde2
VZ
126 DWORD ret;
127
9fc3ad34 128 ret = WaitForSingleObject(m_internal->p_mutex, INFINITE);
3222fde2
VZ
129 switch ( ret )
130 {
131 case WAIT_ABANDONED:
132 return wxMUTEX_BUSY;
133
134 case WAIT_OBJECT_0:
135 // ok
136 break;
2bda0e17 137
3222fde2
VZ
138 case WAIT_FAILED:
139 wxLogSysError(_("Couldn't acquire a mutex lock"));
140 return wxMUTEX_MISC_ERROR;
2bda0e17 141
3222fde2
VZ
142 case WAIT_TIMEOUT:
143 default:
223d09f6 144 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
3222fde2
VZ
145 }
146
147 m_locked++;
148 return wxMUTEX_NO_ERROR;
2bda0e17
KB
149}
150
ee4f8c2a 151wxMutexError wxMutex::TryLock()
2bda0e17 152{
3222fde2 153 DWORD ret;
2bda0e17 154
9fc3ad34 155 ret = WaitForSingleObject(m_internal->p_mutex, 0);
3222fde2
VZ
156 if (ret == WAIT_TIMEOUT || ret == WAIT_ABANDONED)
157 return wxMUTEX_BUSY;
2bda0e17 158
3222fde2
VZ
159 m_locked++;
160 return wxMUTEX_NO_ERROR;
2bda0e17
KB
161}
162
ee4f8c2a 163wxMutexError wxMutex::Unlock()
2bda0e17 164{
3222fde2
VZ
165 if (m_locked > 0)
166 m_locked--;
2bda0e17 167
9fc3ad34 168 BOOL ret = ReleaseMutex(m_internal->p_mutex);
3222fde2
VZ
169 if ( ret == 0 )
170 {
171 wxLogSysError(_("Couldn't release a mutex"));
172 return wxMUTEX_MISC_ERROR;
173 }
a6b0bd49 174
3222fde2 175 return wxMUTEX_NO_ERROR;
2bda0e17
KB
176}
177
3222fde2
VZ
178// ----------------------------------------------------------------------------
179// wxCondition implementation
180// ----------------------------------------------------------------------------
181
182class wxConditionInternal
183{
2bda0e17 184public:
b568d04f
VZ
185 wxConditionInternal()
186 {
187 event = ::CreateEvent(
188 NULL, // default secutiry
189 FALSE, // not manual reset
190 FALSE, // nonsignaled initially
191 NULL // nameless event
192 );
193 if ( !event )
194 {
195 wxLogSysError(_("Can not create event object."));
196 }
197 waiters = 0;
198 }
199
9fc3ad34 200 bool Wait(DWORD timeout)
b568d04f 201 {
b568d04f
VZ
202 waiters++;
203
204 // FIXME this should be MsgWaitForMultipleObjects() as well probably
205 DWORD rc = ::WaitForSingleObject(event, timeout);
206
207 waiters--;
b568d04f
VZ
208
209 return rc != WAIT_TIMEOUT;
210 }
211
212 ~wxConditionInternal()
213 {
214 if ( event )
215 {
216 if ( !::CloseHandle(event) )
217 {
218 wxLogLastError("CloseHandle(event)");
219 }
220 }
221 }
222
3222fde2
VZ
223 HANDLE event;
224 int waiters;
2bda0e17
KB
225};
226
ee4f8c2a 227wxCondition::wxCondition()
2bda0e17 228{
9fc3ad34 229 m_internal = new wxConditionInternal;
2bda0e17
KB
230}
231
ee4f8c2a 232wxCondition::~wxCondition()
2bda0e17 233{
9fc3ad34 234 delete m_internal;
2bda0e17
KB
235}
236
9fc3ad34 237void wxCondition::Wait()
2bda0e17 238{
9fc3ad34 239 (void)m_internal->Wait(INFINITE);
2bda0e17
KB
240}
241
9fc3ad34 242bool wxCondition::Wait(unsigned long sec,
2bda0e17
KB
243 unsigned long nsec)
244{
9fc3ad34 245 return m_internal->Wait(sec*1000 + nsec/1000000);
2bda0e17
KB
246}
247
ee4f8c2a 248void wxCondition::Signal()
2bda0e17 249{
b568d04f
VZ
250 // set the event to signaled: if a thread is already waiting on it, it will
251 // be woken up, otherwise the event will remain in the signaled state until
252 // someone waits on it. In any case, the system will return it to a non
253 // signalled state afterwards. If multiple threads are waiting, only one
254 // will be woken up.
9fc3ad34 255 if ( !::SetEvent(m_internal->event) )
b568d04f
VZ
256 {
257 wxLogLastError("SetEvent");
258 }
2bda0e17
KB
259}
260
ee4f8c2a 261void wxCondition::Broadcast()
2bda0e17 262{
b568d04f
VZ
263 // this works because all these threads are already waiting and so each
264 // SetEvent() inside Signal() is really a PulseEvent() because the event
265 // state is immediately returned to non-signaled
9fc3ad34 266 for ( int i = 0; i < m_internal->waiters; i++ )
a6b0bd49 267 {
b568d04f 268 Signal();
a6b0bd49 269 }
2bda0e17
KB
270}
271
3222fde2
VZ
272// ----------------------------------------------------------------------------
273// wxCriticalSection implementation
274// ----------------------------------------------------------------------------
275
3222fde2
VZ
276wxCriticalSection::wxCriticalSection()
277{
b568d04f 278 wxASSERT_MSG( sizeof(CRITICAL_SECTION) <= sizeof(m_buffer),
0d0512bd
VZ
279 _T("must increase buffer size in wx/thread.h") );
280
281 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
3222fde2
VZ
282}
283
284wxCriticalSection::~wxCriticalSection()
285{
0d0512bd 286 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
3222fde2
VZ
287}
288
289void wxCriticalSection::Enter()
290{
0d0512bd 291 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
3222fde2
VZ
292}
293
294void wxCriticalSection::Leave()
295{
0d0512bd 296 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
3222fde2
VZ
297}
298
299// ----------------------------------------------------------------------------
300// wxThread implementation
301// ----------------------------------------------------------------------------
302
bf1852e1
VZ
303// wxThreadInternal class
304// ----------------------
305
3222fde2
VZ
306class wxThreadInternal
307{
2bda0e17 308public:
bf1852e1
VZ
309 wxThreadInternal()
310 {
311 m_hThread = 0;
312 m_state = STATE_NEW;
313 m_priority = WXTHREAD_DEFAULT_PRIORITY;
314 }
315
b568d04f
VZ
316 ~wxThreadInternal()
317 {
318 Free();
319 }
320
321 void Free()
322 {
323 if ( m_hThread )
324 {
325 if ( !::CloseHandle(m_hThread) )
326 {
327 wxLogLastError("CloseHandle(thread)");
328 }
329
330 m_hThread = 0;
331 }
332 }
333
bf1852e1
VZ
334 // create a new (suspended) thread (for the given thread object)
335 bool Create(wxThread *thread);
336
337 // suspend/resume/terminate
338 bool Suspend();
339 bool Resume();
340 void Cancel() { m_state = STATE_CANCELED; }
341
342 // thread state
343 void SetState(wxThreadState state) { m_state = state; }
344 wxThreadState GetState() const { return m_state; }
345
346 // thread priority
b568d04f 347 void SetPriority(unsigned int priority);
bf1852e1
VZ
348 unsigned int GetPriority() const { return m_priority; }
349
350 // thread handle and id
351 HANDLE GetHandle() const { return m_hThread; }
352 DWORD GetId() const { return m_tid; }
353
354 // thread function
bee503b0 355 static DWORD WinThreadStart(wxThread *thread);
2bda0e17 356
bf1852e1
VZ
357private:
358 HANDLE m_hThread; // handle of the thread
359 wxThreadState m_state; // state, see wxThreadState enum
360 unsigned int m_priority; // thread priority in "wx" units
361 DWORD m_tid; // thread id
2bda0e17
KB
362};
363
bee503b0 364DWORD wxThreadInternal::WinThreadStart(wxThread *thread)
2bda0e17 365{
bf1852e1 366 // store the thread object in the TLS
b568d04f 367 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
bf1852e1
VZ
368 {
369 wxLogSysError(_("Can not start thread: error writing TLS."));
370
371 return (DWORD)-1;
372 }
373
b568d04f
VZ
374 DWORD rc = (DWORD)thread->Entry();
375
376 // enter m_critsect before changing the thread state
377 thread->m_critsect.Enter();
9fc3ad34
VZ
378 bool wasCancelled = thread->m_internal->GetState() == STATE_CANCELED;
379 thread->m_internal->SetState(STATE_EXITED);
b568d04f
VZ
380 thread->m_critsect.Leave();
381
bee503b0 382 thread->OnExit();
2bda0e17 383
b568d04f
VZ
384 // if the thread was cancelled (from Delete()), then it the handle is still
385 // needed there
386 if ( thread->IsDetached() && !wasCancelled )
387 {
388 // auto delete
389 delete thread;
390 }
391 //else: the joinable threads handle will be closed when Wait() is done
bf1852e1 392
b568d04f 393 return rc;
2bda0e17
KB
394}
395
b568d04f 396void wxThreadInternal::SetPriority(unsigned int priority)
2bda0e17 397{
b568d04f 398 m_priority = priority;
3222fde2 399
bf1852e1
VZ
400 // translate wxWindows priority to the Windows one
401 int win_priority;
402 if (m_priority <= 20)
403 win_priority = THREAD_PRIORITY_LOWEST;
404 else if (m_priority <= 40)
405 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
406 else if (m_priority <= 60)
407 win_priority = THREAD_PRIORITY_NORMAL;
408 else if (m_priority <= 80)
409 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
410 else if (m_priority <= 100)
411 win_priority = THREAD_PRIORITY_HIGHEST;
3222fde2
VZ
412 else
413 {
223d09f6 414 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
bf1852e1 415 win_priority = THREAD_PRIORITY_NORMAL;
3222fde2
VZ
416 }
417
b568d04f 418 if ( !::SetThreadPriority(m_hThread, win_priority) )
bee503b0
VZ
419 {
420 wxLogSysError(_("Can't set thread priority"));
421 }
b568d04f
VZ
422}
423
424bool wxThreadInternal::Create(wxThread *thread)
425{
426 // for compilers which have it, we should use C RTL function for thread
427 // creation instead of Win32 API one because otherwise we will have memory
428 // leaks if the thread uses C RTL (and most threads do)
429#ifdef __VISUALC__
430 typedef unsigned (__stdcall *RtlThreadStart)(void *);
431
432 m_hThread = (HANDLE)_beginthreadex(NULL, 0,
433 (RtlThreadStart)
434 wxThreadInternal::WinThreadStart,
435 thread, CREATE_SUSPENDED,
436 (unsigned int *)&m_tid);
437#else // !VC++
438 m_hThread = ::CreateThread
439 (
440 NULL, // default security
441 0, // default stack size
442 (LPTHREAD_START_ROUTINE) // thread entry point
443 wxThreadInternal::WinThreadStart, //
444 (LPVOID)thread, // parameter
445 CREATE_SUSPENDED, // flags
446 &m_tid // [out] thread id
447 );
448#endif // VC++/!VC++
449
450 if ( m_hThread == NULL )
451 {
452 wxLogSysError(_("Can't create thread"));
453
454 return FALSE;
455 }
456
457 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
458 {
459 SetPriority(m_priority);
460 }
3222fde2 461
bf1852e1 462 return TRUE;
2bda0e17
KB
463}
464
bf1852e1 465bool wxThreadInternal::Suspend()
2bda0e17 466{
bf1852e1
VZ
467 DWORD nSuspendCount = ::SuspendThread(m_hThread);
468 if ( nSuspendCount == (DWORD)-1 )
bee503b0 469 {
bf1852e1
VZ
470 wxLogSysError(_("Can not suspend thread %x"), m_hThread);
471
472 return FALSE;
bee503b0 473 }
2bda0e17 474
bf1852e1
VZ
475 m_state = STATE_PAUSED;
476
477 return TRUE;
a6b0bd49
VZ
478}
479
bf1852e1 480bool wxThreadInternal::Resume()
a6b0bd49 481{
bf1852e1 482 DWORD nSuspendCount = ::ResumeThread(m_hThread);
a6b0bd49
VZ
483 if ( nSuspendCount == (DWORD)-1 )
484 {
bf1852e1 485 wxLogSysError(_("Can not resume thread %x"), m_hThread);
a6b0bd49 486
bf1852e1 487 return FALSE;
a6b0bd49
VZ
488 }
489
bf1852e1 490 m_state = STATE_RUNNING;
bee503b0 491
bf1852e1 492 return TRUE;
a6b0bd49
VZ
493}
494
bf1852e1
VZ
495// static functions
496// ----------------
497
498wxThread *wxThread::This()
a6b0bd49 499{
b568d04f 500 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
bf1852e1
VZ
501
502 // be careful, 0 may be a valid return value as well
503 if ( !thread && (::GetLastError() != NO_ERROR) )
a6b0bd49 504 {
bf1852e1 505 wxLogSysError(_("Couldn't get the current thread pointer"));
a6b0bd49 506
bf1852e1 507 // return NULL...
a6b0bd49
VZ
508 }
509
bf1852e1
VZ
510 return thread;
511}
512
513bool wxThread::IsMain()
514{
b568d04f 515 return ::GetCurrentThreadId() == gs_idMainThread;
bf1852e1
VZ
516}
517
518void wxThread::Yield()
519{
b568d04f
VZ
520 // 0 argument to Sleep() is special and means to just give away the rest of
521 // our timeslice
bf1852e1
VZ
522 ::Sleep(0);
523}
524
525void wxThread::Sleep(unsigned long milliseconds)
526{
527 ::Sleep(milliseconds);
528}
529
b568d04f
VZ
530// ctor and dtor
531// -------------
532
533wxThread::wxThread(wxThreadKind kind)
534{
9fc3ad34 535 m_internal = new wxThreadInternal();
b568d04f
VZ
536
537 m_isDetached = kind == wxTHREAD_DETACHED;
538}
539
540wxThread::~wxThread()
541{
9fc3ad34 542 delete m_internal;
b568d04f
VZ
543}
544
bf1852e1
VZ
545// create/start thread
546// -------------------
547
548wxThreadError wxThread::Create()
549{
b568d04f
VZ
550 wxCriticalSectionLocker lock(m_critsect);
551
9fc3ad34 552 if ( !m_internal->Create(this) )
bf1852e1 553 return wxTHREAD_NO_RESOURCE;
bee503b0 554
a6b0bd49 555 return wxTHREAD_NO_ERROR;
2bda0e17
KB
556}
557
bf1852e1 558wxThreadError wxThread::Run()
2bda0e17 559{
bf1852e1
VZ
560 wxCriticalSectionLocker lock(m_critsect);
561
9fc3ad34 562 if ( m_internal->GetState() != STATE_NEW )
bf1852e1
VZ
563 {
564 // actually, it may be almost any state at all, not only STATE_RUNNING
565 return wxTHREAD_RUNNING;
566 }
567
b568d04f 568 // the thread has just been created and is still suspended - let it run
bf1852e1 569 return Resume();
2bda0e17
KB
570}
571
bf1852e1
VZ
572// suspend/resume thread
573// ---------------------
574
575wxThreadError wxThread::Pause()
2bda0e17 576{
bf1852e1
VZ
577 wxCriticalSectionLocker lock(m_critsect);
578
9fc3ad34 579 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
580}
581
bf1852e1 582wxThreadError wxThread::Resume()
2bda0e17 583{
bf1852e1
VZ
584 wxCriticalSectionLocker lock(m_critsect);
585
9fc3ad34 586 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
587}
588
bf1852e1
VZ
589// stopping thread
590// ---------------
591
b568d04f
VZ
592wxThread::ExitCode wxThread::Wait()
593{
594 // although under Windows we can wait for any thread, it's an error to
595 // wait for a detached one in wxWin API
596 wxCHECK_MSG( !IsDetached(), (ExitCode)-1,
597 _T("can't wait for detached thread") );
598
599 ExitCode rc = (ExitCode)-1;
600
601 (void)Delete(&rc);
602
9fc3ad34 603 m_internal->Free();
b568d04f
VZ
604
605 return rc;
606}
607
608wxThreadError wxThread::Delete(ExitCode *pRc)
2bda0e17 609{
bf1852e1
VZ
610 ExitCode rc = 0;
611
612 // Delete() is always safe to call, so consider all possible states
613 if ( IsPaused() )
614 Resume();
615
9fc3ad34 616 HANDLE hThread = m_internal->GetHandle();
b568d04f 617
bf1852e1
VZ
618 if ( IsRunning() )
619 {
620 if ( IsMain() )
621 {
622 // set flag for wxIsWaitingForThread()
b568d04f 623 gs_waitingForThread = TRUE;
bf1852e1 624
b568d04f 625#if wxUSE_GUI
bf1852e1 626 wxBeginBusyCursor();
b568d04f 627#endif // wxUSE_GUI
bf1852e1
VZ
628 }
629
b568d04f 630 // ask the thread to terminate
bf1852e1
VZ
631 {
632 wxCriticalSectionLocker lock(m_critsect);
633
9fc3ad34 634 m_internal->Cancel();
bf1852e1
VZ
635 }
636
b568d04f 637#if wxUSE_GUI
bf1852e1
VZ
638 // we can't just wait for the thread to terminate because it might be
639 // calling some GUI functions and so it will never terminate before we
640 // process the Windows messages that result from these functions
641 DWORD result;
642 do
643 {
644 result = ::MsgWaitForMultipleObjects
645 (
646 1, // number of objects to wait for
647 &hThread, // the objects
648 FALSE, // don't wait for all objects
649 INFINITE, // no timeout
650 QS_ALLEVENTS // return as soon as there are any events
651 );
652
653 switch ( result )
654 {
655 case 0xFFFFFFFF:
656 // error
657 wxLogSysError(_("Can not wait for thread termination"));
658 Kill();
b568d04f 659 return wxTHREAD_KILLED;
bf1852e1
VZ
660
661 case WAIT_OBJECT_0:
662 // thread we're waiting for terminated
663 break;
664
665 case WAIT_OBJECT_0 + 1:
666 // new message arrived, process it
667 if ( !wxTheApp->DoMessage() )
668 {
669 // WM_QUIT received: kill the thread
670 Kill();
671
b568d04f 672 return wxTHREAD_KILLED;
bf1852e1
VZ
673 }
674
675 if ( IsMain() )
676 {
677 // give the thread we're waiting for chance to exit
678 // from the GUI call it might have been in
b568d04f 679 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
bf1852e1
VZ
680 {
681 wxMutexGuiLeave();
682 }
683 }
684
685 break;
686
687 default:
223d09f6 688 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
bf1852e1
VZ
689 }
690 } while ( result != WAIT_OBJECT_0 );
b568d04f
VZ
691#else // !wxUSE_GUI
692 // simply wait for the thread to terminate
693 //
694 // OTOH, even console apps create windows (in wxExecute, for WinSock
695 // &c), so may be use MsgWaitForMultipleObject() too here?
696 if ( WaitForSingleObject(hThread, INFINITE) != WAIT_OBJECT_0 )
697 {
698 wxFAIL_MSG(wxT("unexpected result of WaitForSingleObject"));
699 }
700#endif // wxUSE_GUI/!wxUSE_GUI
bf1852e1
VZ
701
702 if ( IsMain() )
703 {
b568d04f 704 gs_waitingForThread = FALSE;
bf1852e1 705
b568d04f 706#if wxUSE_GUI
bf1852e1 707 wxEndBusyCursor();
b568d04f 708#endif // wxUSE_GUI
bf1852e1 709 }
b568d04f 710 }
bf1852e1 711
b568d04f
VZ
712 if ( !::GetExitCodeThread(hThread, (LPDWORD)&rc) )
713 {
714 wxLogLastError("GetExitCodeThread");
bf1852e1 715
b568d04f
VZ
716 rc = (ExitCode)-1;
717 }
bf1852e1 718
b568d04f
VZ
719 if ( IsDetached() )
720 {
721 // if the thread exits normally, this is done in WinThreadStart, but in
722 // this case it would have been too early because
723 // MsgWaitForMultipleObject() would fail if the therad handle was
724 // closed while we were waiting on it, so we must do it here
725 delete this;
bf1852e1
VZ
726 }
727
b568d04f
VZ
728 wxASSERT_MSG( (DWORD)rc != STILL_ACTIVE,
729 wxT("thread must be already terminated.") );
730
731 if ( pRc )
732 *pRc = rc;
733
734 return rc == (ExitCode)-1 ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
2bda0e17
KB
735}
736
bf1852e1 737wxThreadError wxThread::Kill()
2bda0e17 738{
bf1852e1
VZ
739 if ( !IsRunning() )
740 return wxTHREAD_NOT_RUNNING;
741
9fc3ad34 742 if ( !::TerminateThread(m_internal->GetHandle(), (DWORD)-1) )
bf1852e1
VZ
743 {
744 wxLogSysError(_("Couldn't terminate thread"));
745
746 return wxTHREAD_MISC_ERROR;
747 }
748
9fc3ad34 749 m_internal->Free();
b568d04f
VZ
750
751 if ( IsDetached() )
752 {
753 delete this;
754 }
bf1852e1
VZ
755
756 return wxTHREAD_NO_ERROR;
2bda0e17
KB
757}
758
b568d04f 759void wxThread::Exit(ExitCode status)
2bda0e17 760{
9fc3ad34 761 m_internal->Free();
2bda0e17 762
b568d04f
VZ
763 if ( IsDetached() )
764 {
765 delete this;
766 }
767
768#ifdef __VISUALC__
769 _endthreadex((unsigned)status);
770#else // !VC++
bf1852e1 771 ::ExitThread((DWORD)status);
b568d04f 772#endif // VC++/!VC++
2bda0e17 773
223d09f6 774 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
bf1852e1 775}
2bda0e17 776
b568d04f
VZ
777// priority setting
778// ----------------
779
bf1852e1
VZ
780void wxThread::SetPriority(unsigned int prio)
781{
782 wxCriticalSectionLocker lock(m_critsect);
783
9fc3ad34 784 m_internal->SetPriority(prio);
bf1852e1 785}
2bda0e17 786
bf1852e1
VZ
787unsigned int wxThread::GetPriority() const
788{
b568d04f 789 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
2bda0e17 790
9fc3ad34 791 return m_internal->GetPriority();
2bda0e17
KB
792}
793
b568d04f 794unsigned long wxThread::GetId() const
2bda0e17 795{
b568d04f 796 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 797
9fc3ad34 798 return (unsigned long)m_internal->GetId();
2bda0e17
KB
799}
800
72fd19a1
JS
801bool wxThread::IsRunning() const
802{
b568d04f 803 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 804
9fc3ad34 805 return m_internal->GetState() == STATE_RUNNING;
72fd19a1
JS
806}
807
808bool wxThread::IsAlive() const
809{
b568d04f 810 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 811
9fc3ad34
VZ
812 return (m_internal->GetState() == STATE_RUNNING) ||
813 (m_internal->GetState() == STATE_PAUSED);
72fd19a1
JS
814}
815
a737331d
GL
816bool wxThread::IsPaused() const
817{
b568d04f 818 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
a737331d 819
9fc3ad34 820 return m_internal->GetState() == STATE_PAUSED;
a737331d
GL
821}
822
8c10faf1 823bool wxThread::TestDestroy()
2bda0e17 824{
b568d04f 825 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); // const_cast
bf1852e1 826
9fc3ad34 827 return m_internal->GetState() == STATE_CANCELED;
2bda0e17
KB
828}
829
3222fde2
VZ
830// ----------------------------------------------------------------------------
831// Automatic initialization for thread module
832// ----------------------------------------------------------------------------
2bda0e17 833
3222fde2 834class wxThreadModule : public wxModule
a6b0bd49 835{
3222fde2
VZ
836public:
837 virtual bool OnInit();
838 virtual void OnExit();
d524867f 839
3222fde2
VZ
840private:
841 DECLARE_DYNAMIC_CLASS(wxThreadModule)
842};
d524867f
RR
843
844IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
845
3222fde2 846bool wxThreadModule::OnInit()
d524867f 847{
bf1852e1 848 // allocate TLS index for storing the pointer to the current thread
b568d04f
VZ
849 gs_tlsThisThread = ::TlsAlloc();
850 if ( gs_tlsThisThread == 0xFFFFFFFF )
bf1852e1
VZ
851 {
852 // in normal circumstances it will only happen if all other
853 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
854 // words, this should never happen
855 wxLogSysError(_("Thread module initialization failed: "
856 "impossible to allocate index in thread "
857 "local storage"));
858
859 return FALSE;
860 }
861
862 // main thread doesn't have associated wxThread object, so store 0 in the
863 // TLS instead
b568d04f 864 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
bf1852e1 865 {
b568d04f
VZ
866 ::TlsFree(gs_tlsThisThread);
867 gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1
VZ
868
869 wxLogSysError(_("Thread module initialization failed: "
870 "can not store value in thread local storage"));
871
872 return FALSE;
873 }
874
b568d04f 875 gs_critsectWaitingForGui = new wxCriticalSection();
bee503b0 876
b568d04f
VZ
877 gs_critsectGui = new wxCriticalSection();
878 gs_critsectGui->Enter();
bee503b0 879
bf1852e1 880 // no error return for GetCurrentThreadId()
b568d04f 881 gs_idMainThread = ::GetCurrentThreadId();
3222fde2 882
d524867f
RR
883 return TRUE;
884}
885
3222fde2 886void wxThreadModule::OnExit()
d524867f 887{
b568d04f 888 if ( !::TlsFree(gs_tlsThisThread) )
bf1852e1
VZ
889 {
890 wxLogLastError("TlsFree failed.");
891 }
892
b568d04f 893 if ( gs_critsectGui )
3222fde2 894 {
b568d04f
VZ
895 gs_critsectGui->Leave();
896 delete gs_critsectGui;
897 gs_critsectGui = NULL;
3222fde2 898 }
bee503b0 899
b568d04f
VZ
900 delete gs_critsectWaitingForGui;
901 gs_critsectWaitingForGui = NULL;
3222fde2
VZ
902}
903
bee503b0 904// ----------------------------------------------------------------------------
b568d04f 905// under Windows, these functions are implemented using a critical section and
3222fde2 906// not a mutex, so the names are a bit confusing
bee503b0
VZ
907// ----------------------------------------------------------------------------
908
3222fde2
VZ
909void WXDLLEXPORT wxMutexGuiEnter()
910{
bee503b0
VZ
911 // this would dead lock everything...
912 wxASSERT_MSG( !wxThread::IsMain(),
223d09f6 913 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
bee503b0
VZ
914
915 // the order in which we enter the critical sections here is crucial!!
916
917 // set the flag telling to the main thread that we want to do some GUI
918 {
b568d04f 919 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 920
b568d04f 921 gs_nWaitingForGui++;
bee503b0
VZ
922 }
923
924 wxWakeUpMainThread();
925
926 // now we may block here because the main thread will soon let us in
927 // (during the next iteration of OnIdle())
b568d04f 928 gs_critsectGui->Enter();
3222fde2
VZ
929}
930
931void WXDLLEXPORT wxMutexGuiLeave()
932{
b568d04f 933 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0
VZ
934
935 if ( wxThread::IsMain() )
936 {
b568d04f 937 gs_bGuiOwnedByMainThread = FALSE;
bee503b0
VZ
938 }
939 else
940 {
941 // decrement the number of waiters now
b568d04f 942 wxASSERT_MSG( gs_nWaitingForGui > 0,
223d09f6 943 wxT("calling wxMutexGuiLeave() without entering it first?") );
bee503b0 944
b568d04f 945 gs_nWaitingForGui--;
bee503b0
VZ
946
947 wxWakeUpMainThread();
948 }
949
b568d04f 950 gs_critsectGui->Leave();
bee503b0
VZ
951}
952
953void WXDLLEXPORT wxMutexGuiLeaveOrEnter()
954{
955 wxASSERT_MSG( wxThread::IsMain(),
223d09f6 956 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
bee503b0 957
b568d04f 958 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 959
b568d04f 960 if ( gs_nWaitingForGui == 0 )
bee503b0
VZ
961 {
962 // no threads are waiting for GUI - so we may acquire the lock without
963 // any danger (but only if we don't already have it)
964 if ( !wxGuiOwnedByMainThread() )
965 {
b568d04f 966 gs_critsectGui->Enter();
bee503b0 967
b568d04f 968 gs_bGuiOwnedByMainThread = TRUE;
bee503b0
VZ
969 }
970 //else: already have it, nothing to do
971 }
972 else
973 {
974 // some threads are waiting, release the GUI lock if we have it
975 if ( wxGuiOwnedByMainThread() )
976 {
977 wxMutexGuiLeave();
978 }
979 //else: some other worker thread is doing GUI
980 }
981}
982
983bool WXDLLEXPORT wxGuiOwnedByMainThread()
984{
b568d04f 985 return gs_bGuiOwnedByMainThread;
bee503b0
VZ
986}
987
988// wake up the main thread if it's in ::GetMessage()
989void WXDLLEXPORT wxWakeUpMainThread()
990{
991 // sending any message would do - hopefully WM_NULL is harmless enough
b568d04f 992 if ( !::PostThreadMessage(gs_idMainThread, WM_NULL, 0, 0) )
bee503b0
VZ
993 {
994 // should never happen
995 wxLogLastError("PostThreadMessage(WM_NULL)");
996 }
3222fde2 997}
d524867f 998
bf1852e1
VZ
999bool WXDLLEXPORT wxIsWaitingForThread()
1000{
b568d04f 1001 return gs_waitingForThread;
bf1852e1
VZ
1002}
1003
3222fde2 1004#endif // wxUSE_THREADS