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