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