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