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