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