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