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