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