]> git.saurik.com Git - wxWidgets.git/blame - src/unix/threadpsx.cpp
wxTopLevelWindows is now a wxWindowList, better compatibility with the old
[wxWidgets.git] / src / unix / threadpsx.cpp
CommitLineData
518b5d2f
VZ
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
7bcb11d3
JS
27// With simple makefiles, we must ignore the file body if not using
28// threads.
29#include "wx/setup.h"
518b5d2f 30
7bcb11d3 31#if wxUSE_THREADS
518b5d2f 32
7bcb11d3 33#include "wx/thread.h"
518b5d2f
VZ
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
7bcb11d3 46#if HAVE_SCHED_H
518b5d2f
VZ
47 #include <sched.h>
48#endif
49
50// ----------------------------------------------------------------------------
51// constants
52// ----------------------------------------------------------------------------
53
882eefb1
VZ
54// the possible states of the thread and transitions from them
55enum wxThreadState
518b5d2f
VZ
56{
57 STATE_NEW, // didn't start execution yet (=> RUNNING)
882eefb1
VZ
58 STATE_RUNNING, // running (=> PAUSED or EXITED)
59 STATE_PAUSED, // suspended (=> RUNNING or EXITED)
60 STATE_EXITED // thread doesn't exist any more
518b5d2f
VZ
61};
62
882eefb1
VZ
63// ----------------------------------------------------------------------------
64// types
65// ----------------------------------------------------------------------------
66
518b5d2f
VZ
67WX_DEFINE_ARRAY(wxThread *, wxArrayThread);
68
69// -----------------------------------------------------------------------------
70// global data
71// -----------------------------------------------------------------------------
72
73// we keep the list of all threads created by the application to be able to
74// terminate them on exit if there are some left - otherwise the process would
75// be left in memory
76static wxArrayThread gs_allThreads;
77
78// the id of the main thread
79static pthread_t gs_tidMain;
80
81// the key for the pointer to the associated wxThread object
82static pthread_key_t gs_keySelf;
83
84// this mutex must be acquired before any call to a GUI function
85static wxMutex *gs_mutexGui;
86
87// ============================================================================
88// implementation
89// ============================================================================
90
91//--------------------------------------------------------------------
92// wxMutex (Posix implementation)
93//--------------------------------------------------------------------
94
95class wxMutexInternal
96{
97public:
98 pthread_mutex_t p_mutex;
99};
100
101wxMutex::wxMutex()
102{
103 p_internal = new wxMutexInternal;
104 pthread_mutex_init( &(p_internal->p_mutex), (const pthread_mutexattr_t*) NULL );
105 m_locked = 0;
106}
107
108wxMutex::~wxMutex()
109{
110 if (m_locked > 0)
111 wxLogDebug("Freeing a locked mutex (%d locks)", m_locked);
112
113 pthread_mutex_destroy( &(p_internal->p_mutex) );
114 delete p_internal;
115}
116
117wxMutexError wxMutex::Lock()
118{
119 int err = pthread_mutex_lock( &(p_internal->p_mutex) );
120 if (err == EDEADLK)
121 {
122 wxLogDebug("Locking this mutex would lead to deadlock!");
123
124 return wxMUTEX_DEAD_LOCK;
125 }
126
127 m_locked++;
128
129 return wxMUTEX_NO_ERROR;
130}
131
132wxMutexError wxMutex::TryLock()
133{
134 if (m_locked)
135 {
136 return wxMUTEX_BUSY;
137 }
138
139 int err = pthread_mutex_trylock( &(p_internal->p_mutex) );
140 switch (err)
141 {
142 case EBUSY: return wxMUTEX_BUSY;
143 }
144
145 m_locked++;
146
147 return wxMUTEX_NO_ERROR;
148}
149
150wxMutexError wxMutex::Unlock()
151{
152 if (m_locked > 0)
153 {
154 m_locked--;
155 }
156 else
157 {
158 wxLogDebug("Unlocking not locked mutex.");
159
160 return wxMUTEX_UNLOCKED;
161 }
162
163 pthread_mutex_unlock( &(p_internal->p_mutex) );
164
165 return wxMUTEX_NO_ERROR;
166}
167
168//--------------------------------------------------------------------
169// wxCondition (Posix implementation)
170//--------------------------------------------------------------------
171
172class wxConditionInternal
173{
174public:
175 pthread_cond_t p_condition;
176};
177
178wxCondition::wxCondition()
179{
180 p_internal = new wxConditionInternal;
181 pthread_cond_init( &(p_internal->p_condition), (const pthread_condattr_t *) NULL );
182}
183
184wxCondition::~wxCondition()
185{
186 pthread_cond_destroy( &(p_internal->p_condition) );
187
188 delete p_internal;
189}
190
191void wxCondition::Wait(wxMutex& mutex)
192{
193 pthread_cond_wait( &(p_internal->p_condition), &(mutex.p_internal->p_mutex) );
194}
195
196bool wxCondition::Wait(wxMutex& mutex, unsigned long sec, unsigned long nsec)
197{
198 struct timespec tspec;
199
200 tspec.tv_sec = time(0L)+sec;
201 tspec.tv_nsec = nsec;
202 return (pthread_cond_timedwait(&(p_internal->p_condition), &(mutex.p_internal->p_mutex), &tspec) != ETIMEDOUT);
203}
204
205void wxCondition::Signal()
206{
207 pthread_cond_signal( &(p_internal->p_condition) );
208}
209
210void wxCondition::Broadcast()
211{
212 pthread_cond_broadcast( &(p_internal->p_condition) );
213}
214
215//--------------------------------------------------------------------
216// wxThread (Posix implementation)
217//--------------------------------------------------------------------
218
219class wxThreadInternal
220{
221public:
222 wxThreadInternal();
223 ~wxThreadInternal();
224
225 // thread entry function
226 static void *PthreadStart(void *ptr);
227
228 // thread actions
229 // start the thread
230 wxThreadError Run();
231 // ask the thread to terminate
882eefb1 232 void Wait();
518b5d2f
VZ
233 // wake up threads waiting for our termination
234 void SignalExit();
235 // go to sleep until Resume() is called
236 void Pause();
237 // resume the thread
238 void Resume();
239
240 // accessors
241 // priority
242 int GetPriority() const { return m_prio; }
243 void SetPriority(int prio) { m_prio = prio; }
244 // state
882eefb1
VZ
245 wxThreadState GetState() const { return m_state; }
246 void SetState(wxThreadState state) { m_state = state; }
518b5d2f 247 // id
882eefb1
VZ
248 pthread_t GetId() const { return m_threadId; }
249 pthread_t *GetIdPtr() { return &m_threadId; }
518b5d2f 250 // "cancelled" flag
882eefb1 251 void SetCancelFlag() { m_cancelled = TRUE; }
518b5d2f
VZ
252 bool WasCancelled() const { return m_cancelled; }
253
518b5d2f 254private:
882eefb1
VZ
255 pthread_t m_threadId; // id of the thread
256 wxThreadState m_state; // see wxThreadState enum
257 int m_prio; // in wxWindows units: from 0 to 100
518b5d2f
VZ
258
259 // set when the thread should terminate
260 bool m_cancelled;
261
262 // this (mutex, cond) pair is used to synchronize the main thread and this
263 // thread in several situations:
264 // 1. The thread function blocks until condition is signaled by Run() when
862cc6f9 265 // it's initially created - this allows thread creation in "suspended"
518b5d2f
VZ
266 // state
267 // 2. The Delete() function blocks until the condition is signaled when the
268 // thread exits.
269 wxMutex m_mutex;
270 wxCondition m_cond;
271
272 // another (mutex, cond) pair for Pause()/Resume() usage
273 //
274 // VZ: it's possible that we might reuse the mutex and condition from above
275 // for this too, but as I'm not at all sure that it won't create subtle
276 // problems with race conditions between, say, Pause() and Delete() I
277 // prefer this may be a bit less efficient but much safer solution
278 wxMutex m_mutexSuspend;
279 wxCondition m_condSuspend;
280};
281
282void *wxThreadInternal::PthreadStart(void *ptr)
283{
284 wxThread *thread = (wxThread *)ptr;
285 wxThreadInternal *pthread = thread->p_internal;
286
862cc6f9
VZ
287 int rc = pthread_setspecific(gs_keySelf, thread);
288 if ( rc != 0 )
518b5d2f 289 {
862cc6f9 290 wxLogSysError(rc, _("Can not start thread: error writing TLS."));
518b5d2f
VZ
291
292 return (void *)-1;
293 }
294
295 // wait for the condition to be signaled from Run()
296 // mutex state: currently locked by the thread which created us
297 pthread->m_cond.Wait(pthread->m_mutex);
298
299 // mutex state: locked again on exit of Wait()
300
301 // call the main entry
302 void* status = thread->Entry();
303
304 // terminate the thread
305 thread->Exit(status);
306
307 wxFAIL_MSG("wxThread::Exit() can't return.");
308
309 return NULL;
310}
311
312wxThreadInternal::wxThreadInternal()
313{
314 m_state = STATE_NEW;
315 m_cancelled = FALSE;
316
317 // this mutex is locked during almost all thread lifetime - it will only be
318 // unlocked in the very end
319 m_mutex.Lock();
320
321 // this mutex is used in Pause()/Resume() and is also locked all the time
322 // unless the thread is paused
323 m_mutexSuspend.Lock();
324}
325
326wxThreadInternal::~wxThreadInternal()
327{
328 m_mutexSuspend.Unlock();
329
330 // note that m_mutex will be unlocked by the thread which waits for our
331 // termination
332}
333
334wxThreadError wxThreadInternal::Run()
335{
336 wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
337 "thread may only be started once after successful Create()" );
338
339 // the mutex was locked on Create(), so we will be able to lock it again
340 // only when the thread really starts executing and enters the wait -
341 // otherwise we might signal the condition before anybody is waiting for it
342 wxMutexLocker lock(m_mutex);
343 m_cond.Signal();
344
345 m_state = STATE_RUNNING;
346
347 return wxTHREAD_NO_ERROR;
348
349 // now the mutex is unlocked back - but just to allow Wait() function to
350 // terminate by relocking it, so the net result is that the worker thread
351 // starts executing and the mutex is still locked
352}
353
882eefb1 354void wxThreadInternal::Wait()
518b5d2f 355{
882eefb1
VZ
356 wxCHECK_RET( WasCancelled(), "thread should have been cancelled first" );
357
518b5d2f
VZ
358 // if the thread we're waiting for is waiting for the GUI mutex, we will
359 // deadlock so make sure we release it temporarily
360 if ( wxThread::IsMain() )
361 wxMutexGuiLeave();
362
518b5d2f
VZ
363 // entering Wait() releases the mutex thus allowing SignalExit() to acquire
364 // it and to signal us its termination
365 m_cond.Wait(m_mutex);
366
367 // mutex is still in the locked state - relocked on exit from Wait(), so
368 // unlock it - we don't need it any more, the thread has already terminated
369 m_mutex.Unlock();
370
371 // reacquire GUI mutex
372 if ( wxThread::IsMain() )
373 wxMutexGuiEnter();
374}
375
376void wxThreadInternal::SignalExit()
377{
378 // as mutex is currently locked, this will block until some other thread
379 // (normally the same which created this one) unlocks it by entering Wait()
380 m_mutex.Lock();
381
382 // wake up all the threads waiting for our termination
383 m_cond.Broadcast();
384
385 // after this call mutex will be finally unlocked
386 m_mutex.Unlock();
387}
388
389void wxThreadInternal::Pause()
390{
882eefb1
VZ
391 // the state is set from the thread which pauses us first, this function
392 // is called later so the state should have been already set
518b5d2f
VZ
393 wxCHECK_RET( m_state == STATE_PAUSED,
394 "thread must first be paused with wxThread::Pause()." );
395
862cc6f9
VZ
396 // don't pause the thread which is being terminated - this would lead to
397 // deadlock if the thread is paused after Delete() had called Resume() but
882eefb1
VZ
398 // before it had time to call Wait()
399 if ( WasCancelled() )
862cc6f9
VZ
400 return;
401
518b5d2f
VZ
402 // wait until the condition is signaled from Resume()
403 m_condSuspend.Wait(m_mutexSuspend);
404}
405
406void wxThreadInternal::Resume()
407{
408 wxCHECK_RET( m_state == STATE_PAUSED,
409 "can't resume thread which is not suspended." );
410
411 // we will be able to lock this mutex only when Pause() starts waiting
412 wxMutexLocker lock(m_mutexSuspend);
413 m_condSuspend.Signal();
414
415 SetState(STATE_RUNNING);
416}
417
418// -----------------------------------------------------------------------------
419// static functions
420// -----------------------------------------------------------------------------
421
422wxThread *wxThread::This()
423{
424 return (wxThread *)pthread_getspecific(gs_keySelf);
425}
426
427bool wxThread::IsMain()
428{
429 return (bool)pthread_equal(pthread_self(), gs_tidMain);
430}
431
432void wxThread::Yield()
433{
434 sched_yield();
435}
436
437void wxThread::Sleep(unsigned long milliseconds)
438{
439 wxUsleep(milliseconds);
440}
441
442// -----------------------------------------------------------------------------
443// creating thread
444// -----------------------------------------------------------------------------
445
446wxThread::wxThread()
447{
448 // add this thread to the global list of all threads
449 gs_allThreads.Add(this);
450
451 p_internal = new wxThreadInternal();
452}
453
454wxThreadError wxThread::Create()
455{
456 if (p_internal->GetState() != STATE_NEW)
457 return wxTHREAD_RUNNING;
458
459 // set up the thread attribute: right now, we only set thread priority
460 pthread_attr_t attr;
461 pthread_attr_init(&attr);
462
fc9ef629 463#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
464 int prio;
465 if ( pthread_attr_getschedpolicy(&attr, &prio) != 0 )
466 {
467 wxLogError(_("Can not retrieve thread scheduling policy."));
468 }
469
470 int min_prio = sched_get_priority_min(prio),
471 max_prio = sched_get_priority_max(prio);
472
473 if ( min_prio == -1 || max_prio == -1 )
474 {
475 wxLogError(_("Can not get priority range for scheduling policy %d."),
476 prio);
477 }
478 else
479 {
480 struct sched_param sp;
481 pthread_attr_getschedparam(&attr, &sp);
482 sp.sched_priority = min_prio +
483 (p_internal->GetPriority()*(max_prio-min_prio))/100;
484 pthread_attr_setschedparam(&attr, &sp);
485 }
34f8c26e 486#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
487
488 // create the new OS thread object
882eefb1 489 int rc = pthread_create(p_internal->GetIdPtr(), &attr,
518b5d2f
VZ
490 wxThreadInternal::PthreadStart, (void *)this);
491 pthread_attr_destroy(&attr);
492
493 if ( rc != 0 )
494 {
495 p_internal->SetState(STATE_EXITED);
496 return wxTHREAD_NO_RESOURCE;
497 }
498
499 return wxTHREAD_NO_ERROR;
500}
501
502wxThreadError wxThread::Run()
503{
504 return p_internal->Run();
505}
506
507// -----------------------------------------------------------------------------
508// misc accessors
509// -----------------------------------------------------------------------------
510
511void wxThread::SetPriority(unsigned int prio)
512{
34f8c26e
VZ
513 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) &&
514 ((int)prio <= (int)WXTHREAD_MAX_PRIORITY),
515 "invalid thread priority" );
518b5d2f
VZ
516
517 wxCriticalSectionLocker lock(m_critsect);
518
519 switch ( p_internal->GetState() )
520 {
521 case STATE_NEW:
522 // thread not yet started, priority will be set when it is
523 p_internal->SetPriority(prio);
524 break;
525
526 case STATE_RUNNING:
527 case STATE_PAUSED:
34f8c26e 528#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
529 {
530 struct sched_param sparam;
531 sparam.sched_priority = prio;
532
533 if ( pthread_setschedparam(p_internal->GetId(),
534 SCHED_OTHER, &sparam) != 0 )
535 {
536 wxLogError(_("Failed to set thread priority %d."), prio);
537 }
538 }
34f8c26e 539#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
540 break;
541
542 case STATE_EXITED:
543 default:
544 wxFAIL_MSG("impossible to set thread priority in this state");
545 }
546}
547
548unsigned int wxThread::GetPriority() const
549{
550 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
551
552 return p_internal->GetPriority();
553}
554
555unsigned long wxThread::GetID() const
556{
882eefb1 557 return (unsigned long)p_internal->GetId();
518b5d2f
VZ
558}
559
560// -----------------------------------------------------------------------------
561// pause/resume
562// -----------------------------------------------------------------------------
563
564wxThreadError wxThread::Pause()
565{
566 wxCriticalSectionLocker lock(m_critsect);
567
568 if ( p_internal->GetState() != STATE_RUNNING )
569 {
570 wxLogDebug("Can't pause thread which is not running.");
571
572 return wxTHREAD_NOT_RUNNING;
573 }
574
575 p_internal->SetState(STATE_PAUSED);
576
577 return wxTHREAD_NO_ERROR;
578}
579
580wxThreadError wxThread::Resume()
581{
582 wxCriticalSectionLocker lock(m_critsect);
583
584 if ( p_internal->GetState() == STATE_PAUSED )
585 {
586 p_internal->Resume();
587
588 return wxTHREAD_NO_ERROR;
589 }
590 else
591 {
592 wxLogDebug("Attempt to resume a thread which is not paused.");
593
594 return wxTHREAD_MISC_ERROR;
595 }
596}
597
598// -----------------------------------------------------------------------------
599// exiting thread
600// -----------------------------------------------------------------------------
601
602wxThread::ExitCode wxThread::Delete()
603{
604 m_critsect.Enter();
882eefb1 605 wxThreadState state = p_internal->GetState();
518b5d2f
VZ
606 m_critsect.Leave();
607
882eefb1
VZ
608 // ask the thread to stop
609 p_internal->SetCancelFlag();
610
518b5d2f
VZ
611 switch ( state )
612 {
613 case STATE_NEW:
614 case STATE_EXITED:
615 // nothing to do
616 break;
617
618 case STATE_PAUSED:
619 // resume the thread first
620 Resume();
621
622 // fall through
623
624 default:
882eefb1
VZ
625 // wait until the thread stops
626 p_internal->Wait();
518b5d2f
VZ
627 }
628
629 return NULL;
630}
631
632wxThreadError wxThread::Kill()
633{
634 switch ( p_internal->GetState() )
635 {
636 case STATE_NEW:
637 case STATE_EXITED:
638 return wxTHREAD_NOT_RUNNING;
639
640 default:
34f8c26e 641#ifdef HAVE_PTHREAD_CANCEL
518b5d2f 642 if ( pthread_cancel(p_internal->GetId()) != 0 )
34f8c26e 643#endif
518b5d2f
VZ
644 {
645 wxLogError(_("Failed to terminate a thread."));
646
647 return wxTHREAD_MISC_ERROR;
648 }
649
650 return wxTHREAD_NO_ERROR;
651 }
652}
653
654void wxThread::Exit(void *status)
655{
656 // first call user-level clean up code
657 OnExit();
658
659 // next wake up the threads waiting for us (OTOH, this function won't return
660 // until someone waited for us!)
661 p_internal->SignalExit();
662
663 p_internal->SetState(STATE_EXITED);
664
665 // delete both C++ thread object and terminate the OS thread object
666 delete this;
667 pthread_exit(status);
668}
669
670// also test whether we were paused
671bool wxThread::TestDestroy()
672{
882eefb1 673 wxCriticalSectionLocker lock(m_critsect);
518b5d2f
VZ
674
675 if ( p_internal->GetState() == STATE_PAUSED )
676 {
677 // leave the crit section or the other threads will stop too if they try
678 // to call any of (seemingly harmless) IsXXX() functions while we sleep
679 m_critsect.Leave();
680
681 p_internal->Pause();
682
683 // enter it back before it's finally left in lock object dtor
684 m_critsect.Enter();
685 }
686
687 return p_internal->WasCancelled();
688}
689
690wxThread::~wxThread()
691{
692 // remove this thread from the global array
693 gs_allThreads.Remove(this);
694}
695
696// -----------------------------------------------------------------------------
697// state tests
698// -----------------------------------------------------------------------------
699
700bool wxThread::IsRunning() const
701{
702 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
703
704 return p_internal->GetState() == STATE_RUNNING;
705}
706
707bool wxThread::IsAlive() const
708{
709 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
710
711 switch ( p_internal->GetState() )
712 {
713 case STATE_RUNNING:
714 case STATE_PAUSED:
715 return TRUE;
716
717 default:
718 return FALSE;
719 }
720}
721
722//--------------------------------------------------------------------
723// wxThreadModule
724//--------------------------------------------------------------------
725
726class wxThreadModule : public wxModule
727{
728public:
729 virtual bool OnInit();
730 virtual void OnExit();
731
732private:
733 DECLARE_DYNAMIC_CLASS(wxThreadModule)
734};
735
736IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
737
738bool wxThreadModule::OnInit()
739{
740 if ( pthread_key_create(&gs_keySelf, NULL /* dtor function */) != 0 )
741 {
742 wxLogError(_("Thread module initialization failed: "
743 "failed to create pthread key."));
744
745 return FALSE;
746 }
747
748 gs_mutexGui = new wxMutex();
749
750 //wxThreadGuiInit();
751
752 gs_tidMain = pthread_self();
753 gs_mutexGui->Lock();
754
755 return TRUE;
756}
757
758void wxThreadModule::OnExit()
759{
760 wxASSERT_MSG( wxThread::IsMain(), "only main thread can be here" );
761
762 // terminate any threads left
763 size_t count = gs_allThreads.GetCount();
764 if ( count != 0u )
765 wxLogDebug("Some threads were not terminated by the application.");
766
767 for ( size_t n = 0u; n < count; n++ )
768 {
769 gs_allThreads[n]->Delete();
770 }
771
772 // destroy GUI mutex
773 gs_mutexGui->Unlock();
774
775 //wxThreadGuiExit();
776
777 delete gs_mutexGui;
778
779 // and free TLD slot
780 (void)pthread_key_delete(gs_keySelf);
781}
782
783// ----------------------------------------------------------------------------
784// global functions
785// ----------------------------------------------------------------------------
786
787void wxMutexGuiEnter()
788{
789 gs_mutexGui->Lock();
790}
791
792void wxMutexGuiLeave()
793{
794 gs_mutexGui->Unlock();
795}
80cb83be 796
7bcb11d3
JS
797#endif
798 // wxUSE_THREADS