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