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