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