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