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