first round of Intel compiler warning fixes: down from a few thousands just to slight...
[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), wxPtrToUInt(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 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1062 #define WXUNUSED_STACKSIZE(identifier) identifier
1063 #else
1064 #define WXUNUSED_STACKSIZE(identifier) WXUNUSED(identifier)
1065 #endif
1066
1067 wxThreadError wxThread::Create(unsigned int WXUNUSED_STACKSIZE(stackSize))
1068 {
1069 if ( m_internal->GetState() != STATE_NEW )
1070 {
1071 // don't recreate thread
1072 return wxTHREAD_RUNNING;
1073 }
1074
1075 // set up the thread attribute: right now, we only set thread priority
1076 pthread_attr_t attr;
1077 pthread_attr_init(&attr);
1078
1079 #ifdef HAVE_PTHREAD_ATTR_SETSTACKSIZE
1080 if (stackSize)
1081 pthread_attr_setstacksize(&attr, stackSize);
1082 #endif
1083
1084 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1085 int policy;
1086 if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 )
1087 {
1088 wxLogError(_("Cannot retrieve thread scheduling policy."));
1089 }
1090
1091 #ifdef __VMS__
1092 /* the pthread.h contains too many spaces. This is a work-around */
1093 # undef sched_get_priority_max
1094 #undef sched_get_priority_min
1095 #define sched_get_priority_max(_pol_) \
1096 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
1097 #define sched_get_priority_min(_pol_) \
1098 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
1099 #endif
1100
1101 int max_prio = sched_get_priority_max(policy),
1102 min_prio = sched_get_priority_min(policy),
1103 prio = m_internal->GetPriority();
1104
1105 if ( min_prio == -1 || max_prio == -1 )
1106 {
1107 wxLogError(_("Cannot get priority range for scheduling policy %d."),
1108 policy);
1109 }
1110 else if ( max_prio == min_prio )
1111 {
1112 if ( prio != WXTHREAD_DEFAULT_PRIORITY )
1113 {
1114 // notify the programmer that this doesn't work here
1115 wxLogWarning(_("Thread priority setting is ignored."));
1116 }
1117 //else: we have default priority, so don't complain
1118
1119 // anyhow, don't do anything because priority is just ignored
1120 }
1121 else
1122 {
1123 struct sched_param sp;
1124 if ( pthread_attr_getschedparam(&attr, &sp) != 0 )
1125 {
1126 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
1127 }
1128
1129 sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100;
1130
1131 if ( pthread_attr_setschedparam(&attr, &sp) != 0 )
1132 {
1133 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
1134 }
1135 }
1136 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1137
1138 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1139 // this will make the threads created by this process really concurrent
1140 if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 )
1141 {
1142 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1143 }
1144 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
1145
1146 // VZ: assume that this one is always available (it's rather fundamental),
1147 // if this function is ever missing we should try to use
1148 // pthread_detach() instead (after thread creation)
1149 if ( m_isDetached )
1150 {
1151 if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 )
1152 {
1153 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1154 }
1155
1156 // never try to join detached threads
1157 m_internal->Detach();
1158 }
1159 //else: threads are created joinable by default, it's ok
1160
1161 // create the new OS thread object
1162 int rc = pthread_create
1163 (
1164 m_internal->GetIdPtr(),
1165 &attr,
1166 wxPthreadStart,
1167 (void *)this
1168 );
1169
1170 if ( pthread_attr_destroy(&attr) != 0 )
1171 {
1172 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1173 }
1174
1175 if ( rc != 0 )
1176 {
1177 m_internal->SetState(STATE_EXITED);
1178
1179 return wxTHREAD_NO_RESOURCE;
1180 }
1181
1182 return wxTHREAD_NO_ERROR;
1183 }
1184
1185 wxThreadError wxThread::Run()
1186 {
1187 wxCriticalSectionLocker lock(m_critsect);
1188
1189 wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR,
1190 wxT("must call wxThread::Create() first") );
1191
1192 return m_internal->Run();
1193 }
1194
1195 // -----------------------------------------------------------------------------
1196 // misc accessors
1197 // -----------------------------------------------------------------------------
1198
1199 void wxThread::SetPriority(unsigned int prio)
1200 {
1201 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) &&
1202 ((int)prio <= (int)WXTHREAD_MAX_PRIORITY),
1203 wxT("invalid thread priority") );
1204
1205 wxCriticalSectionLocker lock(m_critsect);
1206
1207 switch ( m_internal->GetState() )
1208 {
1209 case STATE_NEW:
1210 // thread not yet started, priority will be set when it is
1211 m_internal->SetPriority(prio);
1212 break;
1213
1214 case STATE_RUNNING:
1215 case STATE_PAUSED:
1216 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
1217 #if defined(__LINUX__)
1218 // On Linux, pthread_setschedparam with SCHED_OTHER does not allow
1219 // a priority other than 0. Instead, we use the BSD setpriority
1220 // which alllows us to set a 'nice' value between 20 to -20. Only
1221 // super user can set a value less than zero (more negative yields
1222 // higher priority). setpriority set the static priority of a
1223 // process, but this is OK since Linux is configured as a thread
1224 // per process.
1225 //
1226 // FIXME this is not true for 2.6!!
1227
1228 // map wx priorites WXTHREAD_MIN_PRIORITY..WXTHREAD_MAX_PRIORITY
1229 // to Unix priorities 20..-20
1230 if ( setpriority(PRIO_PROCESS, 0, -(2*prio)/5 + 20) == -1 )
1231 {
1232 wxLogError(_("Failed to set thread priority %d."), prio);
1233 }
1234 #else // __LINUX__
1235 {
1236 struct sched_param sparam;
1237 sparam.sched_priority = prio;
1238
1239 if ( pthread_setschedparam(m_internal->GetId(),
1240 SCHED_OTHER, &sparam) != 0 )
1241 {
1242 wxLogError(_("Failed to set thread priority %d."), prio);
1243 }
1244 }
1245 #endif // __LINUX__
1246 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
1247 break;
1248
1249 case STATE_EXITED:
1250 default:
1251 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
1252 }
1253 }
1254
1255 unsigned int wxThread::GetPriority() const
1256 {
1257 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1258
1259 return m_internal->GetPriority();
1260 }
1261
1262 wxThreadIdType wxThread::GetId() const
1263 {
1264 return (wxThreadIdType) m_internal->GetId();
1265 }
1266
1267 // -----------------------------------------------------------------------------
1268 // pause/resume
1269 // -----------------------------------------------------------------------------
1270
1271 wxThreadError wxThread::Pause()
1272 {
1273 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1274 _T("a thread can't pause itself") );
1275
1276 wxCriticalSectionLocker lock(m_critsect);
1277
1278 if ( m_internal->GetState() != STATE_RUNNING )
1279 {
1280 wxLogDebug(wxT("Can't pause thread which is not running."));
1281
1282 return wxTHREAD_NOT_RUNNING;
1283 }
1284
1285 // just set a flag, the thread will be really paused only during the next
1286 // call to TestDestroy()
1287 m_internal->SetState(STATE_PAUSED);
1288
1289 return wxTHREAD_NO_ERROR;
1290 }
1291
1292 wxThreadError wxThread::Resume()
1293 {
1294 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1295 _T("a thread can't resume itself") );
1296
1297 wxCriticalSectionLocker lock(m_critsect);
1298
1299 wxThreadState state = m_internal->GetState();
1300
1301 switch ( state )
1302 {
1303 case STATE_PAUSED:
1304 wxLogTrace(TRACE_THREADS, _T("Thread %ld suspended, resuming."),
1305 GetId());
1306
1307 m_internal->Resume();
1308
1309 return wxTHREAD_NO_ERROR;
1310
1311 case STATE_EXITED:
1312 wxLogTrace(TRACE_THREADS, _T("Thread %ld exited, won't resume."),
1313 GetId());
1314 return wxTHREAD_NO_ERROR;
1315
1316 default:
1317 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1318
1319 return wxTHREAD_MISC_ERROR;
1320 }
1321 }
1322
1323 // -----------------------------------------------------------------------------
1324 // exiting thread
1325 // -----------------------------------------------------------------------------
1326
1327 wxThread::ExitCode wxThread::Wait()
1328 {
1329 wxCHECK_MSG( This() != this, (ExitCode)-1,
1330 _T("a thread can't wait for itself") );
1331
1332 wxCHECK_MSG( !m_isDetached, (ExitCode)-1,
1333 _T("can't wait for detached thread") );
1334
1335 m_internal->Wait();
1336
1337 return m_internal->GetExitCode();
1338 }
1339
1340 wxThreadError wxThread::Delete(ExitCode *rc)
1341 {
1342 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1343 _T("a thread can't delete itself") );
1344
1345 bool isDetached = m_isDetached;
1346
1347 m_critsect.Enter();
1348 wxThreadState state = m_internal->GetState();
1349
1350 // ask the thread to stop
1351 m_internal->SetCancelFlag();
1352
1353 m_critsect.Leave();
1354
1355 switch ( state )
1356 {
1357 case STATE_NEW:
1358 // we need to wake up the thread so that PthreadStart() will
1359 // terminate - right now it's blocking on run semaphore in
1360 // PthreadStart()
1361 m_internal->SignalRun();
1362
1363 // fall through
1364
1365 case STATE_EXITED:
1366 // nothing to do
1367 break;
1368
1369 case STATE_PAUSED:
1370 // resume the thread first
1371 m_internal->Resume();
1372
1373 // fall through
1374
1375 default:
1376 if ( !isDetached )
1377 {
1378 // wait until the thread stops
1379 m_internal->Wait();
1380
1381 if ( rc )
1382 {
1383 // return the exit code of the thread
1384 *rc = m_internal->GetExitCode();
1385 }
1386 }
1387 //else: can't wait for detached threads
1388 }
1389
1390 return wxTHREAD_NO_ERROR;
1391 }
1392
1393 wxThreadError wxThread::Kill()
1394 {
1395 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1396 _T("a thread can't kill itself") );
1397
1398 switch ( m_internal->GetState() )
1399 {
1400 case STATE_NEW:
1401 case STATE_EXITED:
1402 return wxTHREAD_NOT_RUNNING;
1403
1404 case STATE_PAUSED:
1405 // resume the thread first
1406 Resume();
1407
1408 // fall through
1409
1410 default:
1411 #ifdef HAVE_PTHREAD_CANCEL
1412 if ( pthread_cancel(m_internal->GetId()) != 0 )
1413 #endif
1414 {
1415 wxLogError(_("Failed to terminate a thread."));
1416
1417 return wxTHREAD_MISC_ERROR;
1418 }
1419
1420 if ( m_isDetached )
1421 {
1422 // if we use cleanup function, this will be done from
1423 // wxPthreadCleanup()
1424 #ifndef wxHAVE_PTHREAD_CLEANUP
1425 ScheduleThreadForDeletion();
1426
1427 // don't call OnExit() here, it can only be called in the
1428 // threads context and we're in the context of another thread
1429
1430 DeleteThread(this);
1431 #endif // wxHAVE_PTHREAD_CLEANUP
1432 }
1433 else
1434 {
1435 m_internal->SetExitCode(EXITCODE_CANCELLED);
1436 }
1437
1438 return wxTHREAD_NO_ERROR;
1439 }
1440 }
1441
1442 void wxThread::Exit(ExitCode status)
1443 {
1444 wxASSERT_MSG( This() == this,
1445 _T("wxThread::Exit() can only be called in the context of the same thread") );
1446
1447 if ( m_isDetached )
1448 {
1449 // from the moment we call OnExit(), the main program may terminate at
1450 // any moment, so mark this thread as being already in process of being
1451 // deleted or wxThreadModule::OnExit() will try to delete it again
1452 ScheduleThreadForDeletion();
1453 }
1454
1455 // don't enter m_critsect before calling OnExit() because the user code
1456 // might deadlock if, for example, it signals a condition in OnExit() (a
1457 // common case) while the main thread calls any of functions entering
1458 // m_critsect on us (almost all of them do)
1459 OnExit();
1460
1461 // delete C++ thread object if this is a detached thread - user is
1462 // responsible for doing this for joinable ones
1463 if ( m_isDetached )
1464 {
1465 // FIXME I'm feeling bad about it - what if another thread function is
1466 // called (in another thread context) now? It will try to access
1467 // half destroyed object which will probably result in something
1468 // very bad - but we can't protect this by a crit section unless
1469 // we make it a global object, but this would mean that we can
1470 // only call one thread function at a time :-(
1471 DeleteThread(this);
1472 }
1473 else
1474 {
1475 m_critsect.Enter();
1476 m_internal->SetState(STATE_EXITED);
1477 m_critsect.Leave();
1478 }
1479
1480 // terminate the thread (pthread_exit() never returns)
1481 pthread_exit(status);
1482
1483 wxFAIL_MSG(_T("pthread_exit() failed"));
1484 }
1485
1486 // also test whether we were paused
1487 bool wxThread::TestDestroy()
1488 {
1489 wxASSERT_MSG( This() == this,
1490 _T("wxThread::TestDestroy() can only be called in the context of the same thread") );
1491
1492 m_critsect.Enter();
1493
1494 if ( m_internal->GetState() == STATE_PAUSED )
1495 {
1496 m_internal->SetReallyPaused(TRUE);
1497
1498 // leave the crit section or the other threads will stop too if they
1499 // try to call any of (seemingly harmless) IsXXX() functions while we
1500 // sleep
1501 m_critsect.Leave();
1502
1503 m_internal->Pause();
1504 }
1505 else
1506 {
1507 // thread wasn't requested to pause, nothing to do
1508 m_critsect.Leave();
1509 }
1510
1511 return m_internal->WasCancelled();
1512 }
1513
1514 wxThread::~wxThread()
1515 {
1516 #ifdef __WXDEBUG__
1517 m_critsect.Enter();
1518
1519 // check that the thread either exited or couldn't be created
1520 if ( m_internal->GetState() != STATE_EXITED &&
1521 m_internal->GetState() != STATE_NEW )
1522 {
1523 wxLogDebug(_T("The thread %ld is being destroyed although it is still running! The application may crash."),
1524 (long)GetId());
1525 }
1526
1527 m_critsect.Leave();
1528 #endif // __WXDEBUG__
1529
1530 delete m_internal;
1531
1532 // remove this thread from the global array
1533 gs_allThreads.Remove(this);
1534 }
1535
1536 // -----------------------------------------------------------------------------
1537 // state tests
1538 // -----------------------------------------------------------------------------
1539
1540 bool wxThread::IsRunning() const
1541 {
1542 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1543
1544 return m_internal->GetState() == STATE_RUNNING;
1545 }
1546
1547 bool wxThread::IsAlive() const
1548 {
1549 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1550
1551 switch ( m_internal->GetState() )
1552 {
1553 case STATE_RUNNING:
1554 case STATE_PAUSED:
1555 return TRUE;
1556
1557 default:
1558 return FALSE;
1559 }
1560 }
1561
1562 bool wxThread::IsPaused() const
1563 {
1564 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1565
1566 return (m_internal->GetState() == STATE_PAUSED);
1567 }
1568
1569 //--------------------------------------------------------------------
1570 // wxThreadModule
1571 //--------------------------------------------------------------------
1572
1573 class wxThreadModule : public wxModule
1574 {
1575 public:
1576 virtual bool OnInit();
1577 virtual void OnExit();
1578
1579 private:
1580 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1581 };
1582
1583 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1584
1585 bool wxThreadModule::OnInit()
1586 {
1587 int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */);
1588 if ( rc != 0 )
1589 {
1590 wxLogSysError(rc, _("Thread module initialization failed: failed to create thread key"));
1591
1592 return FALSE;
1593 }
1594
1595 gs_tidMain = pthread_self();
1596
1597 gs_mutexGui = new wxMutex();
1598 gs_mutexGui->Lock();
1599
1600 gs_mutexDeleteThread = new wxMutex();
1601 gs_condAllDeleted = new wxCondition( *gs_mutexDeleteThread );
1602
1603 return TRUE;
1604 }
1605
1606 void wxThreadModule::OnExit()
1607 {
1608 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1609
1610 // are there any threads left which are being deleted right now?
1611 size_t nThreadsBeingDeleted;
1612
1613 {
1614 wxMutexLocker lock( *gs_mutexDeleteThread );
1615 nThreadsBeingDeleted = gs_nThreadsBeingDeleted;
1616
1617 if ( nThreadsBeingDeleted > 0 )
1618 {
1619 wxLogTrace(TRACE_THREADS,
1620 _T("Waiting for %lu threads to disappear"),
1621 (unsigned long)nThreadsBeingDeleted);
1622
1623 // have to wait until all of them disappear
1624 gs_condAllDeleted->Wait();
1625 }
1626 }
1627
1628 // terminate any threads left
1629 size_t count = gs_allThreads.GetCount();
1630 if ( count != 0u )
1631 {
1632 wxLogDebug(wxT("%lu threads were not terminated by the application."),
1633 (unsigned long)count);
1634 }
1635
1636 for ( size_t n = 0u; n < count; n++ )
1637 {
1638 // Delete calls the destructor which removes the current entry. We
1639 // should only delete the first one each time.
1640 gs_allThreads[0]->Delete();
1641 }
1642
1643 // destroy GUI mutex
1644 gs_mutexGui->Unlock();
1645 delete gs_mutexGui;
1646
1647 // and free TLD slot
1648 (void)pthread_key_delete(gs_keySelf);
1649
1650 delete gs_condAllDeleted;
1651 delete gs_mutexDeleteThread;
1652 }
1653
1654 // ----------------------------------------------------------------------------
1655 // global functions
1656 // ----------------------------------------------------------------------------
1657
1658 static void ScheduleThreadForDeletion()
1659 {
1660 wxMutexLocker lock( *gs_mutexDeleteThread );
1661
1662 gs_nThreadsBeingDeleted++;
1663
1664 wxLogTrace(TRACE_THREADS, _T("%lu thread%s waiting to be deleted"),
1665 (unsigned long)gs_nThreadsBeingDeleted,
1666 gs_nThreadsBeingDeleted == 1 ? "" : "s");
1667 }
1668
1669 static void DeleteThread(wxThread *This)
1670 {
1671 // gs_mutexDeleteThread should be unlocked before signalling the condition
1672 // or wxThreadModule::OnExit() would deadlock
1673 wxMutexLocker locker( *gs_mutexDeleteThread );
1674
1675 wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId());
1676
1677 delete This;
1678
1679 wxCHECK_RET( gs_nThreadsBeingDeleted > 0,
1680 _T("no threads scheduled for deletion, yet we delete one?") );
1681
1682 wxLogTrace(TRACE_THREADS, _T("%lu scheduled for deletion threads left."),
1683 (unsigned long)gs_nThreadsBeingDeleted - 1);
1684
1685 if ( !--gs_nThreadsBeingDeleted )
1686 {
1687 // no more threads left, signal it
1688 gs_condAllDeleted->Signal();
1689 }
1690 }
1691
1692 void wxMutexGuiEnter()
1693 {
1694 gs_mutexGui->Lock();
1695 }
1696
1697 void wxMutexGuiLeave()
1698 {
1699 gs_mutexGui->Unlock();
1700 }
1701
1702 // ----------------------------------------------------------------------------
1703 // include common implementation code
1704 // ----------------------------------------------------------------------------
1705
1706 #include "wx/thrimpl.cpp"
1707
1708 #endif // wxUSE_THREADS
1709