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