]> git.saurik.com Git - wxWidgets.git/blob - src/unix/threadpsx.cpp
joinable and detached POSIX threads (not fully tested yet)
[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 // With simple makefiles, we must ignore the file body if not using
28 // threads.
29 #include "wx/setup.h"
30
31 #if wxUSE_THREADS
32
33 #include "wx/thread.h"
34 #include "wx/module.h"
35 #include "wx/utils.h"
36 #include "wx/log.h"
37 #include "wx/intl.h"
38 #include "wx/dynarray.h"
39
40 #include <stdio.h>
41 #include <unistd.h>
42 #include <pthread.h>
43 #include <errno.h>
44 #include <time.h>
45
46 #if HAVE_SCHED_H
47 #include <sched.h>
48 #endif
49
50 // ----------------------------------------------------------------------------
51 // constants
52 // ----------------------------------------------------------------------------
53
54 // the possible states of the thread and transitions from them
55 enum wxThreadState
56 {
57 STATE_NEW, // didn't start execution yet (=> RUNNING)
58 STATE_RUNNING, // running (=> PAUSED or EXITED)
59 STATE_PAUSED, // suspended (=> RUNNING or EXITED)
60 STATE_EXITED // thread doesn't exist any more
61 };
62
63 // the exit value of a thread which has been cancelled
64 static const wxThread::ExitCode EXITCODE_CANCELLED = (wxThread::ExitCode)-1;
65
66 // our trace mask
67 #define TRACE_THREADS _T("thread")
68
69 // ----------------------------------------------------------------------------
70 // private functions
71 // ----------------------------------------------------------------------------
72
73 static void ScheduleThreadForDeletion();
74 static void DeleteThread(wxThread *This);
75
76 // ----------------------------------------------------------------------------
77 // private classes
78 // ----------------------------------------------------------------------------
79
80 // same as wxMutexLocker but for "native" mutex
81 class MutexLock
82 {
83 public:
84 MutexLock(pthread_mutex_t& mutex)
85 {
86 m_mutex = &mutex;
87 if ( pthread_mutex_lock(m_mutex) != 0 )
88 {
89 wxLogDebug(_T("pthread_mutex_lock() failed"));
90 }
91 }
92
93 ~MutexLock()
94 {
95 if ( pthread_mutex_unlock(m_mutex) != 0 )
96 {
97 wxLogDebug(_T("pthread_mutex_unlock() failed"));
98 }
99 }
100
101 private:
102 pthread_mutex_t *m_mutex;
103 };
104
105 // ----------------------------------------------------------------------------
106 // types
107 // ----------------------------------------------------------------------------
108
109 WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
110
111 // -----------------------------------------------------------------------------
112 // global data
113 // -----------------------------------------------------------------------------
114
115 // we keep the list of all threads created by the application to be able to
116 // terminate them on exit if there are some left - otherwise the process would
117 // be left in memory
118 static wxArrayThread gs_allThreads;
119
120 // the id of the main thread
121 static pthread_t gs_tidMain;
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 pthread_mutex_t gs_mutexDeleteThread = PTHREAD_MUTEX_INITIALIZER;
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 #if wxUSE_GUI
138 // this mutex must be acquired before any call to a GUI function
139 static wxMutex *gs_mutexGui;
140 #endif // wxUSE_GUI
141
142 // ============================================================================
143 // implementation
144 // ============================================================================
145
146 //--------------------------------------------------------------------
147 // wxMutex (Posix implementation)
148 //--------------------------------------------------------------------
149
150 class wxMutexInternal
151 {
152 public:
153 pthread_mutex_t m_mutex;
154 };
155
156 wxMutex::wxMutex()
157 {
158 m_internal = new wxMutexInternal;
159
160 pthread_mutex_init(&(m_internal->m_mutex),
161 (pthread_mutexattr_t*) NULL );
162 m_locked = 0;
163 }
164
165 wxMutex::~wxMutex()
166 {
167 if (m_locked > 0)
168 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked);
169
170 pthread_mutex_destroy( &(m_internal->m_mutex) );
171 delete m_internal;
172 }
173
174 wxMutexError wxMutex::Lock()
175 {
176 int err = pthread_mutex_lock( &(m_internal->m_mutex) );
177 if (err == EDEADLK)
178 {
179 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
180
181 return wxMUTEX_DEAD_LOCK;
182 }
183
184 m_locked++;
185
186 return wxMUTEX_NO_ERROR;
187 }
188
189 wxMutexError wxMutex::TryLock()
190 {
191 if (m_locked)
192 {
193 return wxMUTEX_BUSY;
194 }
195
196 int err = pthread_mutex_trylock( &(m_internal->m_mutex) );
197 switch (err)
198 {
199 case EBUSY: return wxMUTEX_BUSY;
200 }
201
202 m_locked++;
203
204 return wxMUTEX_NO_ERROR;
205 }
206
207 wxMutexError wxMutex::Unlock()
208 {
209 if (m_locked > 0)
210 {
211 m_locked--;
212 }
213 else
214 {
215 wxLogDebug(wxT("Unlocking not locked mutex."));
216
217 return wxMUTEX_UNLOCKED;
218 }
219
220 pthread_mutex_unlock( &(m_internal->m_mutex) );
221
222 return wxMUTEX_NO_ERROR;
223 }
224
225 //--------------------------------------------------------------------
226 // wxCondition (Posix implementation)
227 //--------------------------------------------------------------------
228
229 // notice that we must use a mutex with POSIX condition variables to ensure
230 // that the worker thread doesn't signal condition before the waiting thread
231 // starts to wait for it
232 class wxConditionInternal
233 {
234 public:
235 wxConditionInternal();
236 ~wxConditionInternal();
237
238 void Wait();
239 bool WaitWithTimeout(const timespec* ts);
240
241 void Signal();
242 void Broadcast();
243
244 private:
245 pthread_mutex_t m_mutex;
246 pthread_cond_t m_condition;
247 };
248
249 wxConditionInternal::wxConditionInternal()
250 {
251 if ( pthread_cond_init(&m_condition, (pthread_condattr_t *)NULL) != 0 )
252 {
253 // this is supposed to never happen
254 wxFAIL_MSG( _T("pthread_cond_init() failed") );
255 }
256
257 if ( pthread_mutex_init(&m_mutex, (pthread_mutexattr_t*)NULL) != 0 )
258 {
259 // neither this
260 wxFAIL_MSG( _T("wxCondition: pthread_mutex_init() failed") );
261 }
262
263 // initially the mutex is locked, so no thread can Signal() or Broadcast()
264 // until another thread starts to Wait()
265 if ( pthread_mutex_lock(&m_mutex) != 0 )
266 {
267 wxFAIL_MSG( _T("wxCondition: pthread_mutex_lock() failed") );
268 }
269 }
270
271 wxConditionInternal::~wxConditionInternal()
272 {
273 if ( pthread_cond_destroy( &m_condition ) != 0 )
274 {
275 wxLogDebug(_T("Failed to destroy condition variable (some "
276 "threads are probably still waiting on it?)"));
277 }
278
279 if ( pthread_mutex_unlock( &m_mutex ) != 0 )
280 {
281 wxLogDebug(_T("wxCondition: failed to unlock the mutex"));
282 }
283
284 if ( pthread_mutex_destroy( &m_mutex ) != 0 )
285 {
286 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
287 }
288 }
289
290 void wxConditionInternal::Wait()
291 {
292 if ( pthread_cond_wait( &m_condition, &m_mutex ) != 0 )
293 {
294 // not supposed to ever happen
295 wxFAIL_MSG( _T("pthread_cond_wait() failed") );
296 }
297 }
298
299 bool wxConditionInternal::WaitWithTimeout(const timespec* ts)
300 {
301 switch ( pthread_cond_timedwait( &m_condition, &m_mutex, ts ) )
302 {
303 case 0:
304 // condition signaled
305 return TRUE;
306
307 default:
308 wxLogDebug(_T("pthread_cond_timedwait() failed"));
309
310 // fall through
311
312 case ETIMEDOUT:
313 case EINTR:
314 // wait interrupted or timeout elapsed
315 return FALSE;
316 }
317 }
318
319 void wxConditionInternal::Signal()
320 {
321 MutexLock lock(m_mutex);
322
323 if ( pthread_cond_signal( &m_condition ) != 0 )
324 {
325 // shouldn't ever happen
326 wxFAIL_MSG(_T("pthread_cond_signal() failed"));
327 }
328 }
329
330 void wxConditionInternal::Broadcast()
331 {
332 MutexLock lock(m_mutex);
333
334 if ( pthread_cond_broadcast( &m_condition ) != 0 )
335 {
336 // shouldn't ever happen
337 wxFAIL_MSG(_T("pthread_cond_broadcast() failed"));
338 }
339 }
340
341 wxCondition::wxCondition()
342 {
343 m_internal = new wxConditionInternal;
344 }
345
346 wxCondition::~wxCondition()
347 {
348 delete m_internal;
349 }
350
351 void wxCondition::Wait()
352 {
353 m_internal->Wait();
354 }
355
356 bool wxCondition::Wait(unsigned long sec, unsigned long nsec)
357 {
358 timespec tspec;
359
360 tspec.tv_sec = time(0L) + sec; // FIXME is time(0) correct here?
361 tspec.tv_nsec = nsec;
362
363 return m_internal->WaitWithTimeout(&tspec);
364 }
365
366 void wxCondition::Signal()
367 {
368 m_internal->Signal();
369 }
370
371 void wxCondition::Broadcast()
372 {
373 m_internal->Broadcast();
374 }
375
376 //--------------------------------------------------------------------
377 // wxThread (Posix implementation)
378 //--------------------------------------------------------------------
379
380 class wxThreadInternal
381 {
382 public:
383 wxThreadInternal();
384 ~wxThreadInternal();
385
386 // thread entry function
387 static void *PthreadStart(void *ptr);
388
389 #if HAVE_THREAD_CLEANUP_FUNCTIONS
390 // thread exit function
391 static void PthreadCleanup(void *ptr);
392 #endif
393
394 // thread actions
395 // start the thread
396 wxThreadError Run();
397 // ask the thread to terminate
398 void Wait();
399 // wake up threads waiting for our termination
400 void SignalExit();
401 // go to sleep until Resume() is called
402 void Pause();
403 // resume the thread
404 void Resume();
405
406 // accessors
407 // priority
408 int GetPriority() const { return m_prio; }
409 void SetPriority(int prio) { m_prio = prio; }
410 // state
411 wxThreadState GetState() const { return m_state; }
412 void SetState(wxThreadState state) { m_state = state; }
413 // id
414 pthread_t GetId() const { return m_threadId; }
415 pthread_t *GetIdPtr() { return &m_threadId; }
416 // "cancelled" flag
417 void SetCancelFlag() { m_cancelled = TRUE; }
418 bool WasCancelled() const { return m_cancelled; }
419 // exit code
420 void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }
421 wxThread::ExitCode GetExitCode() const { return m_exitcode; }
422
423 // tell the thread that it is a detached one
424 void Detach() { m_shouldBeJoined = m_shouldBroadcast = FALSE; }
425 // but even detached threads need to notifyus about their termination
426 // sometimes - tell the thread that it should do it
427 void Notify() { m_shouldBroadcast = TRUE; }
428
429 private:
430 pthread_t m_threadId; // id of the thread
431 wxThreadState m_state; // see wxThreadState enum
432 int m_prio; // in wxWindows units: from 0 to 100
433
434 // this flag is set when the thread should terminate
435 bool m_cancelled;
436
437 // the thread exit code - only used for joinable (!detached) threads and
438 // is only valid after the thread termination
439 wxThread::ExitCode m_exitcode;
440
441 // many threads may call Wait(), but only one of them should call
442 // pthread_join(), so we have to keep track of this
443 wxCriticalSection m_csJoinFlag;
444 bool m_shouldBeJoined;
445 bool m_shouldBroadcast;
446
447 // VZ: it's possible that we might do with less than three different
448 // condition objects - for example, m_condRun and m_condEnd a priori
449 // won't be used in the same time. But for now I prefer this may be a
450 // bit less efficient but safer solution of having distinct condition
451 // variables for each purpose.
452
453 // this condition is signaled by Run() and the threads Entry() is not
454 // called before it is done
455 wxCondition m_condRun;
456
457 // this one is signaled when the thread should resume after having been
458 // Pause()d
459 wxCondition m_condSuspend;
460
461 // finally this one is signalled when the thread exits
462 wxCondition m_condEnd;
463 };
464
465 // ----------------------------------------------------------------------------
466 // thread startup and exit functions
467 // ----------------------------------------------------------------------------
468
469 void *wxThreadInternal::PthreadStart(void *ptr)
470 {
471 wxThread *thread = (wxThread *)ptr;
472 wxThreadInternal *pthread = thread->m_internal;
473
474 // associate the thread pointer with the newly created thread so that
475 // wxThread::This() will work
476 int rc = pthread_setspecific(gs_keySelf, thread);
477 if ( rc != 0 )
478 {
479 wxLogSysError(rc, _("Cannot start thread: error writing TLS"));
480
481 return (void *)-1;
482 }
483
484 #if HAVE_THREAD_CLEANUP_FUNCTIONS
485 // install the cleanup handler which will be called if the thread is
486 // cancelled
487 pthread_cleanup_push(wxThreadInternal::PthreadCleanup, ptr);
488 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
489
490 // wait for the condition to be signaled from Run()
491 pthread->m_condRun.Wait();
492
493 // call the main entry
494 pthread->m_exitcode = thread->Entry();
495
496 wxLogTrace(TRACE_THREADS, _T("Thread %ld left its Entry()."),
497 pthread->GetId());
498
499 {
500 wxCriticalSectionLocker lock(thread->m_critsect);
501
502 wxLogTrace(TRACE_THREADS, _T("Thread %ld changes state to EXITED."),
503 pthread->GetId());
504
505 // change the state of the thread to "exited" so that PthreadCleanup
506 // handler won't do anything from now (if it's called before we do
507 // pthread_cleanup_pop below)
508 pthread->SetState(STATE_EXITED);
509 }
510
511 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
512 // contains the matching '}' for the '{' in push, so they must be used
513 // in the same block!
514 #if HAVE_THREAD_CLEANUP_FUNCTIONS
515 // remove the cleanup handler without executing it
516 pthread_cleanup_pop(FALSE);
517 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518
519 // terminate the thread
520 thread->Exit(pthread->m_exitcode);
521
522 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
523
524 return NULL;
525 }
526
527 #if HAVE_THREAD_CLEANUP_FUNCTIONS
528
529 // this handler is called when the thread is cancelled
530 void wxThreadInternal::PthreadCleanup(void *ptr)
531 {
532 wxThread *thread = (wxThread *) ptr;
533
534 {
535 wxCriticalSectionLocker lock(thread->m_critsect);
536 if ( thread->m_internal->GetState() == STATE_EXITED )
537 {
538 // thread is already considered as finished.
539 return;
540 }
541 }
542
543 // exit the thread gracefully
544 thread->Exit(EXITCODE_CANCELLED);
545 }
546
547 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
548
549 // ----------------------------------------------------------------------------
550 // wxThreadInternal
551 // ----------------------------------------------------------------------------
552
553 wxThreadInternal::wxThreadInternal()
554 {
555 m_state = STATE_NEW;
556 m_cancelled = FALSE;
557 m_prio = WXTHREAD_DEFAULT_PRIORITY;
558 m_threadId = 0;
559 m_exitcode = 0;
560
561 // defaults for joinable threads
562 m_shouldBeJoined = TRUE;
563 m_shouldBroadcast = TRUE;
564 }
565
566 wxThreadInternal::~wxThreadInternal()
567 {
568 }
569
570 wxThreadError wxThreadInternal::Run()
571 {
572 wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
573 wxT("thread may only be started once after Create()") );
574
575 m_condRun.Signal();
576
577 SetState(STATE_RUNNING);
578
579 return wxTHREAD_NO_ERROR;
580 }
581
582 void wxThreadInternal::Wait()
583 {
584 // if the thread we're waiting for is waiting for the GUI mutex, we will
585 // deadlock so make sure we release it temporarily
586 if ( wxThread::IsMain() )
587 wxMutexGuiLeave();
588
589 // wait until the thread terminates (we're blocking in _another_ thread,
590 // of course)
591 m_condEnd.Wait();
592
593 // to avoid memory leaks we should call pthread_join(), but it must only
594 // be done once
595 wxCriticalSectionLocker lock(m_csJoinFlag);
596
597 if ( m_shouldBeJoined )
598 {
599 // FIXME shouldn't we set cancellation type to DISABLED here? If we're
600 // cancelled inside pthread_join(), things will almost certainly
601 // break - but if we disable the cancellation, we might deadlock
602 if ( pthread_join(GetId(), &m_exitcode) != 0 )
603 {
604 wxLogError(_T("Failed to join a thread, potential memory leak "
605 "detected - please restart the program"));
606 }
607
608 m_shouldBeJoined = FALSE;
609 }
610
611 // reacquire GUI mutex
612 if ( wxThread::IsMain() )
613 wxMutexGuiEnter();
614 }
615
616 void wxThreadInternal::SignalExit()
617 {
618 wxLogTrace(TRACE_THREADS, _T("Thread %ld about to exit."), GetId());
619
620 SetState(STATE_EXITED);
621
622 // wake up all the threads waiting for our termination - if there are any
623 if ( m_shouldBroadcast )
624 {
625 m_condEnd.Broadcast();
626 }
627 }
628
629 void wxThreadInternal::Pause()
630 {
631 // the state is set from the thread which pauses us first, this function
632 // is called later so the state should have been already set
633 wxCHECK_RET( m_state == STATE_PAUSED,
634 wxT("thread must first be paused with wxThread::Pause().") );
635
636 wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), GetId());
637
638 // wait until the condition is signaled from Resume()
639 m_condSuspend.Wait();
640 }
641
642 void wxThreadInternal::Resume()
643 {
644 wxCHECK_RET( m_state == STATE_PAUSED,
645 wxT("can't resume thread which is not suspended.") );
646
647 wxLogTrace(TRACE_THREADS, _T("Waking up thread %ld"), GetId());
648
649 // wake up Pause()
650 m_condSuspend.Signal();
651
652 SetState(STATE_RUNNING);
653 }
654
655 // -----------------------------------------------------------------------------
656 // wxThread static functions
657 // -----------------------------------------------------------------------------
658
659 wxThread *wxThread::This()
660 {
661 return (wxThread *)pthread_getspecific(gs_keySelf);
662 }
663
664 bool wxThread::IsMain()
665 {
666 return (bool)pthread_equal(pthread_self(), gs_tidMain);
667 }
668
669 void wxThread::Yield()
670 {
671 sched_yield();
672 }
673
674 void wxThread::Sleep(unsigned long milliseconds)
675 {
676 wxUsleep(milliseconds);
677 }
678
679 // -----------------------------------------------------------------------------
680 // creating thread
681 // -----------------------------------------------------------------------------
682
683 wxThread::wxThread(wxThreadKind kind)
684 {
685 // add this thread to the global list of all threads
686 gs_allThreads.Add(this);
687
688 m_internal = new wxThreadInternal();
689
690 m_isDetached = kind == wxTHREAD_DETACHED;
691 }
692
693 wxThreadError wxThread::Create()
694 {
695 if ( m_internal->GetState() != STATE_NEW )
696 {
697 // don't recreate thread
698 return wxTHREAD_RUNNING;
699 }
700
701 // set up the thread attribute: right now, we only set thread priority
702 pthread_attr_t attr;
703 pthread_attr_init(&attr);
704
705 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
706 int policy;
707 if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 )
708 {
709 wxLogError(_("Cannot retrieve thread scheduling policy."));
710 }
711
712 int min_prio = sched_get_priority_min(policy),
713 max_prio = sched_get_priority_max(policy),
714 prio = m_internal->GetPriority();
715
716 if ( min_prio == -1 || max_prio == -1 )
717 {
718 wxLogError(_("Cannot get priority range for scheduling policy %d."),
719 policy);
720 }
721 else if ( max_prio == min_prio )
722 {
723 if ( prio != WXTHREAD_DEFAULT_PRIORITY )
724 {
725 // notify the programmer that this doesn't work here
726 wxLogWarning(_("Thread priority setting is ignored."));
727 }
728 //else: we have default priority, so don't complain
729
730 // anyhow, don't do anything because priority is just ignored
731 }
732 else
733 {
734 struct sched_param sp;
735 if ( pthread_attr_getschedparam(&attr, &sp) != 0 )
736 {
737 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
738 }
739
740 sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100;
741
742 if ( pthread_attr_setschedparam(&attr, &sp) != 0 )
743 {
744 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
745 }
746 }
747 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
748
749 #ifdef HAVE_PTHREAD_ATTR_SETSCOPE
750 // this will make the threads created by this process really concurrent
751 if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 )
752 {
753 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
754 }
755 #endif // HAVE_PTHREAD_ATTR_SETSCOPE
756
757 // VZ: assume that this one is always available (it's rather fundamental),
758 // if this function is ever missing we should try to use
759 // pthread_detach() instead (after thread creation)
760 if ( m_isDetached )
761 {
762 if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 )
763 {
764 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
765 }
766
767 // never try to join detached threads
768 m_internal->Detach();
769 }
770 //else: threads are created joinable by default, it's ok
771
772 // create the new OS thread object
773 int rc = pthread_create
774 (
775 m_internal->GetIdPtr(),
776 &attr,
777 wxThreadInternal::PthreadStart,
778 (void *)this
779 );
780
781 if ( pthread_attr_destroy(&attr) != 0 )
782 {
783 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
784 }
785
786 if ( rc != 0 )
787 {
788 m_internal->SetState(STATE_EXITED);
789
790 return wxTHREAD_NO_RESOURCE;
791 }
792
793 return wxTHREAD_NO_ERROR;
794 }
795
796 wxThreadError wxThread::Run()
797 {
798 wxCriticalSectionLocker lock(m_critsect);
799
800 wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR,
801 wxT("must call wxThread::Create() first") );
802
803 return m_internal->Run();
804 }
805
806 // -----------------------------------------------------------------------------
807 // misc accessors
808 // -----------------------------------------------------------------------------
809
810 void wxThread::SetPriority(unsigned int prio)
811 {
812 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) &&
813 ((int)prio <= (int)WXTHREAD_MAX_PRIORITY),
814 wxT("invalid thread priority") );
815
816 wxCriticalSectionLocker lock(m_critsect);
817
818 switch ( m_internal->GetState() )
819 {
820 case STATE_NEW:
821 // thread not yet started, priority will be set when it is
822 m_internal->SetPriority(prio);
823 break;
824
825 case STATE_RUNNING:
826 case STATE_PAUSED:
827 #ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
828 {
829 struct sched_param sparam;
830 sparam.sched_priority = prio;
831
832 if ( pthread_setschedparam(m_internal->GetId(),
833 SCHED_OTHER, &sparam) != 0 )
834 {
835 wxLogError(_("Failed to set thread priority %d."), prio);
836 }
837 }
838 #endif // HAVE_THREAD_PRIORITY_FUNCTIONS
839 break;
840
841 case STATE_EXITED:
842 default:
843 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
844 }
845 }
846
847 unsigned int wxThread::GetPriority() const
848 {
849 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
850
851 return m_internal->GetPriority();
852 }
853
854 unsigned long wxThread::GetId() const
855 {
856 return (unsigned long)m_internal->GetId();
857 }
858
859 // -----------------------------------------------------------------------------
860 // pause/resume
861 // -----------------------------------------------------------------------------
862
863 wxThreadError wxThread::Pause()
864 {
865 wxCriticalSectionLocker lock(m_critsect);
866
867 if ( m_internal->GetState() != STATE_RUNNING )
868 {
869 wxLogDebug(wxT("Can't pause thread which is not running."));
870
871 return wxTHREAD_NOT_RUNNING;
872 }
873
874 // just set a flag, the thread will be really paused only during the next
875 // call to TestDestroy()
876 m_internal->SetState(STATE_PAUSED);
877
878 return wxTHREAD_NO_ERROR;
879 }
880
881 wxThreadError wxThread::Resume()
882 {
883 m_critsect.Enter();
884
885 wxThreadState state = m_internal->GetState();
886
887 // the thread might be not actually paused yet - if there were no call to
888 // TestDestroy() since the last call to Pause(), so avoid that
889 // TestDestroy() deadlocks trying to enter m_critsect by leaving it before
890 // calling Resume()
891 m_critsect.Leave();
892
893 switch ( state )
894 {
895 case STATE_PAUSED:
896 wxLogTrace(TRACE_THREADS, _T("Thread %ld is suspended, resuming."),
897 GetId());
898
899 m_internal->Resume();
900
901 return wxTHREAD_NO_ERROR;
902
903 case STATE_EXITED:
904 wxLogTrace(TRACE_THREADS, _T("Thread %ld exited, won't resume."),
905 GetId());
906 return wxTHREAD_NO_ERROR;
907
908 default:
909 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
910
911 return wxTHREAD_MISC_ERROR;
912 }
913 }
914
915 // -----------------------------------------------------------------------------
916 // exiting thread
917 // -----------------------------------------------------------------------------
918
919 wxThread::ExitCode wxThread::Wait()
920 {
921 wxCHECK_MSG( This() != this, (ExitCode)-1,
922 _T("a thread can't wait for itself") );
923
924 wxCHECK_MSG( !m_isDetached, (ExitCode)-1,
925 _T("can't wait for detached thread") );
926
927 m_internal->Wait();
928
929 return m_internal->GetExitCode();
930 }
931
932 wxThreadError wxThread::Delete(ExitCode *rc)
933 {
934 m_critsect.Enter();
935 wxThreadState state = m_internal->GetState();
936
937 // ask the thread to stop
938 m_internal->SetCancelFlag();
939
940 if ( m_isDetached )
941 {
942 // detached threads won't broadcast about their termination by default
943 // because usually nobody waits for them - but here we do, so ask the
944 // thread to notify us
945 m_internal->Notify();
946 }
947
948 m_critsect.Leave();
949
950 switch ( state )
951 {
952 case STATE_NEW:
953 case STATE_EXITED:
954 // nothing to do
955 break;
956
957 case STATE_PAUSED:
958 // resume the thread first (don't call our Resume() because this
959 // would dead lock when it tries to enter m_critsect)
960 m_internal->Resume();
961
962 // fall through
963
964 default:
965 // wait until the thread stops
966 m_internal->Wait();
967
968 if ( rc )
969 {
970 wxASSERT_MSG( !m_isDetached,
971 _T("no return code for detached threads") );
972
973 // if it's a joinable thread, it's not deleted yet
974 *rc = m_internal->GetExitCode();
975 }
976 }
977
978 return wxTHREAD_NO_ERROR;
979 }
980
981 wxThreadError wxThread::Kill()
982 {
983 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
984 _T("a thread can't kill itself") );
985
986 switch ( m_internal->GetState() )
987 {
988 case STATE_NEW:
989 case STATE_EXITED:
990 return wxTHREAD_NOT_RUNNING;
991
992 case STATE_PAUSED:
993 // resume the thread first
994 Resume();
995
996 // fall through
997
998 default:
999 #ifdef HAVE_PTHREAD_CANCEL
1000 if ( pthread_cancel(m_internal->GetId()) != 0 )
1001 #endif
1002 {
1003 wxLogError(_("Failed to terminate a thread."));
1004
1005 return wxTHREAD_MISC_ERROR;
1006 }
1007
1008 if ( m_isDetached )
1009 {
1010 // if we use cleanup function, this will be done from
1011 // PthreadCleanup()
1012 #if !HAVE_THREAD_CLEANUP_FUNCTIONS
1013 ScheduleThreadForDeletion();
1014
1015 OnExit();
1016
1017 DeleteThread(this);
1018 #endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1019 }
1020 else
1021 {
1022 m_internal->SetExitCode(EXITCODE_CANCELLED);
1023 }
1024
1025 return wxTHREAD_NO_ERROR;
1026 }
1027 }
1028
1029 void wxThread::Exit(ExitCode status)
1030 {
1031 // from the moment we call OnExit(), the main program may terminate at any
1032 // moment, so mark this thread as being already in process of being
1033 // deleted or wxThreadModule::OnExit() will try to delete it again
1034 ScheduleThreadForDeletion();
1035
1036 // don't enter m_critsect before calling OnExit() because the user code
1037 // might deadlock if, for example, it signals a condition in OnExit() (a
1038 // common case) while the main thread calls any of functions entering
1039 // m_critsect on us (almost all of them do)
1040 OnExit();
1041
1042 // now do enter it because SignalExit() will change our state
1043 m_critsect.Enter();
1044
1045 // next wake up the threads waiting for us (OTOH, this function won't return
1046 // until someone waited for us!)
1047 m_internal->SignalExit();
1048
1049 // leave the critical section before entering the dtor which tries to
1050 // enter it
1051 m_critsect.Leave();
1052
1053 // delete C++ thread object if this is a detached thread - user is
1054 // responsible for doing this for joinable ones
1055 if ( m_isDetached )
1056 {
1057 // FIXME I'm feeling bad about it - what if another thread function is
1058 // called (in another thread context) now? It will try to access
1059 // half destroyed object which will probably result in something
1060 // very bad - but we can't protect this by a crit section unless
1061 // we make it a global object, but this would mean that we can
1062 // only call one thread function at a time :-(
1063 DeleteThread(this);
1064 }
1065
1066 // terminate the thread (pthread_exit() never returns)
1067 pthread_exit(status);
1068
1069 wxFAIL_MSG(_T("pthread_exit() failed"));
1070 }
1071
1072 // also test whether we were paused
1073 bool wxThread::TestDestroy()
1074 {
1075 m_critsect.Enter();
1076
1077 if ( m_internal->GetState() == STATE_PAUSED )
1078 {
1079 // leave the crit section or the other threads will stop too if they
1080 // try to call any of (seemingly harmless) IsXXX() functions while we
1081 // sleep
1082 m_critsect.Leave();
1083
1084 m_internal->Pause();
1085 }
1086 else
1087 {
1088 // thread wasn't requested to pause, nothing to do
1089 m_critsect.Leave();
1090 }
1091
1092 return m_internal->WasCancelled();
1093 }
1094
1095 wxThread::~wxThread()
1096 {
1097 #ifdef __WXDEBUG__
1098 m_critsect.Enter();
1099
1100 // check that the thread either exited or couldn't be created
1101 if ( m_internal->GetState() != STATE_EXITED &&
1102 m_internal->GetState() != STATE_NEW )
1103 {
1104 wxLogDebug(_T("The thread is being destroyed although it is still "
1105 "running! The application may crash."));
1106 }
1107
1108 m_critsect.Leave();
1109 #endif // __WXDEBUG__
1110
1111 delete m_internal;
1112
1113 // remove this thread from the global array
1114 gs_allThreads.Remove(this);
1115 }
1116
1117 // -----------------------------------------------------------------------------
1118 // state tests
1119 // -----------------------------------------------------------------------------
1120
1121 bool wxThread::IsRunning() const
1122 {
1123 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1124
1125 return m_internal->GetState() == STATE_RUNNING;
1126 }
1127
1128 bool wxThread::IsAlive() const
1129 {
1130 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1131
1132 switch ( m_internal->GetState() )
1133 {
1134 case STATE_RUNNING:
1135 case STATE_PAUSED:
1136 return TRUE;
1137
1138 default:
1139 return FALSE;
1140 }
1141 }
1142
1143 bool wxThread::IsPaused() const
1144 {
1145 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1146
1147 return (m_internal->GetState() == STATE_PAUSED);
1148 }
1149
1150 //--------------------------------------------------------------------
1151 // wxThreadModule
1152 //--------------------------------------------------------------------
1153
1154 class wxThreadModule : public wxModule
1155 {
1156 public:
1157 virtual bool OnInit();
1158 virtual void OnExit();
1159
1160 private:
1161 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1162 };
1163
1164 IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1165
1166 bool wxThreadModule::OnInit()
1167 {
1168 int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */);
1169 if ( rc != 0 )
1170 {
1171 wxLogSysError(rc, _("Thread module initialization failed: "
1172 "failed to create thread key"));
1173
1174 return FALSE;
1175 }
1176
1177 gs_tidMain = pthread_self();
1178
1179 #if wxUSE_GUI
1180 gs_mutexGui = new wxMutex();
1181
1182 gs_mutexGui->Lock();
1183 #endif // wxUSE_GUI
1184
1185 return TRUE;
1186 }
1187
1188 void wxThreadModule::OnExit()
1189 {
1190 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
1191
1192 // are there any threads left which are being deleted right now?
1193 size_t nThreadsBeingDeleted;
1194 {
1195 MutexLock lock(gs_mutexDeleteThread);
1196 nThreadsBeingDeleted = gs_nThreadsBeingDeleted;
1197 }
1198
1199 if ( nThreadsBeingDeleted > 0 )
1200 {
1201 wxLogTrace(TRACE_THREADS, _T("Waiting for %u threads to disappear"),
1202 nThreadsBeingDeleted);
1203
1204 // have to wait until all of them disappear
1205 gs_condAllDeleted->Wait();
1206 }
1207
1208 // terminate any threads left
1209 size_t count = gs_allThreads.GetCount();
1210 if ( count != 0u )
1211 wxLogDebug(wxT("Some threads were not terminated by the application."));
1212
1213 for ( size_t n = 0u; n < count; n++ )
1214 {
1215 // Delete calls the destructor which removes the current entry. We
1216 // should only delete the first one each time.
1217 gs_allThreads[0]->Delete();
1218 }
1219
1220 #if wxUSE_GUI
1221 // destroy GUI mutex
1222 gs_mutexGui->Unlock();
1223
1224 delete gs_mutexGui;
1225 #endif // wxUSE_GUI
1226
1227 // and free TLD slot
1228 (void)pthread_key_delete(gs_keySelf);
1229 }
1230
1231 // ----------------------------------------------------------------------------
1232 // global functions
1233 // ----------------------------------------------------------------------------
1234
1235 static void ScheduleThreadForDeletion()
1236 {
1237 MutexLock lock(gs_mutexDeleteThread);
1238
1239 if ( gs_nThreadsBeingDeleted == 0 )
1240 {
1241 gs_condAllDeleted = new wxCondition;
1242 }
1243
1244 gs_nThreadsBeingDeleted++;
1245
1246 wxLogTrace(TRACE_THREADS, _T("%u threads waiting to be deleted"),
1247 gs_nThreadsBeingDeleted);
1248 }
1249
1250 static void DeleteThread(wxThread *This)
1251 {
1252 // gs_mutexDeleteThread should be unlocked before signalling the condition
1253 // or wxThreadModule::OnExit() would deadlock
1254 {
1255 MutexLock lock(gs_mutexDeleteThread);
1256
1257 wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId());
1258
1259 delete This;
1260
1261 wxCHECK_RET( gs_nThreadsBeingDeleted > 0,
1262 _T("no threads scheduled for deletion, yet we delete "
1263 "one?") );
1264 }
1265
1266 if ( !--gs_nThreadsBeingDeleted )
1267 {
1268 // no more threads left, signal it
1269 gs_condAllDeleted->Signal();
1270
1271 delete gs_condAllDeleted;
1272 gs_condAllDeleted = (wxCondition *)NULL;
1273 }
1274 }
1275
1276 void wxMutexGuiEnter()
1277 {
1278 #if wxUSE_GUI
1279 gs_mutexGui->Lock();
1280 #endif // wxUSE_GUI
1281 }
1282
1283 void wxMutexGuiLeave()
1284 {
1285 #if wxUSE_GUI
1286 gs_mutexGui->Unlock();
1287 #endif // wxUSE_GUI
1288 }
1289
1290 #endif
1291 // wxUSE_THREADS