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