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