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