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