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