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