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