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