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