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