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