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