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