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