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