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