]>
Commit | Line | Data |
---|---|---|
1 | ///////////////////////////////////////////////////////////////////////////// | |
2 | // Name: threadpsx.cpp | |
3 | // Purpose: wxThread (Posix) Implementation | |
4 | // Author: Original from Wolfram Gloger/Guilhem Lavaux | |
5 | // Modified by: K. S. Sreeram (2002): POSIXified wxCondition, added wxSemaphore | |
6 | // Created: 04/22/98 | |
7 | // RCS-ID: $Id$ | |
8 | // Copyright: (c) Wolfram Gloger (1996, 1997) | |
9 | // Guilhem Lavaux (1998) | |
10 | // Vadim Zeitlin (1999-2002) | |
11 | // Robert Roebling (1999) | |
12 | // K. S. Sreeram (2002) | |
13 | // Licence: wxWindows licence | |
14 | ///////////////////////////////////////////////////////////////////////////// | |
15 | ||
16 | // ============================================================================ | |
17 | // declaration | |
18 | // ============================================================================ | |
19 | ||
20 | // ---------------------------------------------------------------------------- | |
21 | // headers | |
22 | // ---------------------------------------------------------------------------- | |
23 | ||
24 | #ifdef __GNUG__ | |
25 | #pragma implementation "thread.h" | |
26 | #endif | |
27 | ||
28 | #include "wx/defs.h" | |
29 | ||
30 | #if wxUSE_THREADS | |
31 | ||
32 | #include "wx/thread.h" | |
33 | #include "wx/module.h" | |
34 | #include "wx/utils.h" | |
35 | #include "wx/log.h" | |
36 | #include "wx/intl.h" | |
37 | #include "wx/dynarray.h" | |
38 | #include "wx/timer.h" | |
39 | ||
40 | #include <stdio.h> | |
41 | #include <unistd.h> | |
42 | #include <pthread.h> | |
43 | #include <errno.h> | |
44 | #include <time.h> | |
45 | #if HAVE_SCHED_H | |
46 | #include <sched.h> | |
47 | #endif | |
48 | ||
49 | #ifdef HAVE_THR_SETCONCURRENCY | |
50 | #include <thread.h> | |
51 | #endif | |
52 | ||
53 | // we use wxFFile under Linux in GetCPUCount() | |
54 | #ifdef __LINUX__ | |
55 | #include "wx/ffile.h" | |
56 | #endif | |
57 | ||
58 | // ---------------------------------------------------------------------------- | |
59 | // constants | |
60 | // ---------------------------------------------------------------------------- | |
61 | ||
62 | // the possible states of the thread and transitions from them | |
63 | enum wxThreadState | |
64 | { | |
65 | STATE_NEW, // didn't start execution yet (=> RUNNING) | |
66 | STATE_RUNNING, // running (=> PAUSED or EXITED) | |
67 | STATE_PAUSED, // suspended (=> RUNNING or EXITED) | |
68 | STATE_EXITED // thread doesn't exist any more | |
69 | }; | |
70 | ||
71 | // the exit value of a thread which has been cancelled | |
72 | static const wxThread::ExitCode EXITCODE_CANCELLED = (wxThread::ExitCode)-1; | |
73 | ||
74 | // trace mask for wxThread operations | |
75 | #define TRACE_THREADS _T("thread") | |
76 | ||
77 | // you can get additional debugging messages for the semaphore operations | |
78 | #define TRACE_SEMA _T("semaphore") | |
79 | ||
80 | // ---------------------------------------------------------------------------- | |
81 | // private functions | |
82 | // ---------------------------------------------------------------------------- | |
83 | ||
84 | static void ScheduleThreadForDeletion(); | |
85 | static void DeleteThread(wxThread *This); | |
86 | ||
87 | // ---------------------------------------------------------------------------- | |
88 | // private classes | |
89 | // ---------------------------------------------------------------------------- | |
90 | ||
91 | // an (non owning) array of pointers to threads | |
92 | WX_DEFINE_ARRAY(wxThread *, wxArrayThread); | |
93 | ||
94 | // an entry for a thread we can wait for | |
95 | ||
96 | // ----------------------------------------------------------------------------- | |
97 | // global data | |
98 | // ----------------------------------------------------------------------------- | |
99 | ||
100 | // we keep the list of all threads created by the application to be able to | |
101 | // terminate them on exit if there are some left - otherwise the process would | |
102 | // be left in memory | |
103 | static wxArrayThread gs_allThreads; | |
104 | ||
105 | // the id of the main thread | |
106 | static pthread_t gs_tidMain; | |
107 | ||
108 | // the key for the pointer to the associated wxThread object | |
109 | static pthread_key_t gs_keySelf; | |
110 | ||
111 | // the number of threads which are being deleted - the program won't exit | |
112 | // until there are any left | |
113 | static size_t gs_nThreadsBeingDeleted = 0; | |
114 | ||
115 | // a mutex to protect gs_nThreadsBeingDeleted | |
116 | static wxMutex *gs_mutexDeleteThread = (wxMutex *)NULL; | |
117 | ||
118 | // and a condition variable which will be signaled when all | |
119 | // gs_nThreadsBeingDeleted will have been deleted | |
120 | static wxCondition *gs_condAllDeleted = (wxCondition *)NULL; | |
121 | ||
122 | #if wxUSE_GUI | |
123 | // this mutex must be acquired before any call to a GUI function | |
124 | static wxMutex *gs_mutexGui; | |
125 | #endif // wxUSE_GUI | |
126 | ||
127 | // when we wait for a thread to exit, we're blocking on a condition which the | |
128 | // thread signals in its SignalExit() method -- but this condition can't be a | |
129 | // member of the thread itself as a detached thread may delete itself at any | |
130 | // moment and accessing the condition member of the thread after this would | |
131 | // result in a disaster | |
132 | // | |
133 | // so instead we maintain a global list of the structs below for the threads | |
134 | // we're interested in waiting on | |
135 | ||
136 | // ============================================================================ | |
137 | // wxMutex implementation | |
138 | // ============================================================================ | |
139 | ||
140 | // ---------------------------------------------------------------------------- | |
141 | // wxMutexInternal | |
142 | // ---------------------------------------------------------------------------- | |
143 | ||
144 | // this is a simple wrapper around pthread_mutex_t which provides error | |
145 | // checking | |
146 | class wxMutexInternal | |
147 | { | |
148 | public: | |
149 | wxMutexInternal(wxMutexType mutexType); | |
150 | ~wxMutexInternal(); | |
151 | ||
152 | wxMutexError Lock(); | |
153 | wxMutexError TryLock(); | |
154 | wxMutexError Unlock(); | |
155 | ||
156 | bool IsOk() const { return m_isOk; } | |
157 | ||
158 | private: | |
159 | pthread_mutex_t m_mutex; | |
160 | bool m_isOk; | |
161 | ||
162 | // wxConditionInternal uses our m_mutex | |
163 | friend class wxConditionInternal; | |
164 | }; | |
165 | ||
166 | wxMutexInternal::wxMutexInternal(wxMutexType mutexType) | |
167 | { | |
168 | int err; | |
169 | switch ( mutexType ) | |
170 | { | |
171 | case wxMUTEX_RECURSIVE: | |
172 | // support recursive locks like Win32, i.e. a thread can lock a | |
173 | // mutex which it had itself already locked | |
174 | // | |
175 | // unfortunately initialization of recursive mutexes is non | |
176 | // portable, so try several methods | |
177 | #ifdef HAVE_PTHREAD_MUTEXATTR_T | |
178 | { | |
179 | pthread_mutexattr_t attr; | |
180 | pthread_mutexattr_init(&attr); | |
181 | pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); | |
182 | ||
183 | err = pthread_mutex_init(&m_mutex, &attr); | |
184 | } | |
185 | #elif defined(HAVE_PTHREAD_RECURSIVE_MUTEX_INITIALIZER) | |
186 | // we can use this only as initializer so we have to assign it | |
187 | // first to a temp var - assigning directly to m_mutex wouldn't | |
188 | // even compile | |
189 | { | |
190 | pthread_mutex_t mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; | |
191 | m_mutex = mutex; | |
192 | } | |
193 | #else // no recursive mutexes | |
194 | err = EINVAL; | |
195 | #endif // HAVE_PTHREAD_MUTEXATTR_T/... | |
196 | break; | |
197 | ||
198 | default: | |
199 | wxFAIL_MSG( _T("unknown mutex type") ); | |
200 | // fall through | |
201 | ||
202 | case wxMUTEX_DEFAULT: | |
203 | err = pthread_mutex_init(&m_mutex, NULL); | |
204 | break; | |
205 | } | |
206 | ||
207 | m_isOk = err == 0; | |
208 | if ( !m_isOk ) | |
209 | { | |
210 | wxLogApiError("pthread_mutex_init()", err); | |
211 | } | |
212 | } | |
213 | ||
214 | wxMutexInternal::~wxMutexInternal() | |
215 | { | |
216 | if ( m_isOk ) | |
217 | { | |
218 | int err = pthread_mutex_destroy(&m_mutex); | |
219 | if ( err != 0 ) | |
220 | { | |
221 | wxLogApiError("pthread_mutex_destroy()", err); | |
222 | } | |
223 | } | |
224 | } | |
225 | ||
226 | wxMutexError wxMutexInternal::Lock() | |
227 | { | |
228 | int err = pthread_mutex_lock(&m_mutex); | |
229 | switch ( err ) | |
230 | { | |
231 | case EDEADLK: | |
232 | // only error checking mutexes return this value and so it's an | |
233 | // unexpected situation -- hence use assert, not wxLogDebug | |
234 | wxFAIL_MSG( _T("mutex deadlock prevented") ); | |
235 | return wxMUTEX_DEAD_LOCK; | |
236 | ||
237 | case EINVAL: | |
238 | wxLogDebug(_T("pthread_mutex_lock(): mutex not initialized.")); | |
239 | break; | |
240 | ||
241 | case 0: | |
242 | return wxMUTEX_NO_ERROR; | |
243 | ||
244 | default: | |
245 | wxLogApiError(_T("pthread_mutex_lock()"), err); | |
246 | } | |
247 | ||
248 | return wxMUTEX_MISC_ERROR; | |
249 | } | |
250 | ||
251 | wxMutexError wxMutexInternal::TryLock() | |
252 | { | |
253 | int err = pthread_mutex_trylock(&m_mutex); | |
254 | switch ( err ) | |
255 | { | |
256 | case EBUSY: | |
257 | // not an error: mutex is already locked, but we're prepared for | |
258 | // this | |
259 | return wxMUTEX_BUSY; | |
260 | ||
261 | case EINVAL: | |
262 | wxLogDebug(_T("pthread_mutex_trylock(): mutex not initialized.")); | |
263 | break; | |
264 | ||
265 | case 0: | |
266 | return wxMUTEX_NO_ERROR; | |
267 | ||
268 | default: | |
269 | wxLogApiError(_T("pthread_mutex_trylock()"), err); | |
270 | } | |
271 | ||
272 | return wxMUTEX_MISC_ERROR; | |
273 | } | |
274 | ||
275 | wxMutexError wxMutexInternal::Unlock() | |
276 | { | |
277 | int err = pthread_mutex_unlock(&m_mutex); | |
278 | switch ( err ) | |
279 | { | |
280 | case EPERM: | |
281 | // we don't own the mutex | |
282 | return wxMUTEX_UNLOCKED; | |
283 | ||
284 | case EINVAL: | |
285 | wxLogDebug(_T("pthread_mutex_unlock(): mutex not initialized.")); | |
286 | break; | |
287 | ||
288 | case 0: | |
289 | return wxMUTEX_NO_ERROR; | |
290 | ||
291 | default: | |
292 | wxLogApiError(_T("pthread_mutex_unlock()"), err); | |
293 | } | |
294 | ||
295 | return wxMUTEX_MISC_ERROR; | |
296 | } | |
297 | ||
298 | // =========================================================================== | |
299 | // wxCondition implementation | |
300 | // =========================================================================== | |
301 | ||
302 | // --------------------------------------------------------------------------- | |
303 | // wxConditionInternal | |
304 | // --------------------------------------------------------------------------- | |
305 | ||
306 | // this is a wrapper around pthread_cond_t associated with a wxMutex (and hence | |
307 | // with a pthread_mutex_t) | |
308 | class wxConditionInternal | |
309 | { | |
310 | public: | |
311 | wxConditionInternal(wxMutex& mutex); | |
312 | ~wxConditionInternal(); | |
313 | ||
314 | bool IsOk() const { return m_isOk && m_mutex.IsOk(); } | |
315 | ||
316 | wxCondError Wait(); | |
317 | wxCondError WaitTimeout(unsigned long milliseconds); | |
318 | ||
319 | wxCondError Signal(); | |
320 | wxCondError Broadcast(); | |
321 | ||
322 | private: | |
323 | // get the POSIX mutex associated with us | |
324 | pthread_mutex_t *GetPMutex() const { return &m_mutex.m_internal->m_mutex; } | |
325 | ||
326 | wxMutex& m_mutex; | |
327 | pthread_cond_t m_cond; | |
328 | ||
329 | bool m_isOk; | |
330 | }; | |
331 | ||
332 | wxConditionInternal::wxConditionInternal(wxMutex& mutex) | |
333 | : m_mutex(mutex) | |
334 | { | |
335 | int err = pthread_cond_init(&m_cond, NULL /* default attributes */); | |
336 | ||
337 | m_isOk = err == 0; | |
338 | ||
339 | if ( !m_isOk ) | |
340 | { | |
341 | wxLogApiError(_T("pthread_cond_init()"), err); | |
342 | } | |
343 | } | |
344 | ||
345 | wxConditionInternal::~wxConditionInternal() | |
346 | { | |
347 | if ( m_isOk ) | |
348 | { | |
349 | int err = pthread_cond_destroy(&m_cond); | |
350 | if ( err != 0 ) | |
351 | { | |
352 | wxLogApiError(_T("pthread_cond_destroy()"), err); | |
353 | } | |
354 | } | |
355 | } | |
356 | ||
357 | wxCondError wxConditionInternal::Wait() | |
358 | { | |
359 | int err = pthread_cond_wait(&m_cond, GetPMutex()); | |
360 | if ( err != 0 ) | |
361 | { | |
362 | wxLogApiError(_T("pthread_cond_wait()"), err); | |
363 | ||
364 | return wxCOND_MISC_ERROR; | |
365 | } | |
366 | ||
367 | return wxCOND_NO_ERROR; | |
368 | } | |
369 | ||
370 | wxCondError wxConditionInternal::WaitTimeout(unsigned long milliseconds) | |
371 | { | |
372 | wxLongLong curtime = wxGetLocalTimeMillis(); | |
373 | curtime += milliseconds; | |
374 | wxLongLong temp = curtime / 1000; | |
375 | int sec = temp.GetLo(); | |
376 | temp *= 1000; | |
377 | temp = curtime - temp; | |
378 | int millis = temp.GetLo(); | |
379 | ||
380 | timespec tspec; | |
381 | ||
382 | tspec.tv_sec = sec; | |
383 | tspec.tv_nsec = millis * 1000L * 1000L; | |
384 | ||
385 | int err = pthread_cond_timedwait( &m_cond, GetPMutex(), &tspec ); | |
386 | switch ( err ) | |
387 | { | |
388 | case ETIMEDOUT: | |
389 | return wxCOND_TIMEOUT; | |
390 | ||
391 | case 0: | |
392 | return wxCOND_NO_ERROR; | |
393 | ||
394 | default: | |
395 | wxLogApiError(_T("pthread_cond_timedwait()"), err); | |
396 | } | |
397 | ||
398 | return wxCOND_MISC_ERROR; | |
399 | } | |
400 | ||
401 | wxCondError wxConditionInternal::Signal() | |
402 | { | |
403 | int err = pthread_cond_signal(&m_cond); | |
404 | if ( err != 0 ) | |
405 | { | |
406 | wxLogApiError(_T("pthread_cond_signal()"), err); | |
407 | ||
408 | return wxCOND_MISC_ERROR; | |
409 | } | |
410 | ||
411 | return wxCOND_NO_ERROR; | |
412 | } | |
413 | ||
414 | wxCondError wxConditionInternal::Broadcast() | |
415 | { | |
416 | int err = pthread_cond_broadcast(&m_cond); | |
417 | if ( err != 0 ) | |
418 | { | |
419 | wxLogApiError(_T("pthread_cond_broadcast()"), err); | |
420 | ||
421 | return wxCOND_MISC_ERROR; | |
422 | } | |
423 | ||
424 | return wxCOND_NO_ERROR; | |
425 | } | |
426 | ||
427 | // =========================================================================== | |
428 | // wxSemaphore implementation | |
429 | // =========================================================================== | |
430 | ||
431 | // --------------------------------------------------------------------------- | |
432 | // wxSemaphoreInternal | |
433 | // --------------------------------------------------------------------------- | |
434 | ||
435 | // we implement the semaphores using mutexes and conditions instead of using | |
436 | // the sem_xxx() POSIX functions because they're not widely available and also | |
437 | // because it's impossible to implement WaitTimeout() using them | |
438 | class wxSemaphoreInternal | |
439 | { | |
440 | public: | |
441 | wxSemaphoreInternal(int initialcount, int maxcount); | |
442 | ||
443 | bool IsOk() const { return m_isOk; } | |
444 | ||
445 | wxSemaError Wait(); | |
446 | wxSemaError TryWait(); | |
447 | wxSemaError WaitTimeout(unsigned long milliseconds); | |
448 | ||
449 | wxSemaError Post(); | |
450 | ||
451 | private: | |
452 | wxMutex m_mutex; | |
453 | wxCondition m_cond; | |
454 | ||
455 | size_t m_count, | |
456 | m_maxcount; | |
457 | ||
458 | bool m_isOk; | |
459 | }; | |
460 | ||
461 | wxSemaphoreInternal::wxSemaphoreInternal(int initialcount, int maxcount) | |
462 | : m_cond(m_mutex) | |
463 | { | |
464 | ||
465 | if ( (initialcount < 0 || maxcount < 0) || | |
466 | ((maxcount > 0) && (initialcount > maxcount)) ) | |
467 | { | |
468 | wxFAIL_MSG( _T("wxSemaphore: invalid initial or maximal count") ); | |
469 | ||
470 | m_isOk = FALSE; | |
471 | } | |
472 | else | |
473 | { | |
474 | m_maxcount = (size_t)maxcount; | |
475 | m_count = (size_t)initialcount; | |
476 | } | |
477 | ||
478 | m_isOk = m_mutex.IsOk() && m_cond.IsOk(); | |
479 | } | |
480 | ||
481 | wxSemaError wxSemaphoreInternal::Wait() | |
482 | { | |
483 | wxMutexLocker locker(m_mutex); | |
484 | ||
485 | while ( m_count == 0 ) | |
486 | { | |
487 | wxLogTrace(TRACE_SEMA, | |
488 | "Thread %ld waiting for semaphore to become signalled", | |
489 | wxThread::GetCurrentId()); | |
490 | ||
491 | if ( m_cond.Wait() != wxCOND_NO_ERROR ) | |
492 | return wxSEMA_MISC_ERROR; | |
493 | ||
494 | wxLogTrace(TRACE_SEMA, | |
495 | "Thread %ld finished waiting for semaphore, count = %u", | |
496 | wxThread::GetCurrentId(), m_count); | |
497 | } | |
498 | ||
499 | m_count--; | |
500 | ||
501 | return wxSEMA_NO_ERROR; | |
502 | } | |
503 | ||
504 | wxSemaError wxSemaphoreInternal::TryWait() | |
505 | { | |
506 | wxMutexLocker locker(m_mutex); | |
507 | ||
508 | if ( m_count == 0 ) | |
509 | return wxSEMA_BUSY; | |
510 | ||
511 | m_count--; | |
512 | ||
513 | return wxSEMA_NO_ERROR; | |
514 | } | |
515 | ||
516 | wxSemaError wxSemaphoreInternal::WaitTimeout(unsigned long milliseconds) | |
517 | { | |
518 | wxMutexLocker locker(m_mutex); | |
519 | ||
520 | wxLongLong startTime = wxGetLocalTimeMillis(); | |
521 | ||
522 | while ( m_count == 0 ) | |
523 | { | |
524 | wxLongLong elapsed = wxGetLocalTimeMillis() - startTime; | |
525 | long remainingTime = (long)milliseconds - (long)elapsed.GetLo(); | |
526 | if ( remainingTime <= 0 ) | |
527 | { | |
528 | // timeout | |
529 | return wxSEMA_TIMEOUT; | |
530 | } | |
531 | ||
532 | if ( m_cond.Wait(remainingTime) != wxCOND_NO_ERROR ) | |
533 | return wxSEMA_MISC_ERROR; | |
534 | } | |
535 | ||
536 | m_count--; | |
537 | ||
538 | return wxSEMA_NO_ERROR; | |
539 | } | |
540 | ||
541 | wxSemaError wxSemaphoreInternal::Post() | |
542 | { | |
543 | wxMutexLocker locker(m_mutex); | |
544 | ||
545 | if ( m_maxcount > 0 && m_count == m_maxcount ) | |
546 | { | |
547 | return wxSEMA_OVERFLOW; | |
548 | } | |
549 | ||
550 | m_count++; | |
551 | ||
552 | wxLogTrace(TRACE_SEMA, | |
553 | "Thread %ld about to signal semaphore, count = %u", | |
554 | wxThread::GetCurrentId(), m_count); | |
555 | ||
556 | return m_cond.Signal() == wxCOND_NO_ERROR ? wxSEMA_NO_ERROR | |
557 | : wxSEMA_MISC_ERROR; | |
558 | } | |
559 | ||
560 | // =========================================================================== | |
561 | // wxThread implementation | |
562 | // =========================================================================== | |
563 | ||
564 | // the thread callback functions must have the C linkage | |
565 | extern "C" | |
566 | { | |
567 | ||
568 | #if HAVE_THREAD_CLEANUP_FUNCTIONS | |
569 | // thread exit function | |
570 | void wxPthreadCleanup(void *ptr); | |
571 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
572 | ||
573 | void *wxPthreadStart(void *ptr); | |
574 | ||
575 | } // extern "C" | |
576 | ||
577 | // ---------------------------------------------------------------------------- | |
578 | // wxThreadInternal | |
579 | // ---------------------------------------------------------------------------- | |
580 | ||
581 | class wxThreadInternal | |
582 | { | |
583 | public: | |
584 | wxThreadInternal(); | |
585 | ~wxThreadInternal(); | |
586 | ||
587 | // thread entry function | |
588 | static void *PthreadStart(wxThread *thread); | |
589 | ||
590 | // thread actions | |
591 | // start the thread | |
592 | wxThreadError Run(); | |
593 | // unblock the thread allowing it to run | |
594 | void SignalRun() { m_semRun.Post(); } | |
595 | // ask the thread to terminate | |
596 | void Wait(); | |
597 | // go to sleep until Resume() is called | |
598 | void Pause(); | |
599 | // resume the thread | |
600 | void Resume(); | |
601 | ||
602 | // accessors | |
603 | // priority | |
604 | int GetPriority() const { return m_prio; } | |
605 | void SetPriority(int prio) { m_prio = prio; } | |
606 | // state | |
607 | wxThreadState GetState() const { return m_state; } | |
608 | void SetState(wxThreadState state) | |
609 | { | |
610 | #ifdef __WXDEBUG__ | |
611 | static const wxChar *stateNames[] = | |
612 | { | |
613 | _T("NEW"), | |
614 | _T("RUNNING"), | |
615 | _T("PAUSED"), | |
616 | _T("EXITED"), | |
617 | }; | |
618 | ||
619 | wxLogTrace(TRACE_THREADS, _T("Thread %ld: %s => %s."), | |
620 | GetId(), stateNames[m_state], stateNames[state]); | |
621 | #endif // __WXDEBUG__ | |
622 | ||
623 | m_state = state; | |
624 | } | |
625 | // id | |
626 | pthread_t GetId() const { return m_threadId; } | |
627 | pthread_t *GetIdPtr() { return &m_threadId; } | |
628 | // "cancelled" flag | |
629 | void SetCancelFlag() { m_cancelled = TRUE; } | |
630 | bool WasCancelled() const { return m_cancelled; } | |
631 | // exit code | |
632 | void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; } | |
633 | wxThread::ExitCode GetExitCode() const { return m_exitcode; } | |
634 | ||
635 | // the pause flag | |
636 | void SetReallyPaused(bool paused) { m_isPaused = paused; } | |
637 | bool IsReallyPaused() const { return m_isPaused; } | |
638 | ||
639 | // tell the thread that it is a detached one | |
640 | void Detach() | |
641 | { | |
642 | wxCriticalSectionLocker lock(m_csJoinFlag); | |
643 | ||
644 | m_shouldBeJoined = FALSE; | |
645 | m_isDetached = TRUE; | |
646 | } | |
647 | ||
648 | #if HAVE_THREAD_CLEANUP_FUNCTIONS | |
649 | // this is used by wxPthreadCleanup() only | |
650 | static void Cleanup(wxThread *thread); | |
651 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
652 | ||
653 | private: | |
654 | pthread_t m_threadId; // id of the thread | |
655 | wxThreadState m_state; // see wxThreadState enum | |
656 | int m_prio; // in wxWindows units: from 0 to 100 | |
657 | ||
658 | // this flag is set when the thread should terminate | |
659 | bool m_cancelled; | |
660 | ||
661 | // this flag is set when the thread is blocking on m_semSuspend | |
662 | bool m_isPaused; | |
663 | ||
664 | // the thread exit code - only used for joinable (!detached) threads and | |
665 | // is only valid after the thread termination | |
666 | wxThread::ExitCode m_exitcode; | |
667 | ||
668 | // many threads may call Wait(), but only one of them should call | |
669 | // pthread_join(), so we have to keep track of this | |
670 | wxCriticalSection m_csJoinFlag; | |
671 | bool m_shouldBeJoined; | |
672 | bool m_isDetached; | |
673 | ||
674 | // this semaphore is posted by Run() and the threads Entry() is not | |
675 | // called before it is done | |
676 | wxSemaphore m_semRun; | |
677 | ||
678 | // this one is signaled when the thread should resume after having been | |
679 | // Pause()d | |
680 | wxSemaphore m_semSuspend; | |
681 | }; | |
682 | ||
683 | // ---------------------------------------------------------------------------- | |
684 | // thread startup and exit functions | |
685 | // ---------------------------------------------------------------------------- | |
686 | ||
687 | void *wxPthreadStart(void *ptr) | |
688 | { | |
689 | return wxThreadInternal::PthreadStart((wxThread *)ptr); | |
690 | } | |
691 | ||
692 | void *wxThreadInternal::PthreadStart(wxThread *thread) | |
693 | { | |
694 | wxThreadInternal *pthread = thread->m_internal; | |
695 | ||
696 | wxLogTrace(TRACE_THREADS, _T("Thread %ld started."), pthread->GetId()); | |
697 | ||
698 | // associate the thread pointer with the newly created thread so that | |
699 | // wxThread::This() will work | |
700 | int rc = pthread_setspecific(gs_keySelf, thread); | |
701 | if ( rc != 0 ) | |
702 | { | |
703 | wxLogSysError(rc, _("Cannot start thread: error writing TLS")); | |
704 | ||
705 | return (void *)-1; | |
706 | } | |
707 | ||
708 | // have to declare this before pthread_cleanup_push() which defines a | |
709 | // block! | |
710 | bool dontRunAtAll; | |
711 | ||
712 | #if HAVE_THREAD_CLEANUP_FUNCTIONS | |
713 | // install the cleanup handler which will be called if the thread is | |
714 | // cancelled | |
715 | pthread_cleanup_push(wxPthreadCleanup, thread); | |
716 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
717 | ||
718 | // wait for the semaphore to be posted from Run() | |
719 | pthread->m_semRun.Wait(); | |
720 | ||
721 | // test whether we should run the run at all - may be it was deleted | |
722 | // before it started to Run()? | |
723 | { | |
724 | wxCriticalSectionLocker lock(thread->m_critsect); | |
725 | ||
726 | dontRunAtAll = pthread->GetState() == STATE_NEW && | |
727 | pthread->WasCancelled(); | |
728 | } | |
729 | ||
730 | if ( !dontRunAtAll ) | |
731 | { | |
732 | // call the main entry | |
733 | wxLogTrace(TRACE_THREADS, _T("Thread %ld about to enter its Entry()."), | |
734 | pthread->GetId()); | |
735 | ||
736 | pthread->m_exitcode = thread->Entry(); | |
737 | ||
738 | wxLogTrace(TRACE_THREADS, _T("Thread %ld Entry() returned %lu."), | |
739 | pthread->GetId(), (unsigned long)pthread->m_exitcode); | |
740 | ||
741 | { | |
742 | wxCriticalSectionLocker lock(thread->m_critsect); | |
743 | ||
744 | // change the state of the thread to "exited" so that | |
745 | // wxPthreadCleanup handler won't do anything from now (if it's | |
746 | // called before we do pthread_cleanup_pop below) | |
747 | pthread->SetState(STATE_EXITED); | |
748 | } | |
749 | } | |
750 | ||
751 | // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop | |
752 | // contains the matching '}' for the '{' in push, so they must be used | |
753 | // in the same block! | |
754 | #if HAVE_THREAD_CLEANUP_FUNCTIONS | |
755 | // remove the cleanup handler without executing it | |
756 | pthread_cleanup_pop(FALSE); | |
757 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
758 | ||
759 | if ( dontRunAtAll ) | |
760 | { | |
761 | // FIXME: deleting a possibly joinable thread here??? | |
762 | delete thread; | |
763 | ||
764 | return EXITCODE_CANCELLED; | |
765 | } | |
766 | else | |
767 | { | |
768 | // terminate the thread | |
769 | thread->Exit(pthread->m_exitcode); | |
770 | ||
771 | wxFAIL_MSG(wxT("wxThread::Exit() can't return.")); | |
772 | ||
773 | return NULL; | |
774 | } | |
775 | } | |
776 | ||
777 | #if HAVE_THREAD_CLEANUP_FUNCTIONS | |
778 | ||
779 | // this handler is called when the thread is cancelled | |
780 | extern "C" void wxPthreadCleanup(void *ptr) | |
781 | { | |
782 | wxThreadInternal::Cleanup((wxThread *)ptr); | |
783 | } | |
784 | ||
785 | void wxThreadInternal::Cleanup(wxThread *thread) | |
786 | { | |
787 | { | |
788 | wxCriticalSectionLocker lock(thread->m_critsect); | |
789 | if ( thread->m_internal->GetState() == STATE_EXITED ) | |
790 | { | |
791 | // thread is already considered as finished. | |
792 | return; | |
793 | } | |
794 | } | |
795 | ||
796 | // exit the thread gracefully | |
797 | thread->Exit(EXITCODE_CANCELLED); | |
798 | } | |
799 | ||
800 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
801 | ||
802 | // ---------------------------------------------------------------------------- | |
803 | // wxThreadInternal | |
804 | // ---------------------------------------------------------------------------- | |
805 | ||
806 | wxThreadInternal::wxThreadInternal() | |
807 | { | |
808 | m_state = STATE_NEW; | |
809 | m_cancelled = FALSE; | |
810 | m_prio = WXTHREAD_DEFAULT_PRIORITY; | |
811 | m_threadId = 0; | |
812 | m_exitcode = 0; | |
813 | ||
814 | // set to TRUE only when the thread starts waiting on m_semSuspend | |
815 | m_isPaused = FALSE; | |
816 | ||
817 | // defaults for joinable threads | |
818 | m_shouldBeJoined = TRUE; | |
819 | m_isDetached = FALSE; | |
820 | } | |
821 | ||
822 | wxThreadInternal::~wxThreadInternal() | |
823 | { | |
824 | } | |
825 | ||
826 | wxThreadError wxThreadInternal::Run() | |
827 | { | |
828 | wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING, | |
829 | wxT("thread may only be started once after Create()") ); | |
830 | ||
831 | SetState(STATE_RUNNING); | |
832 | ||
833 | // wake up threads waiting for our start | |
834 | SignalRun(); | |
835 | ||
836 | return wxTHREAD_NO_ERROR; | |
837 | } | |
838 | ||
839 | void wxThreadInternal::Wait() | |
840 | { | |
841 | wxCHECK_RET( !m_isDetached, _T("can't wait for a detached thread") ); | |
842 | ||
843 | // if the thread we're waiting for is waiting for the GUI mutex, we will | |
844 | // deadlock so make sure we release it temporarily | |
845 | if ( wxThread::IsMain() ) | |
846 | wxMutexGuiLeave(); | |
847 | ||
848 | wxLogTrace(TRACE_THREADS, | |
849 | _T("Starting to wait for thread %ld to exit."), GetId()); | |
850 | ||
851 | // to avoid memory leaks we should call pthread_join(), but it must only be | |
852 | // done once so use a critical section to serialize the code below | |
853 | { | |
854 | wxCriticalSectionLocker lock(m_csJoinFlag); | |
855 | ||
856 | if ( m_shouldBeJoined ) | |
857 | { | |
858 | // FIXME shouldn't we set cancellation type to DISABLED here? If | |
859 | // we're cancelled inside pthread_join(), things will almost | |
860 | // certainly break - but if we disable the cancellation, we | |
861 | // might deadlock | |
862 | if ( pthread_join((pthread_t)GetId(), &m_exitcode) != 0 ) | |
863 | { | |
864 | // this is a serious problem, so use wxLogError and not | |
865 | // wxLogDebug: it is possible to bring the system to its knees | |
866 | // by creating too many threads and not joining them quite | |
867 | // easily | |
868 | wxLogError(_("Failed to join a thread, potential memory leak " | |
869 | "detected - please restart the program")); | |
870 | } | |
871 | ||
872 | m_shouldBeJoined = FALSE; | |
873 | } | |
874 | } | |
875 | ||
876 | // reacquire GUI mutex | |
877 | if ( wxThread::IsMain() ) | |
878 | wxMutexGuiEnter(); | |
879 | } | |
880 | ||
881 | void wxThreadInternal::Pause() | |
882 | { | |
883 | // the state is set from the thread which pauses us first, this function | |
884 | // is called later so the state should have been already set | |
885 | wxCHECK_RET( m_state == STATE_PAUSED, | |
886 | wxT("thread must first be paused with wxThread::Pause().") ); | |
887 | ||
888 | wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), GetId()); | |
889 | ||
890 | // wait until the semaphore is Post()ed from Resume() | |
891 | m_semSuspend.Wait(); | |
892 | } | |
893 | ||
894 | void wxThreadInternal::Resume() | |
895 | { | |
896 | wxCHECK_RET( m_state == STATE_PAUSED, | |
897 | wxT("can't resume thread which is not suspended.") ); | |
898 | ||
899 | // the thread might be not actually paused yet - if there were no call to | |
900 | // TestDestroy() since the last call to Pause() for example | |
901 | if ( IsReallyPaused() ) | |
902 | { | |
903 | wxLogTrace(TRACE_THREADS, _T("Waking up thread %ld"), GetId()); | |
904 | ||
905 | // wake up Pause() | |
906 | m_semSuspend.Post(); | |
907 | ||
908 | // reset the flag | |
909 | SetReallyPaused(FALSE); | |
910 | } | |
911 | else | |
912 | { | |
913 | wxLogTrace(TRACE_THREADS, _T("Thread %ld is not yet really paused"), | |
914 | GetId()); | |
915 | } | |
916 | ||
917 | SetState(STATE_RUNNING); | |
918 | } | |
919 | ||
920 | // ----------------------------------------------------------------------------- | |
921 | // wxThread static functions | |
922 | // ----------------------------------------------------------------------------- | |
923 | ||
924 | wxThread *wxThread::This() | |
925 | { | |
926 | return (wxThread *)pthread_getspecific(gs_keySelf); | |
927 | } | |
928 | ||
929 | bool wxThread::IsMain() | |
930 | { | |
931 | return (bool)pthread_equal(pthread_self(), gs_tidMain); | |
932 | } | |
933 | ||
934 | void wxThread::Yield() | |
935 | { | |
936 | #ifdef HAVE_SCHED_YIELD | |
937 | sched_yield(); | |
938 | #endif | |
939 | } | |
940 | ||
941 | void wxThread::Sleep(unsigned long milliseconds) | |
942 | { | |
943 | wxUsleep(milliseconds); | |
944 | } | |
945 | ||
946 | int wxThread::GetCPUCount() | |
947 | { | |
948 | #if defined(__LINUX__) && wxUSE_FFILE | |
949 | // read from proc (can't use wxTextFile here because it's a special file: | |
950 | // it has 0 size but still can be read from) | |
951 | wxLogNull nolog; | |
952 | ||
953 | wxFFile file(_T("/proc/cpuinfo")); | |
954 | if ( file.IsOpened() ) | |
955 | { | |
956 | // slurp the whole file | |
957 | wxString s; | |
958 | if ( file.ReadAll(&s) ) | |
959 | { | |
960 | // (ab)use Replace() to find the number of "processor" strings | |
961 | size_t count = s.Replace(_T("processor"), _T("")); | |
962 | if ( count > 0 ) | |
963 | { | |
964 | return count; | |
965 | } | |
966 | ||
967 | wxLogDebug(_T("failed to parse /proc/cpuinfo")); | |
968 | } | |
969 | else | |
970 | { | |
971 | wxLogDebug(_T("failed to read /proc/cpuinfo")); | |
972 | } | |
973 | } | |
974 | #elif defined(_SC_NPROCESSORS_ONLN) | |
975 | // this works for Solaris | |
976 | int rc = sysconf(_SC_NPROCESSORS_ONLN); | |
977 | if ( rc != -1 ) | |
978 | { | |
979 | return rc; | |
980 | } | |
981 | #endif // different ways to get number of CPUs | |
982 | ||
983 | // unknown | |
984 | return -1; | |
985 | } | |
986 | ||
987 | #ifdef __VMS | |
988 | // VMS is a 64 bit system and threads have 64 bit pointers. | |
989 | // ??? also needed for other systems???? | |
990 | unsigned long long wxThread::GetCurrentId() | |
991 | { | |
992 | return (unsigned long long)pthread_self(); | |
993 | #else | |
994 | unsigned long wxThread::GetCurrentId() | |
995 | { | |
996 | return (unsigned long)pthread_self(); | |
997 | #endif | |
998 | } | |
999 | ||
1000 | bool wxThread::SetConcurrency(size_t level) | |
1001 | { | |
1002 | #ifdef HAVE_THR_SETCONCURRENCY | |
1003 | int rc = thr_setconcurrency(level); | |
1004 | if ( rc != 0 ) | |
1005 | { | |
1006 | wxLogSysError(rc, _T("thr_setconcurrency() failed")); | |
1007 | } | |
1008 | ||
1009 | return rc == 0; | |
1010 | #else // !HAVE_THR_SETCONCURRENCY | |
1011 | // ok only for the default value | |
1012 | return level == 0; | |
1013 | #endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY | |
1014 | } | |
1015 | ||
1016 | // ----------------------------------------------------------------------------- | |
1017 | // creating thread | |
1018 | // ----------------------------------------------------------------------------- | |
1019 | ||
1020 | wxThread::wxThread(wxThreadKind kind) | |
1021 | { | |
1022 | // add this thread to the global list of all threads | |
1023 | gs_allThreads.Add(this); | |
1024 | ||
1025 | m_internal = new wxThreadInternal(); | |
1026 | ||
1027 | m_isDetached = kind == wxTHREAD_DETACHED; | |
1028 | } | |
1029 | ||
1030 | wxThreadError wxThread::Create(unsigned int WXUNUSED(stackSize)) | |
1031 | { | |
1032 | if ( m_internal->GetState() != STATE_NEW ) | |
1033 | { | |
1034 | // don't recreate thread | |
1035 | return wxTHREAD_RUNNING; | |
1036 | } | |
1037 | ||
1038 | // set up the thread attribute: right now, we only set thread priority | |
1039 | pthread_attr_t attr; | |
1040 | pthread_attr_init(&attr); | |
1041 | ||
1042 | #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS | |
1043 | int policy; | |
1044 | if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 ) | |
1045 | { | |
1046 | wxLogError(_("Cannot retrieve thread scheduling policy.")); | |
1047 | } | |
1048 | ||
1049 | #ifdef __VMS__ | |
1050 | /* the pthread.h contains too many spaces. This is a work-around */ | |
1051 | # undef sched_get_priority_max | |
1052 | #undef sched_get_priority_min | |
1053 | #define sched_get_priority_max(_pol_) \ | |
1054 | (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX) | |
1055 | #define sched_get_priority_min(_pol_) \ | |
1056 | (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN) | |
1057 | #endif | |
1058 | ||
1059 | int max_prio = sched_get_priority_max(policy), | |
1060 | min_prio = sched_get_priority_min(policy), | |
1061 | prio = m_internal->GetPriority(); | |
1062 | ||
1063 | if ( min_prio == -1 || max_prio == -1 ) | |
1064 | { | |
1065 | wxLogError(_("Cannot get priority range for scheduling policy %d."), | |
1066 | policy); | |
1067 | } | |
1068 | else if ( max_prio == min_prio ) | |
1069 | { | |
1070 | if ( prio != WXTHREAD_DEFAULT_PRIORITY ) | |
1071 | { | |
1072 | // notify the programmer that this doesn't work here | |
1073 | wxLogWarning(_("Thread priority setting is ignored.")); | |
1074 | } | |
1075 | //else: we have default priority, so don't complain | |
1076 | ||
1077 | // anyhow, don't do anything because priority is just ignored | |
1078 | } | |
1079 | else | |
1080 | { | |
1081 | struct sched_param sp; | |
1082 | if ( pthread_attr_getschedparam(&attr, &sp) != 0 ) | |
1083 | { | |
1084 | wxFAIL_MSG(_T("pthread_attr_getschedparam() failed")); | |
1085 | } | |
1086 | ||
1087 | sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100; | |
1088 | ||
1089 | if ( pthread_attr_setschedparam(&attr, &sp) != 0 ) | |
1090 | { | |
1091 | wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed")); | |
1092 | } | |
1093 | } | |
1094 | #endif // HAVE_THREAD_PRIORITY_FUNCTIONS | |
1095 | ||
1096 | #ifdef HAVE_PTHREAD_ATTR_SETSCOPE | |
1097 | // this will make the threads created by this process really concurrent | |
1098 | if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 ) | |
1099 | { | |
1100 | wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed")); | |
1101 | } | |
1102 | #endif // HAVE_PTHREAD_ATTR_SETSCOPE | |
1103 | ||
1104 | // VZ: assume that this one is always available (it's rather fundamental), | |
1105 | // if this function is ever missing we should try to use | |
1106 | // pthread_detach() instead (after thread creation) | |
1107 | if ( m_isDetached ) | |
1108 | { | |
1109 | if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 ) | |
1110 | { | |
1111 | wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed")); | |
1112 | } | |
1113 | ||
1114 | // never try to join detached threads | |
1115 | m_internal->Detach(); | |
1116 | } | |
1117 | //else: threads are created joinable by default, it's ok | |
1118 | ||
1119 | // create the new OS thread object | |
1120 | int rc = pthread_create | |
1121 | ( | |
1122 | m_internal->GetIdPtr(), | |
1123 | &attr, | |
1124 | wxPthreadStart, | |
1125 | (void *)this | |
1126 | ); | |
1127 | ||
1128 | if ( pthread_attr_destroy(&attr) != 0 ) | |
1129 | { | |
1130 | wxFAIL_MSG(_T("pthread_attr_destroy() failed")); | |
1131 | } | |
1132 | ||
1133 | if ( rc != 0 ) | |
1134 | { | |
1135 | m_internal->SetState(STATE_EXITED); | |
1136 | ||
1137 | return wxTHREAD_NO_RESOURCE; | |
1138 | } | |
1139 | ||
1140 | return wxTHREAD_NO_ERROR; | |
1141 | } | |
1142 | ||
1143 | wxThreadError wxThread::Run() | |
1144 | { | |
1145 | wxCriticalSectionLocker lock(m_critsect); | |
1146 | ||
1147 | wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR, | |
1148 | wxT("must call wxThread::Create() first") ); | |
1149 | ||
1150 | return m_internal->Run(); | |
1151 | } | |
1152 | ||
1153 | // ----------------------------------------------------------------------------- | |
1154 | // misc accessors | |
1155 | // ----------------------------------------------------------------------------- | |
1156 | ||
1157 | void wxThread::SetPriority(unsigned int prio) | |
1158 | { | |
1159 | wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) && | |
1160 | ((int)prio <= (int)WXTHREAD_MAX_PRIORITY), | |
1161 | wxT("invalid thread priority") ); | |
1162 | ||
1163 | wxCriticalSectionLocker lock(m_critsect); | |
1164 | ||
1165 | switch ( m_internal->GetState() ) | |
1166 | { | |
1167 | case STATE_NEW: | |
1168 | // thread not yet started, priority will be set when it is | |
1169 | m_internal->SetPriority(prio); | |
1170 | break; | |
1171 | ||
1172 | case STATE_RUNNING: | |
1173 | case STATE_PAUSED: | |
1174 | #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS | |
1175 | { | |
1176 | struct sched_param sparam; | |
1177 | sparam.sched_priority = prio; | |
1178 | ||
1179 | if ( pthread_setschedparam(m_internal->GetId(), | |
1180 | SCHED_OTHER, &sparam) != 0 ) | |
1181 | { | |
1182 | wxLogError(_("Failed to set thread priority %d."), prio); | |
1183 | } | |
1184 | } | |
1185 | #endif // HAVE_THREAD_PRIORITY_FUNCTIONS | |
1186 | break; | |
1187 | ||
1188 | case STATE_EXITED: | |
1189 | default: | |
1190 | wxFAIL_MSG(wxT("impossible to set thread priority in this state")); | |
1191 | } | |
1192 | } | |
1193 | ||
1194 | unsigned int wxThread::GetPriority() const | |
1195 | { | |
1196 | wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); | |
1197 | ||
1198 | return m_internal->GetPriority(); | |
1199 | } | |
1200 | ||
1201 | wxThreadIdType wxThread::GetId() const | |
1202 | { | |
1203 | return (wxThreadIdType) m_internal->GetId(); | |
1204 | } | |
1205 | ||
1206 | // ----------------------------------------------------------------------------- | |
1207 | // pause/resume | |
1208 | // ----------------------------------------------------------------------------- | |
1209 | ||
1210 | wxThreadError wxThread::Pause() | |
1211 | { | |
1212 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, | |
1213 | _T("a thread can't pause itself") ); | |
1214 | ||
1215 | wxCriticalSectionLocker lock(m_critsect); | |
1216 | ||
1217 | if ( m_internal->GetState() != STATE_RUNNING ) | |
1218 | { | |
1219 | wxLogDebug(wxT("Can't pause thread which is not running.")); | |
1220 | ||
1221 | return wxTHREAD_NOT_RUNNING; | |
1222 | } | |
1223 | ||
1224 | // just set a flag, the thread will be really paused only during the next | |
1225 | // call to TestDestroy() | |
1226 | m_internal->SetState(STATE_PAUSED); | |
1227 | ||
1228 | return wxTHREAD_NO_ERROR; | |
1229 | } | |
1230 | ||
1231 | wxThreadError wxThread::Resume() | |
1232 | { | |
1233 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, | |
1234 | _T("a thread can't resume itself") ); | |
1235 | ||
1236 | wxCriticalSectionLocker lock(m_critsect); | |
1237 | ||
1238 | wxThreadState state = m_internal->GetState(); | |
1239 | ||
1240 | switch ( state ) | |
1241 | { | |
1242 | case STATE_PAUSED: | |
1243 | wxLogTrace(TRACE_THREADS, _T("Thread %ld suspended, resuming."), | |
1244 | GetId()); | |
1245 | ||
1246 | m_internal->Resume(); | |
1247 | ||
1248 | return wxTHREAD_NO_ERROR; | |
1249 | ||
1250 | case STATE_EXITED: | |
1251 | wxLogTrace(TRACE_THREADS, _T("Thread %ld exited, won't resume."), | |
1252 | GetId()); | |
1253 | return wxTHREAD_NO_ERROR; | |
1254 | ||
1255 | default: | |
1256 | wxLogDebug(_T("Attempt to resume a thread which is not paused.")); | |
1257 | ||
1258 | return wxTHREAD_MISC_ERROR; | |
1259 | } | |
1260 | } | |
1261 | ||
1262 | // ----------------------------------------------------------------------------- | |
1263 | // exiting thread | |
1264 | // ----------------------------------------------------------------------------- | |
1265 | ||
1266 | wxThread::ExitCode wxThread::Wait() | |
1267 | { | |
1268 | wxCHECK_MSG( This() != this, (ExitCode)-1, | |
1269 | _T("a thread can't wait for itself") ); | |
1270 | ||
1271 | wxCHECK_MSG( !m_isDetached, (ExitCode)-1, | |
1272 | _T("can't wait for detached thread") ); | |
1273 | ||
1274 | m_internal->Wait(); | |
1275 | ||
1276 | return m_internal->GetExitCode(); | |
1277 | } | |
1278 | ||
1279 | wxThreadError wxThread::Delete(ExitCode *rc) | |
1280 | { | |
1281 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, | |
1282 | _T("a thread can't delete itself") ); | |
1283 | ||
1284 | bool isDetached = m_isDetached; | |
1285 | ||
1286 | m_critsect.Enter(); | |
1287 | wxThreadState state = m_internal->GetState(); | |
1288 | ||
1289 | // ask the thread to stop | |
1290 | m_internal->SetCancelFlag(); | |
1291 | ||
1292 | m_critsect.Leave(); | |
1293 | ||
1294 | switch ( state ) | |
1295 | { | |
1296 | case STATE_NEW: | |
1297 | // we need to wake up the thread so that PthreadStart() will | |
1298 | // terminate - right now it's blocking on run semaphore in | |
1299 | // PthreadStart() | |
1300 | m_internal->SignalRun(); | |
1301 | ||
1302 | // fall through | |
1303 | ||
1304 | case STATE_EXITED: | |
1305 | // nothing to do | |
1306 | break; | |
1307 | ||
1308 | case STATE_PAUSED: | |
1309 | // resume the thread first | |
1310 | m_internal->Resume(); | |
1311 | ||
1312 | // fall through | |
1313 | ||
1314 | default: | |
1315 | if ( !isDetached ) | |
1316 | { | |
1317 | // wait until the thread stops | |
1318 | m_internal->Wait(); | |
1319 | ||
1320 | if ( rc ) | |
1321 | { | |
1322 | // return the exit code of the thread | |
1323 | *rc = m_internal->GetExitCode(); | |
1324 | } | |
1325 | } | |
1326 | //else: can't wait for detached threads | |
1327 | } | |
1328 | ||
1329 | return wxTHREAD_NO_ERROR; | |
1330 | } | |
1331 | ||
1332 | wxThreadError wxThread::Kill() | |
1333 | { | |
1334 | wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR, | |
1335 | _T("a thread can't kill itself") ); | |
1336 | ||
1337 | switch ( m_internal->GetState() ) | |
1338 | { | |
1339 | case STATE_NEW: | |
1340 | case STATE_EXITED: | |
1341 | return wxTHREAD_NOT_RUNNING; | |
1342 | ||
1343 | case STATE_PAUSED: | |
1344 | // resume the thread first | |
1345 | Resume(); | |
1346 | ||
1347 | // fall through | |
1348 | ||
1349 | default: | |
1350 | #ifdef HAVE_PTHREAD_CANCEL | |
1351 | if ( pthread_cancel(m_internal->GetId()) != 0 ) | |
1352 | #endif | |
1353 | { | |
1354 | wxLogError(_("Failed to terminate a thread.")); | |
1355 | ||
1356 | return wxTHREAD_MISC_ERROR; | |
1357 | } | |
1358 | ||
1359 | if ( m_isDetached ) | |
1360 | { | |
1361 | // if we use cleanup function, this will be done from | |
1362 | // wxPthreadCleanup() | |
1363 | #if !HAVE_THREAD_CLEANUP_FUNCTIONS | |
1364 | ScheduleThreadForDeletion(); | |
1365 | ||
1366 | // don't call OnExit() here, it can only be called in the | |
1367 | // threads context and we're in the context of another thread | |
1368 | ||
1369 | DeleteThread(this); | |
1370 | #endif // HAVE_THREAD_CLEANUP_FUNCTIONS | |
1371 | } | |
1372 | else | |
1373 | { | |
1374 | m_internal->SetExitCode(EXITCODE_CANCELLED); | |
1375 | } | |
1376 | ||
1377 | return wxTHREAD_NO_ERROR; | |
1378 | } | |
1379 | } | |
1380 | ||
1381 | void wxThread::Exit(ExitCode status) | |
1382 | { | |
1383 | wxASSERT_MSG( This() == this, | |
1384 | _T("wxThread::Exit() can only be called in the " | |
1385 | "context of the same thread") ); | |
1386 | ||
1387 | if ( m_isDetached ) | |
1388 | { | |
1389 | // from the moment we call OnExit(), the main program may terminate at | |
1390 | // any moment, so mark this thread as being already in process of being | |
1391 | // deleted or wxThreadModule::OnExit() will try to delete it again | |
1392 | ScheduleThreadForDeletion(); | |
1393 | } | |
1394 | ||
1395 | // don't enter m_critsect before calling OnExit() because the user code | |
1396 | // might deadlock if, for example, it signals a condition in OnExit() (a | |
1397 | // common case) while the main thread calls any of functions entering | |
1398 | // m_critsect on us (almost all of them do) | |
1399 | OnExit(); | |
1400 | ||
1401 | // delete C++ thread object if this is a detached thread - user is | |
1402 | // responsible for doing this for joinable ones | |
1403 | if ( m_isDetached ) | |
1404 | { | |
1405 | // FIXME I'm feeling bad about it - what if another thread function is | |
1406 | // called (in another thread context) now? It will try to access | |
1407 | // half destroyed object which will probably result in something | |
1408 | // very bad - but we can't protect this by a crit section unless | |
1409 | // we make it a global object, but this would mean that we can | |
1410 | // only call one thread function at a time :-( | |
1411 | DeleteThread(this); | |
1412 | } | |
1413 | ||
1414 | // terminate the thread (pthread_exit() never returns) | |
1415 | pthread_exit(status); | |
1416 | ||
1417 | wxFAIL_MSG(_T("pthread_exit() failed")); | |
1418 | } | |
1419 | ||
1420 | // also test whether we were paused | |
1421 | bool wxThread::TestDestroy() | |
1422 | { | |
1423 | wxASSERT_MSG( This() == this, | |
1424 | _T("wxThread::TestDestroy() can only be called in the " | |
1425 | "context of the same thread") ); | |
1426 | ||
1427 | m_critsect.Enter(); | |
1428 | ||
1429 | if ( m_internal->GetState() == STATE_PAUSED ) | |
1430 | { | |
1431 | m_internal->SetReallyPaused(TRUE); | |
1432 | ||
1433 | // leave the crit section or the other threads will stop too if they | |
1434 | // try to call any of (seemingly harmless) IsXXX() functions while we | |
1435 | // sleep | |
1436 | m_critsect.Leave(); | |
1437 | ||
1438 | m_internal->Pause(); | |
1439 | } | |
1440 | else | |
1441 | { | |
1442 | // thread wasn't requested to pause, nothing to do | |
1443 | m_critsect.Leave(); | |
1444 | } | |
1445 | ||
1446 | return m_internal->WasCancelled(); | |
1447 | } | |
1448 | ||
1449 | wxThread::~wxThread() | |
1450 | { | |
1451 | #ifdef __WXDEBUG__ | |
1452 | m_critsect.Enter(); | |
1453 | ||
1454 | // check that the thread either exited or couldn't be created | |
1455 | if ( m_internal->GetState() != STATE_EXITED && | |
1456 | m_internal->GetState() != STATE_NEW ) | |
1457 | { | |
1458 | wxLogDebug(_T("The thread %ld is being destroyed although it is still " | |
1459 | "running! The application may crash."), GetId()); | |
1460 | } | |
1461 | ||
1462 | m_critsect.Leave(); | |
1463 | #endif // __WXDEBUG__ | |
1464 | ||
1465 | delete m_internal; | |
1466 | ||
1467 | // remove this thread from the global array | |
1468 | gs_allThreads.Remove(this); | |
1469 | } | |
1470 | ||
1471 | // ----------------------------------------------------------------------------- | |
1472 | // state tests | |
1473 | // ----------------------------------------------------------------------------- | |
1474 | ||
1475 | bool wxThread::IsRunning() const | |
1476 | { | |
1477 | wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect); | |
1478 | ||
1479 | return m_internal->GetState() == STATE_RUNNING; | |
1480 | } | |
1481 | ||
1482 | bool wxThread::IsAlive() const | |
1483 | { | |
1484 | wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect); | |
1485 | ||
1486 | switch ( m_internal->GetState() ) | |
1487 | { | |
1488 | case STATE_RUNNING: | |
1489 | case STATE_PAUSED: | |
1490 | return TRUE; | |
1491 | ||
1492 | default: | |
1493 | return FALSE; | |
1494 | } | |
1495 | } | |
1496 | ||
1497 | bool wxThread::IsPaused() const | |
1498 | { | |
1499 | wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect); | |
1500 | ||
1501 | return (m_internal->GetState() == STATE_PAUSED); | |
1502 | } | |
1503 | ||
1504 | //-------------------------------------------------------------------- | |
1505 | // wxThreadModule | |
1506 | //-------------------------------------------------------------------- | |
1507 | ||
1508 | class wxThreadModule : public wxModule | |
1509 | { | |
1510 | public: | |
1511 | virtual bool OnInit(); | |
1512 | virtual void OnExit(); | |
1513 | ||
1514 | private: | |
1515 | DECLARE_DYNAMIC_CLASS(wxThreadModule) | |
1516 | }; | |
1517 | ||
1518 | IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule) | |
1519 | ||
1520 | bool wxThreadModule::OnInit() | |
1521 | { | |
1522 | int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */); | |
1523 | if ( rc != 0 ) | |
1524 | { | |
1525 | wxLogSysError(rc, _("Thread module initialization failed: " | |
1526 | "failed to create thread key")); | |
1527 | ||
1528 | return FALSE; | |
1529 | } | |
1530 | ||
1531 | gs_tidMain = pthread_self(); | |
1532 | ||
1533 | #if wxUSE_GUI | |
1534 | gs_mutexGui = new wxMutex(); | |
1535 | ||
1536 | gs_mutexGui->Lock(); | |
1537 | #endif // wxUSE_GUI | |
1538 | ||
1539 | gs_mutexDeleteThread = new wxMutex(); | |
1540 | gs_condAllDeleted = new wxCondition( *gs_mutexDeleteThread ); | |
1541 | ||
1542 | return TRUE; | |
1543 | } | |
1544 | ||
1545 | void wxThreadModule::OnExit() | |
1546 | { | |
1547 | wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") ); | |
1548 | ||
1549 | // are there any threads left which are being deleted right now? | |
1550 | size_t nThreadsBeingDeleted; | |
1551 | ||
1552 | { | |
1553 | wxMutexLocker lock( *gs_mutexDeleteThread ); | |
1554 | nThreadsBeingDeleted = gs_nThreadsBeingDeleted; | |
1555 | ||
1556 | if ( nThreadsBeingDeleted > 0 ) | |
1557 | { | |
1558 | wxLogTrace(TRACE_THREADS, _T("Waiting for %u threads to disappear"), | |
1559 | nThreadsBeingDeleted); | |
1560 | ||
1561 | // have to wait until all of them disappear | |
1562 | gs_condAllDeleted->Wait(); | |
1563 | } | |
1564 | } | |
1565 | ||
1566 | // terminate any threads left | |
1567 | size_t count = gs_allThreads.GetCount(); | |
1568 | if ( count != 0u ) | |
1569 | { | |
1570 | wxLogDebug(wxT("%u threads were not terminated by the application."), | |
1571 | count); | |
1572 | } | |
1573 | ||
1574 | for ( size_t n = 0u; n < count; n++ ) | |
1575 | { | |
1576 | // Delete calls the destructor which removes the current entry. We | |
1577 | // should only delete the first one each time. | |
1578 | gs_allThreads[0]->Delete(); | |
1579 | } | |
1580 | ||
1581 | #if wxUSE_GUI | |
1582 | // destroy GUI mutex | |
1583 | gs_mutexGui->Unlock(); | |
1584 | ||
1585 | delete gs_mutexGui; | |
1586 | #endif // wxUSE_GUI | |
1587 | ||
1588 | // and free TLD slot | |
1589 | (void)pthread_key_delete(gs_keySelf); | |
1590 | ||
1591 | delete gs_condAllDeleted; | |
1592 | delete gs_mutexDeleteThread; | |
1593 | } | |
1594 | ||
1595 | // ---------------------------------------------------------------------------- | |
1596 | // global functions | |
1597 | // ---------------------------------------------------------------------------- | |
1598 | ||
1599 | static void ScheduleThreadForDeletion() | |
1600 | { | |
1601 | wxMutexLocker lock( *gs_mutexDeleteThread ); | |
1602 | ||
1603 | gs_nThreadsBeingDeleted++; | |
1604 | ||
1605 | wxLogTrace(TRACE_THREADS, _T("%u thread%s waiting to be deleted"), | |
1606 | gs_nThreadsBeingDeleted, | |
1607 | gs_nThreadsBeingDeleted == 1 ? "" : "s"); | |
1608 | } | |
1609 | ||
1610 | static void DeleteThread(wxThread *This) | |
1611 | { | |
1612 | // gs_mutexDeleteThread should be unlocked before signalling the condition | |
1613 | // or wxThreadModule::OnExit() would deadlock | |
1614 | wxMutexLocker locker( *gs_mutexDeleteThread ); | |
1615 | ||
1616 | wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId()); | |
1617 | ||
1618 | delete This; | |
1619 | ||
1620 | wxCHECK_RET( gs_nThreadsBeingDeleted > 0, | |
1621 | _T("no threads scheduled for deletion, yet we delete one?") ); | |
1622 | ||
1623 | wxLogTrace(TRACE_THREADS, _T("%u scheduled for deletion threads left."), | |
1624 | gs_nThreadsBeingDeleted - 1); | |
1625 | ||
1626 | if ( !--gs_nThreadsBeingDeleted ) | |
1627 | { | |
1628 | // no more threads left, signal it | |
1629 | gs_condAllDeleted->Signal(); | |
1630 | } | |
1631 | } | |
1632 | ||
1633 | void wxMutexGuiEnter() | |
1634 | { | |
1635 | #if wxUSE_GUI | |
1636 | gs_mutexGui->Lock(); | |
1637 | #endif // wxUSE_GUI | |
1638 | } | |
1639 | ||
1640 | void wxMutexGuiLeave() | |
1641 | { | |
1642 | #if wxUSE_GUI | |
1643 | gs_mutexGui->Unlock(); | |
1644 | #endif // wxUSE_GUI | |
1645 | } | |
1646 | ||
1647 | // ---------------------------------------------------------------------------- | |
1648 | // include common implementation code | |
1649 | // ---------------------------------------------------------------------------- | |
1650 | ||
1651 | #include "wx/thrimpl.cpp" | |
1652 | ||
1653 | #endif // wxUSE_THREADS | |
1654 |