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