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