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