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