]> git.saurik.com Git - wxWidgets.git/blame - src/msw/thread.cpp
fixing osx_cocoa
[wxWidgets.git] / src / msw / thread.cpp
CommitLineData
2bda0e17 1/////////////////////////////////////////////////////////////////////////////
9e84b847 2// Name: src/msw/thread.cpp
2bda0e17
KB
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$
9e84b847
VZ
8// Copyright: (c) Wolfram Gloger (1996, 1997), Guilhem Lavaux (1998);
9// Vadim Zeitlin (1999-2002)
65571936 10// Licence: wxWindows licence
2bda0e17
KB
11/////////////////////////////////////////////////////////////////////////////
12
3222fde2
VZ
13// ----------------------------------------------------------------------------
14// headers
15// ----------------------------------------------------------------------------
16
a3b46648 17// For compilers that support precompilation, includes "wx.h".
2bda0e17
KB
18#include "wx/wxprec.h"
19
20#if defined(__BORLANDC__)
3222fde2 21 #pragma hdrstop
2bda0e17
KB
22#endif
23
670f9935
WS
24#if wxUSE_THREADS
25
26#include "wx/thread.h"
27
2bda0e17 28#ifndef WX_PRECOMP
60ab3272
VS
29 #include "wx/intl.h"
30 #include "wx/app.h"
02761f6c 31 #include "wx/module.h"
2bda0e17
KB
32#endif
33
e2478fde 34#include "wx/apptrait.h"
d3f8206c 35#include "wx/scopeguard.h"
e2478fde 36
0d0512bd 37#include "wx/msw/private.h"
a6c2e2c7 38#include "wx/msw/missing.h"
d3f8206c 39#include "wx/msw/seh.h"
3222fde2 40
d3f8206c 41#include "wx/except.h"
2bda0e17 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 64 (defined(__GNUG__) && defined(__MSVCRT__)) || \
ba14d986 65 defined(__WATCOMC__) || defined(__MWERKS__)
ccebc98a 66
4676948b 67#ifndef __WXWINCE__
9f51f2b6
VZ
68 #undef wxUSE_BEGIN_THREAD
69 #define wxUSE_BEGIN_THREAD
8536082d
BJ
70#endif
71
4676948b
JS
72#endif
73
9f51f2b6
VZ
74#ifdef wxUSE_BEGIN_THREAD
75 // this is where _beginthreadex() is declared
b568d04f 76 #include <process.h>
9f51f2b6 77
d79c9c67
VZ
78 // the return type of the thread function entry point: notice that this
79 // type can't hold a pointer under Win64
80 typedef unsigned THREAD_RETVAL;
9f51f2b6
VZ
81
82 // the calling convention of the thread function entry point
83 #define THREAD_CALLCONV __stdcall
84#else
85 // the settings for CreateThread()
86 typedef DWORD THREAD_RETVAL;
87 #define THREAD_CALLCONV WINAPI
b568d04f
VZ
88#endif
89
3f49efdb
VZ
90static const THREAD_RETVAL THREAD_ERROR_EXIT = (THREAD_RETVAL)-1;
91
b568d04f
VZ
92// ----------------------------------------------------------------------------
93// constants
94// ----------------------------------------------------------------------------
95
bf1852e1
VZ
96// the possible states of the thread ("=>" shows all possible transitions from
97// this state)
98enum wxThreadState
99{
100 STATE_NEW, // didn't start execution yet (=> RUNNING)
101 STATE_RUNNING, // thread is running (=> PAUSED, CANCELED)
102 STATE_PAUSED, // thread is temporarily suspended (=> RUNNING)
103 STATE_CANCELED, // thread should terminate a.s.a.p. (=> EXITED)
104 STATE_EXITED // thread is terminating
2bda0e17
KB
105};
106
3222fde2 107// ----------------------------------------------------------------------------
b568d04f 108// this module globals
3222fde2 109// ----------------------------------------------------------------------------
2bda0e17 110
bf1852e1 111// TLS index of the slot where we store the pointer to the current thread
b568d04f 112static DWORD gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 113
3222fde2
VZ
114// id of the main thread - the one which can call GUI functions without first
115// calling wxMutexGuiEnter()
f9226383 116wxThreadIdType wxThread::ms_idMainThread = 0;
bee503b0 117
3ef22a5b
VZ
118// if it's false, some secondary thread is holding the GUI lock
119static bool gs_bGuiOwnedByMainThread = true;
2bda0e17 120
3222fde2
VZ
121// critical section which controls access to all GUI functions: any secondary
122// thread (i.e. except the main one) must enter this crit section before doing
123// any GUI calls
b568d04f 124static wxCriticalSection *gs_critsectGui = NULL;
bee503b0 125
b568d04f
VZ
126// critical section which protects gs_nWaitingForGui variable
127static wxCriticalSection *gs_critsectWaitingForGui = NULL;
bee503b0 128
3ef22a5b
VZ
129// critical section which serializes WinThreadStart() and WaitForTerminate()
130// (this is a potential bottleneck, we use a single crit sect for all threads
131// in the system, but normally time spent inside it should be quite short)
132static wxCriticalSection *gs_critsectThreadDelete = NULL;
133
bee503b0 134// number of threads waiting for GUI in wxMutexGuiEnter()
b568d04f 135static size_t gs_nWaitingForGui = 0;
2bda0e17 136
bf1852e1 137// are we waiting for a thread termination?
3ef22a5b 138static bool gs_waitingForThread = false;
bf1852e1 139
3222fde2 140// ============================================================================
9e84b847 141// Windows implementation of thread and related classes
3222fde2
VZ
142// ============================================================================
143
144// ----------------------------------------------------------------------------
9e84b847
VZ
145// wxCriticalSection
146// ----------------------------------------------------------------------------
147
3ad41c28 148wxCriticalSection::wxCriticalSection( wxCriticalSectionType WXUNUSED(critSecType) )
9e84b847 149{
1c6f2414
WS
150 wxCOMPILE_TIME_ASSERT( sizeof(CRITICAL_SECTION) <= sizeof(wxCritSectBuffer),
151 wxCriticalSectionBufferTooSmall );
152
9e84b847
VZ
153 ::InitializeCriticalSection((CRITICAL_SECTION *)m_buffer);
154}
155
156wxCriticalSection::~wxCriticalSection()
157{
158 ::DeleteCriticalSection((CRITICAL_SECTION *)m_buffer);
159}
160
161void wxCriticalSection::Enter()
162{
163 ::EnterCriticalSection((CRITICAL_SECTION *)m_buffer);
164}
165
166void wxCriticalSection::Leave()
167{
168 ::LeaveCriticalSection((CRITICAL_SECTION *)m_buffer);
169}
170
171// ----------------------------------------------------------------------------
172// wxMutex
3222fde2 173// ----------------------------------------------------------------------------
0d0512bd 174
3222fde2
VZ
175class wxMutexInternal
176{
2bda0e17 177public:
9e84b847
VZ
178 wxMutexInternal(wxMutexType mutexType);
179 ~wxMutexInternal();
7f684264 180
9e84b847
VZ
181 bool IsOk() const { return m_mutex != NULL; }
182
183 wxMutexError Lock() { return LockTimeout(INFINITE); }
696d13ee
VZ
184 wxMutexError Lock(unsigned long ms) { return LockTimeout(ms); }
185 wxMutexError TryLock();
9e84b847
VZ
186 wxMutexError Unlock();
187
188private:
189 wxMutexError LockTimeout(DWORD milliseconds);
7f684264 190
7f684264 191 HANDLE m_mutex;
1654ef4c 192
424c9ce7 193 unsigned long m_owningThread;
424c9ce7 194 wxMutexType m_type;
22f3361e 195
c0c133e1 196 wxDECLARE_NO_COPY_CLASS(wxMutexInternal);
2bda0e17
KB
197};
198
9e84b847 199// all mutexes are recursive under Win32 so we don't use mutexType
424c9ce7 200wxMutexInternal::wxMutexInternal(wxMutexType mutexType)
2bda0e17 201{
9e84b847
VZ
202 // create a nameless (hence intra process and always private) mutex
203 m_mutex = ::CreateMutex
204 (
205 NULL, // default secutiry attributes
696d13ee 206 FALSE, // not initially locked
9e84b847
VZ
207 NULL // no name
208 );
a6b0bd49 209
424c9ce7
RR
210 m_type = mutexType;
211 m_owningThread = 0;
424c9ce7 212
9e84b847
VZ
213 if ( !m_mutex )
214 {
9a83f860 215 wxLogLastError(wxT("CreateMutex()"));
9e84b847 216 }
1654ef4c 217
2bda0e17
KB
218}
219
9e84b847 220wxMutexInternal::~wxMutexInternal()
2bda0e17 221{
9e84b847 222 if ( m_mutex )
7f684264 223 {
9e84b847
VZ
224 if ( !::CloseHandle(m_mutex) )
225 {
9a83f860 226 wxLogLastError(wxT("CloseHandle(mutex)"));
9e84b847 227 }
7f684264 228 }
2bda0e17
KB
229}
230
696d13ee
VZ
231wxMutexError wxMutexInternal::TryLock()
232{
233 const wxMutexError rc = LockTimeout(0);
234
235 // we have a special return code for timeout in this case
236 return rc == wxMUTEX_TIMEOUT ? wxMUTEX_BUSY : rc;
237}
238
9e84b847 239wxMutexError wxMutexInternal::LockTimeout(DWORD milliseconds)
2bda0e17 240{
424c9ce7
RR
241 if (m_type == wxMUTEX_DEFAULT)
242 {
243 // Don't allow recursive
375f364e 244 if (m_owningThread != 0)
424c9ce7
RR
245 {
246 if (m_owningThread == wxThread::GetCurrentId())
247 return wxMUTEX_DEAD_LOCK;
248 }
249 }
250
9e84b847 251 DWORD rc = ::WaitForSingleObject(m_mutex, milliseconds);
9e84b847
VZ
252 switch ( rc )
253 {
1654ef4c
VZ
254 case WAIT_ABANDONED:
255 // the previous caller died without releasing the mutex, so even
256 // though we did get it, log a message about this
9a83f860 257 wxLogDebug(wxT("WaitForSingleObject() returned WAIT_ABANDONED"));
1654ef4c
VZ
258 // fall through
259
3222fde2
VZ
260 case WAIT_OBJECT_0:
261 // ok
262 break;
2bda0e17 263
3222fde2 264 case WAIT_TIMEOUT:
696d13ee 265 return wxMUTEX_TIMEOUT;
9e84b847 266
3222fde2 267 default:
223d09f6 268 wxFAIL_MSG(wxT("impossible return value in wxMutex::Lock"));
9e84b847 269 // fall through
3222fde2 270
9e84b847 271 case WAIT_FAILED:
9a83f860 272 wxLogLastError(wxT("WaitForSingleObject(mutex)"));
9e84b847
VZ
273 return wxMUTEX_MISC_ERROR;
274 }
2bda0e17 275
424c9ce7 276 if (m_type == wxMUTEX_DEFAULT)
1654ef4c 277 {
424c9ce7 278 // required for checking recursiveness
424c9ce7
RR
279 m_owningThread = wxThread::GetCurrentId();
280 }
1654ef4c 281
3222fde2 282 return wxMUTEX_NO_ERROR;
2bda0e17
KB
283}
284
9e84b847 285wxMutexError wxMutexInternal::Unlock()
2bda0e17 286{
375f364e
RR
287 // required for checking recursiveness
288 m_owningThread = 0;
289
9e84b847 290 if ( !::ReleaseMutex(m_mutex) )
3222fde2 291 {
9a83f860 292 wxLogLastError(wxT("ReleaseMutex()"));
9e84b847 293
3222fde2
VZ
294 return wxMUTEX_MISC_ERROR;
295 }
a6b0bd49 296
3222fde2 297 return wxMUTEX_NO_ERROR;
2bda0e17
KB
298}
299
be809868 300// --------------------------------------------------------------------------
9e84b847 301// wxSemaphore
be809868
VZ
302// --------------------------------------------------------------------------
303
9e84b847 304// a trivial wrapper around Win32 semaphore
be809868 305class wxSemaphoreInternal
3222fde2 306{
2bda0e17 307public:
9e84b847 308 wxSemaphoreInternal(int initialcount, int maxcount);
be809868
VZ
309 ~wxSemaphoreInternal();
310
9e84b847 311 bool IsOk() const { return m_semaphore != NULL; }
be809868 312
9e84b847 313 wxSemaError Wait() { return WaitTimeout(INFINITE); }
918dc519
VZ
314
315 wxSemaError TryWait()
316 {
317 wxSemaError rc = WaitTimeout(0);
318 if ( rc == wxSEMA_TIMEOUT )
319 rc = wxSEMA_BUSY;
320
321 return rc;
322 }
323
9e84b847 324 wxSemaError WaitTimeout(unsigned long milliseconds);
be809868 325
9e84b847 326 wxSemaError Post();
be809868
VZ
327
328private:
329 HANDLE m_semaphore;
22f3361e 330
c0c133e1 331 wxDECLARE_NO_COPY_CLASS(wxSemaphoreInternal);
be809868
VZ
332};
333
9e84b847 334wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount)
be809868 335{
4a268913 336#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
be809868 337 if ( maxcount == 0 )
b568d04f 338 {
be809868
VZ
339 // make it practically infinite
340 maxcount = INT_MAX;
341 }
4d1c1c3c 342
9e84b847
VZ
343 m_semaphore = ::CreateSemaphore
344 (
345 NULL, // default security attributes
346 initialcount,
347 maxcount,
348 NULL // no name
349 );
4676948b 350#endif
be809868
VZ
351 if ( !m_semaphore )
352 {
9a83f860 353 wxLogLastError(wxT("CreateSemaphore()"));
b568d04f 354 }
be809868
VZ
355}
356
357wxSemaphoreInternal::~wxSemaphoreInternal()
358{
9e84b847 359 if ( m_semaphore )
b568d04f 360 {
9e84b847
VZ
361 if ( !::CloseHandle(m_semaphore) )
362 {
9a83f860 363 wxLogLastError(wxT("CloseHandle(semaphore)"));
9e84b847 364 }
be809868
VZ
365 }
366}
b568d04f 367
9e84b847 368wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds)
be809868 369{
9e84b847 370 DWORD rc = ::WaitForSingleObject( m_semaphore, milliseconds );
be809868 371
9e84b847 372 switch ( rc )
be809868
VZ
373 {
374 case WAIT_OBJECT_0:
9e84b847 375 return wxSEMA_NO_ERROR;
b568d04f 376
be809868 377 case WAIT_TIMEOUT:
918dc519 378 return wxSEMA_TIMEOUT;
be809868
VZ
379
380 default:
9a83f860 381 wxLogLastError(wxT("WaitForSingleObject(semaphore)"));
b568d04f
VZ
382 }
383
9e84b847 384 return wxSEMA_MISC_ERROR;
be809868
VZ
385}
386
9e84b847 387wxSemaError wxSemaphoreInternal::Post()
be809868 388{
4a268913 389#if !defined(_WIN32_WCE) || (_WIN32_WCE >= 300)
9e84b847 390 if ( !::ReleaseSemaphore(m_semaphore, 1, NULL /* ptr to previous count */) )
4d1c1c3c 391 {
a0020fcd
VZ
392 if ( GetLastError() == ERROR_TOO_MANY_POSTS )
393 {
394 return wxSEMA_OVERFLOW;
395 }
396 else
397 {
9a83f860 398 wxLogLastError(wxT("ReleaseSemaphore"));
a0020fcd
VZ
399 return wxSEMA_MISC_ERROR;
400 }
9e84b847 401 }
be809868 402
9e84b847 403 return wxSEMA_NO_ERROR;
a0020fcd
VZ
404#else
405 return wxSEMA_MISC_ERROR;
406#endif
be809868 407}
4d1c1c3c 408
3222fde2
VZ
409// ----------------------------------------------------------------------------
410// wxThread implementation
411// ----------------------------------------------------------------------------
412
bf1852e1
VZ
413// wxThreadInternal class
414// ----------------------
415
3222fde2
VZ
416class wxThreadInternal
417{
2bda0e17 418public:
3ef22a5b 419 wxThreadInternal(wxThread *thread)
bf1852e1 420 {
3ef22a5b 421 m_thread = thread;
bf1852e1
VZ
422 m_hThread = 0;
423 m_state = STATE_NEW;
424 m_priority = WXTHREAD_DEFAULT_PRIORITY;
3ef22a5b 425 m_nRef = 1;
bf1852e1
VZ
426 }
427
b568d04f
VZ
428 ~wxThreadInternal()
429 {
430 Free();
431 }
432
433 void Free()
434 {
435 if ( m_hThread )
436 {
437 if ( !::CloseHandle(m_hThread) )
438 {
f6bcfd97 439 wxLogLastError(wxT("CloseHandle(thread)"));
b568d04f
VZ
440 }
441
442 m_hThread = 0;
443 }
444 }
445
bf1852e1 446 // create a new (suspended) thread (for the given thread object)
6fe73788 447 bool Create(wxThread *thread, unsigned int stackSize);
bf1852e1 448
68d41720
VZ
449 // wait for the thread to terminate, either by itself, or by asking it
450 // (politely, this is not Kill()!) to do it
3ef22a5b
VZ
451 wxThreadError WaitForTerminate(wxCriticalSection& cs,
452 wxThread::ExitCode *pRc,
b95a7c31 453 wxThreadWait waitMode,
3ef22a5b 454 wxThread *threadToDelete = NULL);
68d41720
VZ
455
456 // kill the thread unconditionally
457 wxThreadError Kill();
458
bf1852e1
VZ
459 // suspend/resume/terminate
460 bool Suspend();
461 bool Resume();
462 void Cancel() { m_state = STATE_CANCELED; }
463
464 // thread state
465 void SetState(wxThreadState state) { m_state = state; }
466 wxThreadState GetState() const { return m_state; }
467
468 // thread priority
b568d04f 469 void SetPriority(unsigned int priority);
bf1852e1
VZ
470 unsigned int GetPriority() const { return m_priority; }
471
472 // thread handle and id
473 HANDLE GetHandle() const { return m_hThread; }
474 DWORD GetId() const { return m_tid; }
475
d3f8206c 476 // the thread function forwarding to DoThreadStart
9f51f2b6 477 static THREAD_RETVAL THREAD_CALLCONV WinThreadStart(void *thread);
2bda0e17 478
d3f8206c
VZ
479 // really start the thread (if it's not already dead)
480 static THREAD_RETVAL DoThreadStart(wxThread *thread);
481
5b53617d
VZ
482 // call OnExit() on the thread
483 static void DoThreadOnExit(wxThread *thread);
484
485
3ef22a5b
VZ
486 void KeepAlive()
487 {
488 if ( m_thread->IsDetached() )
489 ::InterlockedIncrement(&m_nRef);
490 }
491
492 void LetDie()
493 {
494 if ( m_thread->IsDetached() && !::InterlockedDecrement(&m_nRef) )
495 delete m_thread;
496 }
497
bf1852e1 498private:
3ef22a5b
VZ
499 // the thread we're associated with
500 wxThread *m_thread;
501
bf1852e1
VZ
502 HANDLE m_hThread; // handle of the thread
503 wxThreadState m_state; // state, see wxThreadState enum
504 unsigned int m_priority; // thread priority in "wx" units
505 DWORD m_tid; // thread id
22f3361e 506
3ef22a5b
VZ
507 // number of threads which need this thread to remain alive, when the count
508 // reaches 0 we kill the owning wxThread -- and die ourselves with it
509 LONG m_nRef;
510
c0c133e1 511 wxDECLARE_NO_COPY_CLASS(wxThreadInternal);
2bda0e17
KB
512};
513
3ef22a5b
VZ
514// small class which keeps a thread alive during its lifetime
515class wxThreadKeepAlive
516{
517public:
518 wxThreadKeepAlive(wxThreadInternal& thrImpl) : m_thrImpl(thrImpl)
519 { m_thrImpl.KeepAlive(); }
520 ~wxThreadKeepAlive()
521 { m_thrImpl.LetDie(); }
522
523private:
524 wxThreadInternal& m_thrImpl;
525};
526
5b53617d
VZ
527/* static */
528void wxThreadInternal::DoThreadOnExit(wxThread *thread)
529{
530 wxTRY
531 {
532 thread->OnExit();
533 }
534 wxCATCH_ALL( wxTheApp->OnUnhandledException(); )
535}
536
537/* static */
d3f8206c
VZ
538THREAD_RETVAL wxThreadInternal::DoThreadStart(wxThread *thread)
539{
5b53617d
VZ
540 wxON_BLOCK_EXIT1(DoThreadOnExit, thread);
541
3f49efdb 542 THREAD_RETVAL rc = THREAD_ERROR_EXIT;
d3f8206c
VZ
543
544 wxTRY
545 {
d3f8206c
VZ
546 // store the thread object in the TLS
547 if ( !::TlsSetValue(gs_tlsThisThread, thread) )
548 {
4c51a665 549 wxLogSysError(_("Cannot start thread: error writing TLS."));
d3f8206c 550
3f49efdb 551 return THREAD_ERROR_EXIT;
d3f8206c
VZ
552 }
553
d79c9c67 554 rc = wxPtrToUInt(thread->Entry());
d3f8206c
VZ
555 }
556 wxCATCH_ALL( wxTheApp->OnUnhandledException(); )
557
558 return rc;
559}
3ef22a5b 560
5b53617d 561/* static */
08d7397c 562THREAD_RETVAL THREAD_CALLCONV wxThreadInternal::WinThreadStart(void *param)
2bda0e17 563{
3f49efdb 564 THREAD_RETVAL rc = THREAD_ERROR_EXIT;
3ef22a5b
VZ
565
566 wxThread * const thread = (wxThread *)param;
f6bcfd97 567
d3f8206c
VZ
568 // each thread has its own SEH translator so install our own a.s.a.p.
569 DisableAutomaticSETranslator();
570
f6bcfd97
BP
571 // first of all, check whether we hadn't been cancelled already and don't
572 // start the user code at all then
0f00be4b 573 const bool hasExited = thread->m_internal->GetState() == STATE_EXITED;
5eba4394 574
5b53617d
VZ
575 // run the thread function itself inside a SEH try/except block
576 wxSEH_TRY
bf1852e1 577 {
5b53617d
VZ
578 if ( hasExited )
579 DoThreadOnExit(thread);
580 else
d3f8206c 581 rc = DoThreadStart(thread);
5eba4394 582 }
3f49efdb 583 wxSEH_HANDLE(THREAD_ERROR_EXIT)
5b53617d 584
5eba4394 585
5eba4394
DS
586 // save IsDetached because thread object can be deleted by joinable
587 // threads after state is changed to STATE_EXITED.
d3f8206c 588 const bool isDetached = thread->IsDetached();
0f00be4b 589 if ( !hasExited )
5eba4394 590 {
f6bcfd97 591 // enter m_critsect before changing the thread state
d3f8206c
VZ
592 //
593 // NB: can't use wxCriticalSectionLocker here as we use SEH and it's
594 // incompatible with C++ object dtors
595 thread->m_critsect.Enter();
f6bcfd97 596 thread->m_internal->SetState(STATE_EXITED);
d3f8206c 597 thread->m_critsect.Leave();
f6bcfd97 598 }
b568d04f 599
3ef22a5b 600 // the thread may delete itself now if it wants, we don't need it any more
0f00be4b
VZ
601 if ( isDetached )
602 thread->m_internal->LetDie();
bf1852e1 603
b568d04f 604 return rc;
2bda0e17
KB
605}
606
b568d04f 607void wxThreadInternal::SetPriority(unsigned int priority)
2bda0e17 608{
b568d04f 609 m_priority = priority;
3222fde2 610
77ffb593 611 // translate wxWidgets priority to the Windows one
bf1852e1
VZ
612 int win_priority;
613 if (m_priority <= 20)
614 win_priority = THREAD_PRIORITY_LOWEST;
615 else if (m_priority <= 40)
616 win_priority = THREAD_PRIORITY_BELOW_NORMAL;
617 else if (m_priority <= 60)
618 win_priority = THREAD_PRIORITY_NORMAL;
619 else if (m_priority <= 80)
620 win_priority = THREAD_PRIORITY_ABOVE_NORMAL;
621 else if (m_priority <= 100)
622 win_priority = THREAD_PRIORITY_HIGHEST;
3222fde2
VZ
623 else
624 {
223d09f6 625 wxFAIL_MSG(wxT("invalid value of thread priority parameter"));
bf1852e1 626 win_priority = THREAD_PRIORITY_NORMAL;
3222fde2
VZ
627 }
628
b568d04f 629 if ( !::SetThreadPriority(m_hThread, win_priority) )
bee503b0
VZ
630 {
631 wxLogSysError(_("Can't set thread priority"));
632 }
b568d04f
VZ
633}
634
6fe73788 635bool wxThreadInternal::Create(wxThread *thread, unsigned int stackSize)
b568d04f 636{
50ef4401 637 wxASSERT_MSG( m_state == STATE_NEW && !m_hThread,
9a83f860 638 wxT("Create()ing thread twice?") );
50ef4401 639
b568d04f
VZ
640 // for compilers which have it, we should use C RTL function for thread
641 // creation instead of Win32 API one because otherwise we will have memory
642 // leaks if the thread uses C RTL (and most threads do)
9f51f2b6 643#ifdef wxUSE_BEGIN_THREAD
414c639c
VZ
644
645 // Watcom is reported to not like 0 stack size (which means "use default"
646 // for the other compilers and is also the default value for stackSize)
647#ifdef __WATCOMC__
648 if ( !stackSize )
649 stackSize = 10240;
650#endif // __WATCOMC__
651
9f51f2b6
VZ
652 m_hThread = (HANDLE)_beginthreadex
653 (
6fe73788
RL
654 NULL, // default security
655 stackSize,
656 wxThreadInternal::WinThreadStart, // entry point
657 thread,
658 CREATE_SUSPENDED,
659 (unsigned int *)&m_tid
9f51f2b6 660 );
611cb666 661#else // compiler doesn't have _beginthreadex
b568d04f
VZ
662 m_hThread = ::CreateThread
663 (
664 NULL, // default security
414c639c 665 stackSize, // stack size
9f51f2b6 666 wxThreadInternal::WinThreadStart, // thread entry point
b568d04f
VZ
667 (LPVOID)thread, // parameter
668 CREATE_SUSPENDED, // flags
669 &m_tid // [out] thread id
670 );
611cb666 671#endif // _beginthreadex/CreateThread
b568d04f
VZ
672
673 if ( m_hThread == NULL )
674 {
675 wxLogSysError(_("Can't create thread"));
676
3ef22a5b 677 return false;
b568d04f
VZ
678 }
679
680 if ( m_priority != WXTHREAD_DEFAULT_PRIORITY )
681 {
682 SetPriority(m_priority);
683 }
3222fde2 684
3ef22a5b 685 return true;
2bda0e17
KB
686}
687
68d41720
VZ
688wxThreadError wxThreadInternal::Kill()
689{
df191bfe
VZ
690 m_thread->OnKill();
691
3f49efdb 692 if ( !::TerminateThread(m_hThread, THREAD_ERROR_EXIT) )
68d41720
VZ
693 {
694 wxLogSysError(_("Couldn't terminate thread"));
695
696 return wxTHREAD_MISC_ERROR;
697 }
698
699 Free();
700
701 return wxTHREAD_NO_ERROR;
702}
703
704wxThreadError
3ef22a5b
VZ
705wxThreadInternal::WaitForTerminate(wxCriticalSection& cs,
706 wxThread::ExitCode *pRc,
b95a7c31 707 wxThreadWait waitMode,
3ef22a5b 708 wxThread *threadToDelete)
68d41720 709{
3ef22a5b
VZ
710 // prevent the thread C++ object from disappearing as long as we are using
711 // it here
712 wxThreadKeepAlive keepAlive(*this);
713
714
715 // we may either wait passively for the thread to terminate (when called
716 // from Wait()) or ask it to terminate (when called from Delete())
717 bool shouldDelete = threadToDelete != NULL;
718
3f49efdb 719 DWORD rc = 0;
68d41720 720
0f00be4b
VZ
721 // we might need to resume the thread if it's currently stopped
722 bool shouldResume = false;
68d41720 723
0f00be4b
VZ
724 // as Delete() (which calls us) is always safe to call we need to consider
725 // all possible states
68d41720
VZ
726 {
727 wxCriticalSectionLocker lock(cs);
728
729 if ( m_state == STATE_NEW )
730 {
3ef22a5b 731 if ( shouldDelete )
68d41720 732 {
63fa42b3
VZ
733 // WinThreadStart() will see it and terminate immediately, no
734 // need to cancel the thread -- but we still need to resume it
735 // to let it run
68d41720
VZ
736 m_state = STATE_EXITED;
737
0f00be4b
VZ
738 // we must call Resume() as the thread hasn't been initially
739 // resumed yet (and as Resume() it knows about STATE_EXITED
740 // special case, it won't touch it and WinThreadStart() will
741 // just exit immediately)
742 shouldResume = true;
3ef22a5b 743 shouldDelete = false;
68d41720 744 }
0f00be4b
VZ
745 //else: shouldResume is correctly set to false here, wait until
746 // someone else runs the thread and it finishes
68d41720 747 }
0f00be4b 748 else // running, paused, cancelled or even exited
68d41720
VZ
749 {
750 shouldResume = m_state == STATE_PAUSED;
751 }
752 }
753
754 // resume the thread if it is paused
755 if ( shouldResume )
756 Resume();
757
0f00be4b
VZ
758 // ask the thread to terminate
759 if ( shouldDelete )
68d41720 760 {
0f00be4b 761 wxCriticalSectionLocker lock(cs);
68d41720 762
0f00be4b
VZ
763 Cancel();
764 }
68d41720 765
486fa396
VZ
766 if ( threadToDelete )
767 threadToDelete->OnDelete();
68d41720 768
0f00be4b
VZ
769 // now wait for thread to finish
770 if ( wxThread::IsMain() )
771 {
772 // set flag for wxIsWaitingForThread()
773 gs_waitingForThread = true;
774 }
775
776 // we can't just wait for the thread to terminate because it might be
777 // calling some GUI functions and so it will never terminate before we
778 // process the Windows messages that result from these functions
779 // (note that even in console applications we might have to process
780 // messages if we use wxExecute() or timers or ...)
781 DWORD result wxDUMMY_INITIALIZE(0);
782 do
783 {
784 if ( wxThread::IsMain() )
68d41720 785 {
0f00be4b
VZ
786 // give the thread we're waiting for chance to do the GUI call
787 // it might be in
788 if ( (gs_nWaitingForGui > 0) && wxGuiOwnedByMainThread() )
68d41720 789 {
0f00be4b 790 wxMutexGuiLeave();
68d41720 791 }
0f00be4b 792 }
68d41720 793
e570a44b
VZ
794 wxAppTraits *traits = wxTheApp ? wxTheApp->GetTraits() : NULL;
795 if ( traits )
796 {
b95a7c31 797 result = traits->WaitForThread(m_hThread, waitMode);
e570a44b
VZ
798 }
799 else // can't wait for the thread
800 {
801 // so kill it below
802 result = 0xFFFFFFFF;
803 }
0f00be4b
VZ
804
805 switch ( result )
806 {
807 case 0xFFFFFFFF:
808 // error
4c51a665 809 wxLogSysError(_("Cannot wait for thread termination"));
0f00be4b
VZ
810 Kill();
811 return wxTHREAD_KILLED;
812
813 case WAIT_OBJECT_0:
814 // thread we're waiting for terminated
815 break;
816
817 case WAIT_OBJECT_0 + 1:
818 // new message arrived, process it -- but only if we're the
819 // main thread as we don't support processing messages in
820 // the other ones
821 //
822 // NB: we still must include QS_ALLINPUT even when waiting
823 // in a secondary thread because if it had created some
824 // window somehow (possible not even using wxWidgets)
825 // the system might dead lock then
826 if ( wxThread::IsMain() )
827 {
0f00be4b 828 if ( traits && !traits->DoMessageFromThreadWait() )
68d41720 829 {
0f00be4b
VZ
830 // WM_QUIT received: kill the thread
831 Kill();
68d41720 832
0f00be4b
VZ
833 return wxTHREAD_KILLED;
834 }
835 }
836 break;
68d41720 837
0f00be4b
VZ
838 default:
839 wxFAIL_MSG(wxT("unexpected result of MsgWaitForMultipleObject"));
68d41720 840 }
0f00be4b
VZ
841 } while ( result != WAIT_OBJECT_0 );
842
843 if ( wxThread::IsMain() )
844 {
845 gs_waitingForThread = false;
68d41720
VZ
846 }
847
0f00be4b 848
68d41720
VZ
849 // although the thread might be already in the EXITED state it might not
850 // have terminated yet and so we are not sure that it has actually
851 // terminated if the "if" above hadn't been taken
7d0bf46a 852 for ( ;; )
68d41720 853 {
3f49efdb 854 if ( !::GetExitCodeThread(m_hThread, &rc) )
68d41720
VZ
855 {
856 wxLogLastError(wxT("GetExitCodeThread"));
857
3f49efdb 858 rc = THREAD_ERROR_EXIT;
7d0bf46a
VZ
859
860 break;
68d41720 861 }
7d0bf46a 862
3f49efdb 863 if ( rc != STILL_ACTIVE )
7d0bf46a
VZ
864 break;
865
866 // give the other thread some time to terminate, otherwise we may be
867 // starving it
868 ::Sleep(1);
869 }
68d41720
VZ
870
871 if ( pRc )
3f49efdb 872 *pRc = wxUIntToPtr(rc);
68d41720 873
3ef22a5b 874 // we don't need the thread handle any more in any case
4f45ba63
VZ
875 Free();
876
4f45ba63 877
3f49efdb 878 return rc == THREAD_ERROR_EXIT ? wxTHREAD_MISC_ERROR : wxTHREAD_NO_ERROR;
68d41720
VZ
879}
880
bf1852e1 881bool wxThreadInternal::Suspend()
2bda0e17 882{
bf1852e1
VZ
883 DWORD nSuspendCount = ::SuspendThread(m_hThread);
884 if ( nSuspendCount == (DWORD)-1 )
bee503b0 885 {
4c51a665 886 wxLogSysError(_("Cannot suspend thread %x"), m_hThread);
bf1852e1 887
3ef22a5b 888 return false;
bee503b0 889 }
2bda0e17 890
bf1852e1
VZ
891 m_state = STATE_PAUSED;
892
3ef22a5b 893 return true;
a6b0bd49
VZ
894}
895
bf1852e1 896bool wxThreadInternal::Resume()
a6b0bd49 897{
bf1852e1 898 DWORD nSuspendCount = ::ResumeThread(m_hThread);
a6b0bd49
VZ
899 if ( nSuspendCount == (DWORD)-1 )
900 {
4c51a665 901 wxLogSysError(_("Cannot resume thread %x"), m_hThread);
a6b0bd49 902
3ef22a5b 903 return false;
a6b0bd49
VZ
904 }
905
f6bcfd97
BP
906 // don't change the state from STATE_EXITED because it's special and means
907 // we are going to terminate without running any user code - if we did it,
0f00be4b 908 // the code in WaitForTerminate() wouldn't work
f6bcfd97
BP
909 if ( m_state != STATE_EXITED )
910 {
911 m_state = STATE_RUNNING;
912 }
bee503b0 913
3ef22a5b 914 return true;
a6b0bd49
VZ
915}
916
bf1852e1
VZ
917// static functions
918// ----------------
919
920wxThread *wxThread::This()
a6b0bd49 921{
b568d04f 922 wxThread *thread = (wxThread *)::TlsGetValue(gs_tlsThisThread);
bf1852e1
VZ
923
924 // be careful, 0 may be a valid return value as well
925 if ( !thread && (::GetLastError() != NO_ERROR) )
a6b0bd49 926 {
bf1852e1 927 wxLogSysError(_("Couldn't get the current thread pointer"));
a6b0bd49 928
bf1852e1 929 // return NULL...
a6b0bd49
VZ
930 }
931
bf1852e1
VZ
932 return thread;
933}
934
bf1852e1
VZ
935void wxThread::Yield()
936{
b568d04f
VZ
937 // 0 argument to Sleep() is special and means to just give away the rest of
938 // our timeslice
bf1852e1
VZ
939 ::Sleep(0);
940}
941
ef8d96c2
VZ
942int wxThread::GetCPUCount()
943{
28a4627c
VZ
944 SYSTEM_INFO si;
945 GetSystemInfo(&si);
946
947 return si.dwNumberOfProcessors;
ef8d96c2
VZ
948}
949
4958ea8f
RD
950unsigned long wxThread::GetCurrentId()
951{
952 return (unsigned long)::GetCurrentThreadId();
953}
954
0c0d1521 955bool wxThread::SetConcurrency(size_t WXUNUSED_IN_WINCE(level))
ef8d96c2 956{
7010702f 957#ifdef __WXWINCE__
7010702f
WS
958 return false;
959#else
9a83f860 960 wxASSERT_MSG( IsMain(), wxT("should only be called from the main thread") );
28a4627c 961
ef8d96c2 962 // ok only for the default one
28a4627c
VZ
963 if ( level == 0 )
964 return 0;
965
966 // get system affinity mask first
967 HANDLE hProcess = ::GetCurrentProcess();
975b6bcf 968 DWORD_PTR dwProcMask, dwSysMask;
28a4627c
VZ
969 if ( ::GetProcessAffinityMask(hProcess, &dwProcMask, &dwSysMask) == 0 )
970 {
9a83f860 971 wxLogLastError(wxT("GetProcessAffinityMask"));
28a4627c 972
3ef22a5b 973 return false;
28a4627c
VZ
974 }
975
976 // how many CPUs have we got?
977 if ( dwSysMask == 1 )
978 {
979 // don't bother with all this complicated stuff - on a single
980 // processor system it doesn't make much sense anyhow
981 return level == 1;
982 }
983
984 // calculate the process mask: it's a bit vector with one bit per
985 // processor; we want to schedule the process to run on first level
986 // CPUs
987 DWORD bit = 1;
988 while ( bit )
989 {
990 if ( dwSysMask & bit )
991 {
992 // ok, we can set this bit
993 dwProcMask |= bit;
994
995 // another process added
8d7eaf91 996 if ( --level == 0 )
28a4627c
VZ
997 {
998 // and that's enough
999 break;
1000 }
1001 }
1002
1003 // next bit
1004 bit <<= 1;
1005 }
1006
1007 // could we set all bits?
1008 if ( level != 0 )
1009 {
9a83f860 1010 wxLogDebug(wxT("bad level %u in wxThread::SetConcurrency()"), level);
28a4627c 1011
3ef22a5b 1012 return false;
28a4627c
VZ
1013 }
1014
1015 // set it: we can't link to SetProcessAffinityMask() because it doesn't
1016 // exist in Win9x, use RT binding instead
1017
fdb9d2b8 1018 typedef BOOL (WINAPI *SETPROCESSAFFINITYMASK)(HANDLE, DWORD_PTR);
28a4627c
VZ
1019
1020 // can use static var because we're always in the main thread here
1021 static SETPROCESSAFFINITYMASK pfnSetProcessAffinityMask = NULL;
1022
1023 if ( !pfnSetProcessAffinityMask )
1024 {
9a83f860 1025 HMODULE hModKernel = ::LoadLibrary(wxT("kernel32"));
28a4627c
VZ
1026 if ( hModKernel )
1027 {
1028 pfnSetProcessAffinityMask = (SETPROCESSAFFINITYMASK)
f6bcfd97 1029 ::GetProcAddress(hModKernel, "SetProcessAffinityMask");
28a4627c
VZ
1030 }
1031
1032 // we've discovered a MT version of Win9x!
1033 wxASSERT_MSG( pfnSetProcessAffinityMask,
9a83f860 1034 wxT("this system has several CPUs but no SetProcessAffinityMask function?") );
28a4627c
VZ
1035 }
1036
1037 if ( !pfnSetProcessAffinityMask )
1038 {
1039 // msg given above - do it only once
3ef22a5b 1040 return false;
28a4627c
VZ
1041 }
1042
696e1ea0 1043 if ( pfnSetProcessAffinityMask(hProcess, dwProcMask) == 0 )
28a4627c 1044 {
9a83f860 1045 wxLogLastError(wxT("SetProcessAffinityMask"));
28a4627c 1046
3ef22a5b 1047 return false;
28a4627c 1048 }
975b6bcf 1049
3ef22a5b 1050 return true;
7010702f 1051#endif // __WXWINCE__/!__WXWINCE__
ef8d96c2
VZ
1052}
1053
b568d04f
VZ
1054// ctor and dtor
1055// -------------
1056
1057wxThread::wxThread(wxThreadKind kind)
1058{
3ef22a5b 1059 m_internal = new wxThreadInternal(this);
b568d04f
VZ
1060
1061 m_isDetached = kind == wxTHREAD_DETACHED;
1062}
1063
1064wxThread::~wxThread()
1065{
9fc3ad34 1066 delete m_internal;
b568d04f
VZ
1067}
1068
bf1852e1
VZ
1069// create/start thread
1070// -------------------
1071
6fe73788 1072wxThreadError wxThread::Create(unsigned int stackSize)
bf1852e1 1073{
b568d04f
VZ
1074 wxCriticalSectionLocker lock(m_critsect);
1075
6fe73788 1076 if ( !m_internal->Create(this, stackSize) )
bf1852e1 1077 return wxTHREAD_NO_RESOURCE;
bee503b0 1078
a6b0bd49 1079 return wxTHREAD_NO_ERROR;
2bda0e17
KB
1080}
1081
bf1852e1 1082wxThreadError wxThread::Run()
2bda0e17 1083{
bf1852e1
VZ
1084 wxCriticalSectionLocker lock(m_critsect);
1085
89a76d5d
FM
1086 wxCHECK_MSG( m_internal->GetState() == STATE_NEW, wxTHREAD_RUNNING,
1087 wxT("thread may only be started once after Create()") );
bf1852e1 1088
b568d04f 1089 // the thread has just been created and is still suspended - let it run
bf1852e1 1090 return Resume();
2bda0e17
KB
1091}
1092
bf1852e1
VZ
1093// suspend/resume thread
1094// ---------------------
1095
1096wxThreadError wxThread::Pause()
2bda0e17 1097{
bf1852e1
VZ
1098 wxCriticalSectionLocker lock(m_critsect);
1099
9fc3ad34 1100 return m_internal->Suspend() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
1101}
1102
bf1852e1 1103wxThreadError wxThread::Resume()
2bda0e17 1104{
bf1852e1
VZ
1105 wxCriticalSectionLocker lock(m_critsect);
1106
9fc3ad34 1107 return m_internal->Resume() ? wxTHREAD_NO_ERROR : wxTHREAD_MISC_ERROR;
2bda0e17
KB
1108}
1109
bf1852e1
VZ
1110// stopping thread
1111// ---------------
1112
b95a7c31 1113wxThread::ExitCode wxThread::Wait(wxThreadWait waitMode)
b568d04f 1114{
d79c9c67 1115 ExitCode rc = wxUIntToPtr(THREAD_ERROR_EXIT);
3f49efdb 1116
b568d04f
VZ
1117 // although under Windows we can wait for any thread, it's an error to
1118 // wait for a detached one in wxWin API
3f49efdb 1119 wxCHECK_MSG( !IsDetached(), rc,
9a83f860 1120 wxT("wxThread::Wait(): can't wait for detached thread") );
b568d04f 1121
b95a7c31 1122 (void)m_internal->WaitForTerminate(m_critsect, &rc, waitMode);
b568d04f 1123
b568d04f
VZ
1124 return rc;
1125}
1126
b95a7c31 1127wxThreadError wxThread::Delete(ExitCode *pRc, wxThreadWait waitMode)
2bda0e17 1128{
b95a7c31 1129 return m_internal->WaitForTerminate(m_critsect, pRc, waitMode, this);
2bda0e17
KB
1130}
1131
bf1852e1 1132wxThreadError wxThread::Kill()
2bda0e17 1133{
bf1852e1
VZ
1134 if ( !IsRunning() )
1135 return wxTHREAD_NOT_RUNNING;
1136
68d41720 1137 wxThreadError rc = m_internal->Kill();
b568d04f
VZ
1138
1139 if ( IsDetached() )
1140 {
1141 delete this;
1142 }
57fd9bb2
VZ
1143 else // joinable
1144 {
1145 // update the status of the joinable thread
1146 wxCriticalSectionLocker lock(m_critsect);
1147 m_internal->SetState(STATE_EXITED);
1148 }
bf1852e1 1149
68d41720 1150 return rc;
2bda0e17
KB
1151}
1152
b568d04f 1153void wxThread::Exit(ExitCode status)
2bda0e17 1154{
9fc3ad34 1155 m_internal->Free();
2bda0e17 1156
b568d04f
VZ
1157 if ( IsDetached() )
1158 {
1159 delete this;
1160 }
57fd9bb2
VZ
1161 else // joinable
1162 {
1163 // update the status of the joinable thread
1164 wxCriticalSectionLocker lock(m_critsect);
1165 m_internal->SetState(STATE_EXITED);
1166 }
b568d04f 1167
9f51f2b6 1168#ifdef wxUSE_BEGIN_THREAD
3f49efdb 1169 _endthreadex(wxPtrToUInt(status));
b568d04f 1170#else // !VC++
bf1852e1 1171 ::ExitThread((DWORD)status);
b568d04f 1172#endif // VC++/!VC++
2bda0e17 1173
223d09f6 1174 wxFAIL_MSG(wxT("Couldn't return from ExitThread()!"));
bf1852e1 1175}
2bda0e17 1176
b568d04f
VZ
1177// priority setting
1178// ----------------
1179
bf1852e1
VZ
1180void wxThread::SetPriority(unsigned int prio)
1181{
1182 wxCriticalSectionLocker lock(m_critsect);
1183
9fc3ad34 1184 m_internal->SetPriority(prio);
bf1852e1 1185}
2bda0e17 1186
bf1852e1
VZ
1187unsigned int wxThread::GetPriority() const
1188{
f48a1159 1189 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
2bda0e17 1190
9fc3ad34 1191 return m_internal->GetPriority();
2bda0e17
KB
1192}
1193
b568d04f 1194unsigned long wxThread::GetId() const
2bda0e17 1195{
f48a1159 1196 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
bf1852e1 1197
9fc3ad34 1198 return (unsigned long)m_internal->GetId();
2bda0e17
KB
1199}
1200
72fd19a1
JS
1201bool wxThread::IsRunning() const
1202{
f48a1159 1203 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
bf1852e1 1204
9fc3ad34 1205 return m_internal->GetState() == STATE_RUNNING;
72fd19a1
JS
1206}
1207
1208bool wxThread::IsAlive() const
1209{
f48a1159 1210 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
bf1852e1 1211
9fc3ad34
VZ
1212 return (m_internal->GetState() == STATE_RUNNING) ||
1213 (m_internal->GetState() == STATE_PAUSED);
72fd19a1
JS
1214}
1215
a737331d
GL
1216bool wxThread::IsPaused() const
1217{
f48a1159 1218 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
a737331d 1219
9fc3ad34 1220 return m_internal->GetState() == STATE_PAUSED;
a737331d
GL
1221}
1222
8c10faf1 1223bool wxThread::TestDestroy()
2bda0e17 1224{
f48a1159 1225 wxCriticalSectionLocker lock(const_cast<wxCriticalSection &>(m_critsect));
bf1852e1 1226
9fc3ad34 1227 return m_internal->GetState() == STATE_CANCELED;
2bda0e17
KB
1228}
1229
3222fde2
VZ
1230// ----------------------------------------------------------------------------
1231// Automatic initialization for thread module
1232// ----------------------------------------------------------------------------
2bda0e17 1233
3222fde2 1234class wxThreadModule : public wxModule
a6b0bd49 1235{
3222fde2
VZ
1236public:
1237 virtual bool OnInit();
1238 virtual void OnExit();
d524867f 1239
3222fde2
VZ
1240private:
1241 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1242};
d524867f
RR
1243
1244IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1245
3222fde2 1246bool wxThreadModule::OnInit()
d524867f 1247{
bf1852e1 1248 // allocate TLS index for storing the pointer to the current thread
b568d04f
VZ
1249 gs_tlsThisThread = ::TlsAlloc();
1250 if ( gs_tlsThisThread == 0xFFFFFFFF )
bf1852e1
VZ
1251 {
1252 // in normal circumstances it will only happen if all other
1253 // TLS_MINIMUM_AVAILABLE (>= 64) indices are already taken - in other
1254 // words, this should never happen
f6bcfd97 1255 wxLogSysError(_("Thread module initialization failed: impossible to allocate index in thread local storage"));
bf1852e1 1256
3ef22a5b 1257 return false;
bf1852e1
VZ
1258 }
1259
1260 // main thread doesn't have associated wxThread object, so store 0 in the
1261 // TLS instead
b568d04f 1262 if ( !::TlsSetValue(gs_tlsThisThread, (LPVOID)0) )
bf1852e1 1263 {
b568d04f
VZ
1264 ::TlsFree(gs_tlsThisThread);
1265 gs_tlsThisThread = 0xFFFFFFFF;
bf1852e1 1266
4c51a665 1267 wxLogSysError(_("Thread module initialization failed: cannot store value in thread local storage"));
bf1852e1 1268
3ef22a5b 1269 return false;
bf1852e1
VZ
1270 }
1271
b568d04f 1272 gs_critsectWaitingForGui = new wxCriticalSection();
bee503b0 1273
b568d04f
VZ
1274 gs_critsectGui = new wxCriticalSection();
1275 gs_critsectGui->Enter();
bee503b0 1276
3ef22a5b
VZ
1277 gs_critsectThreadDelete = new wxCriticalSection;
1278
f9226383 1279 wxThread::ms_idMainThread = wxThread::GetCurrentId();
3222fde2 1280
3ef22a5b 1281 return true;
d524867f
RR
1282}
1283
3222fde2 1284void wxThreadModule::OnExit()
d524867f 1285{
b568d04f 1286 if ( !::TlsFree(gs_tlsThisThread) )
bf1852e1 1287 {
f6bcfd97 1288 wxLogLastError(wxT("TlsFree failed."));
bf1852e1
VZ
1289 }
1290
5276b0a5 1291 wxDELETE(gs_critsectThreadDelete);
3ef22a5b 1292
b568d04f 1293 if ( gs_critsectGui )
3222fde2 1294 {
b568d04f 1295 gs_critsectGui->Leave();
5276b0a5 1296 wxDELETE(gs_critsectGui);
3222fde2 1297 }
bee503b0 1298
5276b0a5 1299 wxDELETE(gs_critsectWaitingForGui);
3222fde2
VZ
1300}
1301
bee503b0 1302// ----------------------------------------------------------------------------
b568d04f 1303// under Windows, these functions are implemented using a critical section and
3222fde2 1304// not a mutex, so the names are a bit confusing
bee503b0
VZ
1305// ----------------------------------------------------------------------------
1306
d254213e 1307void wxMutexGuiEnterImpl()
3222fde2 1308{
bee503b0
VZ
1309 // this would dead lock everything...
1310 wxASSERT_MSG( !wxThread::IsMain(),
223d09f6 1311 wxT("main thread doesn't want to block in wxMutexGuiEnter()!") );
bee503b0
VZ
1312
1313 // the order in which we enter the critical sections here is crucial!!
1314
1315 // set the flag telling to the main thread that we want to do some GUI
1316 {
b568d04f 1317 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1318
b568d04f 1319 gs_nWaitingForGui++;
bee503b0
VZ
1320 }
1321
1322 wxWakeUpMainThread();
1323
1324 // now we may block here because the main thread will soon let us in
1325 // (during the next iteration of OnIdle())
b568d04f 1326 gs_critsectGui->Enter();
3222fde2
VZ
1327}
1328
d254213e 1329void wxMutexGuiLeaveImpl()
3222fde2 1330{
b568d04f 1331 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0
VZ
1332
1333 if ( wxThread::IsMain() )
1334 {
3ef22a5b 1335 gs_bGuiOwnedByMainThread = false;
bee503b0
VZ
1336 }
1337 else
1338 {
4d1c1c3c 1339 // decrement the number of threads waiting for GUI access now
b568d04f 1340 wxASSERT_MSG( gs_nWaitingForGui > 0,
223d09f6 1341 wxT("calling wxMutexGuiLeave() without entering it first?") );
bee503b0 1342
b568d04f 1343 gs_nWaitingForGui--;
bee503b0
VZ
1344
1345 wxWakeUpMainThread();
1346 }
1347
b568d04f 1348 gs_critsectGui->Leave();
bee503b0
VZ
1349}
1350
0c2f35dc 1351void WXDLLIMPEXP_BASE wxMutexGuiLeaveOrEnter()
bee503b0
VZ
1352{
1353 wxASSERT_MSG( wxThread::IsMain(),
223d09f6 1354 wxT("only main thread may call wxMutexGuiLeaveOrEnter()!") );
bee503b0 1355
b568d04f 1356 wxCriticalSectionLocker enter(*gs_critsectWaitingForGui);
bee503b0 1357
b568d04f 1358 if ( gs_nWaitingForGui == 0 )
bee503b0
VZ
1359 {
1360 // no threads are waiting for GUI - so we may acquire the lock without
1361 // any danger (but only if we don't already have it)
1362 if ( !wxGuiOwnedByMainThread() )
1363 {
b568d04f 1364 gs_critsectGui->Enter();
bee503b0 1365
3ef22a5b 1366 gs_bGuiOwnedByMainThread = true;
bee503b0
VZ
1367 }
1368 //else: already have it, nothing to do
1369 }
1370 else
1371 {
1372 // some threads are waiting, release the GUI lock if we have it
1373 if ( wxGuiOwnedByMainThread() )
1374 {
1375 wxMutexGuiLeave();
1376 }
1377 //else: some other worker thread is doing GUI
1378 }
1379}
1380
0c2f35dc 1381bool WXDLLIMPEXP_BASE wxGuiOwnedByMainThread()
bee503b0 1382{
b568d04f 1383 return gs_bGuiOwnedByMainThread;
bee503b0
VZ
1384}
1385
1386// wake up the main thread if it's in ::GetMessage()
0c2f35dc 1387void WXDLLIMPEXP_BASE wxWakeUpMainThread()
bee503b0
VZ
1388{
1389 // sending any message would do - hopefully WM_NULL is harmless enough
3cc63190 1390 if ( !::PostThreadMessage(wxThread::GetMainId(), WM_NULL, 0, 0) )
bee503b0
VZ
1391 {
1392 // should never happen
f6bcfd97 1393 wxLogLastError(wxT("PostThreadMessage(WM_NULL)"));
bee503b0 1394 }
3222fde2 1395}
d524867f 1396
0c2f35dc 1397bool WXDLLIMPEXP_BASE wxIsWaitingForThread()
bf1852e1 1398{
b568d04f 1399 return gs_waitingForThread;
bf1852e1
VZ
1400}
1401
9e84b847
VZ
1402// ----------------------------------------------------------------------------
1403// include common implementation code
1404// ----------------------------------------------------------------------------
1405
1406#include "wx/thrimpl.cpp"
1407
3222fde2 1408#endif // wxUSE_THREADS