]> git.saurik.com Git - wxWidgets.git/blame - src/unix/threadpsx.cpp
*** empty log message ***
[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
138static pthread_mutex_t gs_mutexDeleteThread = PTHREAD_MUTEX_INITIALIZER;
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
167 pthread_mutex_init(&(m_internal->m_mutex),
18341904 168 (pthread_mutexattr_t*) NULL );
518b5d2f
VZ
169 m_locked = 0;
170}
171
172wxMutex::~wxMutex()
173{
174 if (m_locked > 0)
223d09f6 175 wxLogDebug(wxT("Freeing a locked mutex (%d locks)"), m_locked);
518b5d2f 176
9fc3ad34
VZ
177 pthread_mutex_destroy( &(m_internal->m_mutex) );
178 delete m_internal;
518b5d2f
VZ
179}
180
181wxMutexError wxMutex::Lock()
182{
9fc3ad34 183 int err = pthread_mutex_lock( &(m_internal->m_mutex) );
518b5d2f
VZ
184 if (err == EDEADLK)
185 {
223d09f6 186 wxLogDebug(wxT("Locking this mutex would lead to deadlock!"));
518b5d2f
VZ
187
188 return wxMUTEX_DEAD_LOCK;
189 }
190
191 m_locked++;
192
193 return wxMUTEX_NO_ERROR;
194}
195
196wxMutexError wxMutex::TryLock()
197{
198 if (m_locked)
199 {
200 return wxMUTEX_BUSY;
201 }
202
9fc3ad34 203 int err = pthread_mutex_trylock( &(m_internal->m_mutex) );
518b5d2f
VZ
204 switch (err)
205 {
206 case EBUSY: return wxMUTEX_BUSY;
207 }
208
209 m_locked++;
210
211 return wxMUTEX_NO_ERROR;
212}
213
214wxMutexError wxMutex::Unlock()
215{
216 if (m_locked > 0)
217 {
218 m_locked--;
219 }
220 else
221 {
223d09f6 222 wxLogDebug(wxT("Unlocking not locked mutex."));
518b5d2f
VZ
223
224 return wxMUTEX_UNLOCKED;
225 }
226
9fc3ad34 227 pthread_mutex_unlock( &(m_internal->m_mutex) );
518b5d2f
VZ
228
229 return wxMUTEX_NO_ERROR;
230}
231
232//--------------------------------------------------------------------
233// wxCondition (Posix implementation)
234//--------------------------------------------------------------------
235
4c460b34
VZ
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
518b5d2f
VZ
242class wxConditionInternal
243{
244public:
9fc3ad34
VZ
245 wxConditionInternal();
246 ~wxConditionInternal();
247
248 void Wait();
249 bool WaitWithTimeout(const timespec* ts);
250
251 void Signal();
252 void Broadcast();
253
4c460b34
VZ
254 void WaitDone();
255 bool ShouldWait();
256 bool HasWaiters();
257
9fc3ad34 258private:
4c460b34
VZ
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
518b5d2f
VZ
267};
268
9fc3ad34
VZ
269wxConditionInternal::wxConditionInternal()
270{
4c460b34
VZ
271 m_wasSignaled = FALSE;
272 m_nWaiters = 0;
273
9fc3ad34
VZ
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
4c460b34
VZ
280 if ( pthread_mutex_init(&m_mutex, (pthread_mutexattr_t *)NULL) != 0 ||
281 pthread_mutex_init(&m_mutexProtect, NULL) != 0 )
9fc3ad34
VZ
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
295wxConditionInternal::~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
4c460b34
VZ
308 if ( pthread_mutex_destroy( &m_mutex ) != 0 ||
309 pthread_mutex_destroy( &m_mutexProtect ) != 0 )
9fc3ad34
VZ
310 {
311 wxLogDebug(_T("Failed to destroy mutex (it is probably locked)"));
312 }
313}
314
4c460b34
VZ
315void wxConditionInternal::WaitDone()
316{
317 MutexLock lock(m_mutexProtect);
318
319 m_wasSignaled = FALSE;
320 m_nWaiters--;
321}
322
323bool 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
342bool 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
9fc3ad34
VZ
359void wxConditionInternal::Wait()
360{
4c460b34 361 if ( ShouldWait() )
9fc3ad34 362 {
4c460b34
VZ
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 }
9fc3ad34 368 }
4c460b34
VZ
369
370 WaitDone();
9fc3ad34
VZ
371}
372
373bool wxConditionInternal::WaitWithTimeout(const timespec* ts)
374{
4c460b34
VZ
375 bool ok;
376
377 if ( ShouldWait() )
9fc3ad34 378 {
4c460b34
VZ
379 switch ( pthread_cond_timedwait( &m_condition, &m_mutex, ts ) )
380 {
381 case 0:
382 // condition signaled
383 ok = TRUE;
384 break;
9fc3ad34 385
4c460b34
VZ
386 default:
387 wxLogDebug(_T("pthread_cond_timedwait() failed"));
9fc3ad34 388
4c460b34 389 // fall through
9fc3ad34 390
4c460b34
VZ
391 case ETIMEDOUT:
392 case EINTR:
393 // wait interrupted or timeout elapsed
394 ok = FALSE;
395 }
9fc3ad34 396 }
4c460b34
VZ
397 else
398 {
399 // the condition had already been signaled before
400 ok = TRUE;
401 }
402
403 WaitDone();
404
405 return ok;
9fc3ad34
VZ
406}
407
408void wxConditionInternal::Signal()
409{
4c460b34 410 if ( HasWaiters() )
9fc3ad34 411 {
4c460b34
VZ
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 }
9fc3ad34
VZ
419 }
420}
421
422void wxConditionInternal::Broadcast()
423{
4c460b34 424 if ( HasWaiters() )
9fc3ad34 425 {
4c460b34
VZ
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 }
9fc3ad34
VZ
433 }
434}
435
518b5d2f
VZ
436wxCondition::wxCondition()
437{
9fc3ad34 438 m_internal = new wxConditionInternal;
518b5d2f
VZ
439}
440
441wxCondition::~wxCondition()
442{
9fc3ad34 443 delete m_internal;
518b5d2f
VZ
444}
445
9fc3ad34 446void wxCondition::Wait()
518b5d2f 447{
9fc3ad34 448 m_internal->Wait();
518b5d2f
VZ
449}
450
9fc3ad34 451bool wxCondition::Wait(unsigned long sec, unsigned long nsec)
518b5d2f 452{
9fc3ad34 453 timespec tspec;
518b5d2f 454
9fc3ad34 455 tspec.tv_sec = time(0L) + sec; // FIXME is time(0) correct here?
518b5d2f 456 tspec.tv_nsec = nsec;
9fc3ad34
VZ
457
458 return m_internal->WaitWithTimeout(&tspec);
518b5d2f
VZ
459}
460
461void wxCondition::Signal()
462{
9fc3ad34 463 m_internal->Signal();
518b5d2f
VZ
464}
465
466void wxCondition::Broadcast()
467{
9fc3ad34 468 m_internal->Broadcast();
518b5d2f
VZ
469}
470
471//--------------------------------------------------------------------
472// wxThread (Posix implementation)
473//--------------------------------------------------------------------
474
475class wxThreadInternal
476{
477public:
478 wxThreadInternal();
479 ~wxThreadInternal();
480
481 // thread entry function
482 static void *PthreadStart(void *ptr);
483
5092b3ad
GL
484#if HAVE_THREAD_CLEANUP_FUNCTIONS
485 // thread exit function
486 static void PthreadCleanup(void *ptr);
487#endif
488
518b5d2f
VZ
489 // thread actions
490 // start the thread
491 wxThreadError Run();
492 // ask the thread to terminate
882eefb1 493 void Wait();
518b5d2f
VZ
494 // wake up threads waiting for our termination
495 void SignalExit();
4c460b34
VZ
496 // wake up threads waiting for our start
497 void SignalRun() { m_condRun.Signal(); }
518b5d2f
VZ
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
882eefb1
VZ
508 wxThreadState GetState() const { return m_state; }
509 void SetState(wxThreadState state) { m_state = state; }
518b5d2f 510 // id
882eefb1
VZ
511 pthread_t GetId() const { return m_threadId; }
512 pthread_t *GetIdPtr() { return &m_threadId; }
518b5d2f 513 // "cancelled" flag
882eefb1 514 void SetCancelFlag() { m_cancelled = TRUE; }
518b5d2f 515 bool WasCancelled() const { return m_cancelled; }
9fc3ad34
VZ
516 // exit code
517 void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }
518 wxThread::ExitCode GetExitCode() const { return m_exitcode; }
519
4c460b34
VZ
520 // the pause flag
521 void SetReallyPaused(bool paused) { m_isPaused = paused; }
522 bool IsReallyPaused() const { return m_isPaused; }
523
9fc3ad34 524 // tell the thread that it is a detached one
4c460b34
VZ
525 void Detach()
526 {
527 m_shouldBeJoined = m_shouldBroadcast = FALSE;
528 m_isDetached = TRUE;
529 }
9fc3ad34
VZ
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; }
518b5d2f 533
518b5d2f 534private:
882eefb1
VZ
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
518b5d2f 538
9fc3ad34 539 // this flag is set when the thread should terminate
518b5d2f
VZ
540 bool m_cancelled;
541
4c460b34
VZ
542 // this flag is set when the thread is blocking on m_condSuspend
543 bool m_isPaused;
544
9fc3ad34
VZ
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;
4c460b34 554 bool m_isDetached;
9fc3ad34
VZ
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
518b5d2f 568 wxCondition m_condSuspend;
9fc3ad34
VZ
569
570 // finally this one is signalled when the thread exits
571 wxCondition m_condEnd;
518b5d2f
VZ
572};
573
9fc3ad34
VZ
574// ----------------------------------------------------------------------------
575// thread startup and exit functions
576// ----------------------------------------------------------------------------
577
518b5d2f
VZ
578void *wxThreadInternal::PthreadStart(void *ptr)
579{
580 wxThread *thread = (wxThread *)ptr;
9fc3ad34 581 wxThreadInternal *pthread = thread->m_internal;
518b5d2f 582
9fc3ad34
VZ
583 // associate the thread pointer with the newly created thread so that
584 // wxThread::This() will work
862cc6f9
VZ
585 int rc = pthread_setspecific(gs_keySelf, thread);
586 if ( rc != 0 )
518b5d2f 587 {
58230fb1 588 wxLogSysError(rc, _("Cannot start thread: error writing TLS"));
518b5d2f
VZ
589
590 return (void *)-1;
591 }
9fc3ad34 592
4c460b34
VZ
593 // have to declare this before pthread_cleanup_push() which defines a
594 // block!
595 bool dontRunAtAll;
596
5092b3ad 597#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34
VZ
598 // install the cleanup handler which will be called if the thread is
599 // cancelled
062c4861 600 pthread_cleanup_push(wxThreadInternal::PthreadCleanup, ptr);
9fc3ad34 601#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f
VZ
602
603 // wait for the condition to be signaled from Run()
9fc3ad34 604 pthread->m_condRun.Wait();
518b5d2f 605
4c460b34
VZ
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);
9fc3ad34 610
4c460b34
VZ
611 dontRunAtAll = pthread->GetState() == STATE_NEW &&
612 pthread->WasCancelled();
613 }
9fc3ad34 614
4c460b34 615 if ( !dontRunAtAll )
9fc3ad34 616 {
4c460b34
VZ
617 // call the main entry
618 pthread->m_exitcode = thread->Entry();
5092b3ad 619
4c460b34 620 wxLogTrace(TRACE_THREADS, _T("Thread %ld left its Entry()."),
9fc3ad34
VZ
621 pthread->GetId());
622
4c460b34
VZ
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 }
9fc3ad34
VZ
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!
5092b3ad 639#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34 640 // remove the cleanup handler without executing it
062c4861 641 pthread_cleanup_pop(FALSE);
9fc3ad34 642#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f 643
4c460b34
VZ
644 if ( dontRunAtAll )
645 {
646 delete thread;
518b5d2f 647
4c460b34
VZ
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."));
518b5d2f 656
4c460b34
VZ
657 return NULL;
658 }
518b5d2f
VZ
659}
660
5092b3ad 661#if HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 662
9fc3ad34 663// this handler is called when the thread is cancelled
5092b3ad
GL
664void wxThreadInternal::PthreadCleanup(void *ptr)
665{
666 wxThread *thread = (wxThread *) ptr;
667
9fc3ad34
VZ
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 }
5092b3ad 676
9fc3ad34
VZ
677 // exit the thread gracefully
678 thread->Exit(EXITCODE_CANCELLED);
679}
5092b3ad 680
9fc3ad34 681#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 682
9fc3ad34
VZ
683// ----------------------------------------------------------------------------
684// wxThreadInternal
685// ----------------------------------------------------------------------------
5092b3ad 686
518b5d2f
VZ
687wxThreadInternal::wxThreadInternal()
688{
689 m_state = STATE_NEW;
690 m_cancelled = FALSE;
bbfa0322
VZ
691 m_prio = WXTHREAD_DEFAULT_PRIORITY;
692 m_threadId = 0;
9fc3ad34 693 m_exitcode = 0;
518b5d2f 694
4c460b34
VZ
695 // set to TRUE only when the thread starts waiting on m_condSuspend
696 m_isPaused = FALSE;
697
9fc3ad34
VZ
698 // defaults for joinable threads
699 m_shouldBeJoined = TRUE;
700 m_shouldBroadcast = TRUE;
4c460b34 701 m_isDetached = FALSE;
518b5d2f
VZ
702}
703
704wxThreadInternal::~wxThreadInternal()
705{
518b5d2f
VZ
706}
707
708wxThreadError wxThreadInternal::Run()
709{
710 wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
9fc3ad34 711 wxT("thread may only be started once after Create()") );
518b5d2f 712
4c460b34 713 SignalRun();
518b5d2f 714
9fc3ad34 715 SetState(STATE_RUNNING);
518b5d2f
VZ
716
717 return wxTHREAD_NO_ERROR;
518b5d2f
VZ
718}
719
882eefb1 720void wxThreadInternal::Wait()
518b5d2f
VZ
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
4c460b34
VZ
727 bool isDetached = m_isDetached;
728 long id = GetId();
fcc3d7cb 729 wxLogTrace(TRACE_THREADS, _T("Starting to wait for thread %ld to exit."),
4c460b34 730 id);
fcc3d7cb 731
9fc3ad34
VZ
732 // wait until the thread terminates (we're blocking in _another_ thread,
733 // of course)
734 m_condEnd.Wait();
518b5d2f 735
4c460b34 736 wxLogTrace(TRACE_THREADS, _T("Finished waiting for thread %ld."), id);
518b5d2f 737
4c460b34
VZ
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 )
9fc3ad34 741 {
4c460b34
VZ
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 )
9fc3ad34 747 {
4c460b34
VZ
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(id, &m_exitcode) != 0 )
753 {
754 wxLogError(_("Failed to join a thread, potential memory leak "
755 "detected - please restart the program"));
756 }
9fc3ad34 757
4c460b34
VZ
758 m_shouldBeJoined = FALSE;
759 }
9fc3ad34 760 }
9111db68 761
518b5d2f
VZ
762 // reacquire GUI mutex
763 if ( wxThread::IsMain() )
764 wxMutexGuiEnter();
765}
766
767void wxThreadInternal::SignalExit()
768{
9fc3ad34 769 wxLogTrace(TRACE_THREADS, _T("Thread %ld about to exit."), GetId());
518b5d2f 770
9fc3ad34 771 SetState(STATE_EXITED);
518b5d2f 772
9fc3ad34
VZ
773 // wake up all the threads waiting for our termination - if there are any
774 if ( m_shouldBroadcast )
775 {
fcc3d7cb
VZ
776 wxLogTrace(TRACE_THREADS, _T("Thread %ld signals end condition."),
777 GetId());
778
9fc3ad34
VZ
779 m_condEnd.Broadcast();
780 }
518b5d2f
VZ
781}
782
783void wxThreadInternal::Pause()
784{
882eefb1
VZ
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
518b5d2f 787 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 788 wxT("thread must first be paused with wxThread::Pause().") );
518b5d2f 789
9fc3ad34 790 wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), GetId());
862cc6f9 791
518b5d2f 792 // wait until the condition is signaled from Resume()
9fc3ad34 793 m_condSuspend.Wait();
518b5d2f
VZ
794}
795
796void wxThreadInternal::Resume()
797{
798 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 799 wxT("can't resume thread which is not suspended.") );
518b5d2f 800
4c460b34
VZ
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());
9fc3ad34 806
4c460b34
VZ
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 }
518b5d2f
VZ
818
819 SetState(STATE_RUNNING);
820}
821
822// -----------------------------------------------------------------------------
9fc3ad34 823// wxThread static functions
518b5d2f
VZ
824// -----------------------------------------------------------------------------
825
826wxThread *wxThread::This()
827{
828 return (wxThread *)pthread_getspecific(gs_keySelf);
829}
830
831bool wxThread::IsMain()
832{
833 return (bool)pthread_equal(pthread_self(), gs_tidMain);
834}
835
836void wxThread::Yield()
837{
838 sched_yield();
839}
840
841void wxThread::Sleep(unsigned long milliseconds)
842{
843 wxUsleep(milliseconds);
844}
845
ef8d96c2
VZ
846int 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
887bool 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
518b5d2f
VZ
903// -----------------------------------------------------------------------------
904// creating thread
905// -----------------------------------------------------------------------------
906
acb8423c 907wxThread::wxThread(wxThreadKind kind)
518b5d2f
VZ
908{
909 // add this thread to the global list of all threads
910 gs_allThreads.Add(this);
911
9fc3ad34 912 m_internal = new wxThreadInternal();
acb8423c
VZ
913
914 m_isDetached = kind == wxTHREAD_DETACHED;
518b5d2f
VZ
915}
916
917wxThreadError wxThread::Create()
918{
9fc3ad34
VZ
919 if ( m_internal->GetState() != STATE_NEW )
920 {
921 // don't recreate thread
518b5d2f 922 return wxTHREAD_RUNNING;
9fc3ad34 923 }
518b5d2f
VZ
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
fc9ef629 929#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
9fc3ad34
VZ
930 int policy;
931 if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 )
518b5d2f 932 {
58230fb1 933 wxLogError(_("Cannot retrieve thread scheduling policy."));
518b5d2f
VZ
934 }
935
9fc3ad34
VZ
936 int min_prio = sched_get_priority_min(policy),
937 max_prio = sched_get_priority_max(policy),
938 prio = m_internal->GetPriority();
518b5d2f
VZ
939
940 if ( min_prio == -1 || max_prio == -1 )
941 {
58230fb1 942 wxLogError(_("Cannot get priority range for scheduling policy %d."),
9fc3ad34 943 policy);
518b5d2f 944 }
bbfa0322
VZ
945 else if ( max_prio == min_prio )
946 {
9fc3ad34 947 if ( prio != WXTHREAD_DEFAULT_PRIORITY )
bbfa0322
VZ
948 {
949 // notify the programmer that this doesn't work here
950 wxLogWarning(_("Thread priority setting is ignored."));
951 }
952 //else: we have default priority, so don't complain
953
954 // anyhow, don't do anything because priority is just ignored
955 }
518b5d2f
VZ
956 else
957 {
958 struct sched_param sp;
9fc3ad34
VZ
959 if ( pthread_attr_getschedparam(&attr, &sp) != 0 )
960 {
961 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
962 }
963
964 sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100;
965
966 if ( pthread_attr_setschedparam(&attr, &sp) != 0 )
967 {
968 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
969 }
518b5d2f 970 }
34f8c26e 971#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f 972
58230fb1
VZ
973#ifdef HAVE_PTHREAD_ATTR_SETSCOPE
974 // this will make the threads created by this process really concurrent
9fc3ad34
VZ
975 if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 )
976 {
977 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
978 }
58230fb1
VZ
979#endif // HAVE_PTHREAD_ATTR_SETSCOPE
980
9fc3ad34
VZ
981 // VZ: assume that this one is always available (it's rather fundamental),
982 // if this function is ever missing we should try to use
983 // pthread_detach() instead (after thread creation)
984 if ( m_isDetached )
985 {
986 if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 )
987 {
988 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
989 }
990
991 // never try to join detached threads
992 m_internal->Detach();
993 }
994 //else: threads are created joinable by default, it's ok
995
518b5d2f 996 // create the new OS thread object
9fc3ad34
VZ
997 int rc = pthread_create
998 (
999 m_internal->GetIdPtr(),
1000 &attr,
1001 wxThreadInternal::PthreadStart,
1002 (void *)this
1003 );
1004
1005 if ( pthread_attr_destroy(&attr) != 0 )
1006 {
1007 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1008 }
518b5d2f
VZ
1009
1010 if ( rc != 0 )
1011 {
9fc3ad34
VZ
1012 m_internal->SetState(STATE_EXITED);
1013
518b5d2f
VZ
1014 return wxTHREAD_NO_RESOURCE;
1015 }
1016
1017 return wxTHREAD_NO_ERROR;
1018}
1019
1020wxThreadError wxThread::Run()
1021{
9fc3ad34
VZ
1022 wxCriticalSectionLocker lock(m_critsect);
1023
1024 wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR,
223d09f6 1025 wxT("must call wxThread::Create() first") );
bbfa0322 1026
9fc3ad34 1027 return m_internal->Run();
518b5d2f
VZ
1028}
1029
1030// -----------------------------------------------------------------------------
1031// misc accessors
1032// -----------------------------------------------------------------------------
1033
1034void wxThread::SetPriority(unsigned int prio)
1035{
34f8c26e
VZ
1036 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) &&
1037 ((int)prio <= (int)WXTHREAD_MAX_PRIORITY),
223d09f6 1038 wxT("invalid thread priority") );
518b5d2f
VZ
1039
1040 wxCriticalSectionLocker lock(m_critsect);
1041
9fc3ad34 1042 switch ( m_internal->GetState() )
518b5d2f
VZ
1043 {
1044 case STATE_NEW:
1045 // thread not yet started, priority will be set when it is
9fc3ad34 1046 m_internal->SetPriority(prio);
518b5d2f
VZ
1047 break;
1048
1049 case STATE_RUNNING:
1050 case STATE_PAUSED:
34f8c26e 1051#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
1052 {
1053 struct sched_param sparam;
1054 sparam.sched_priority = prio;
1055
9fc3ad34 1056 if ( pthread_setschedparam(m_internal->GetId(),
518b5d2f
VZ
1057 SCHED_OTHER, &sparam) != 0 )
1058 {
1059 wxLogError(_("Failed to set thread priority %d."), prio);
1060 }
1061 }
34f8c26e 1062#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
1063 break;
1064
1065 case STATE_EXITED:
1066 default:
223d09f6 1067 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
518b5d2f
VZ
1068 }
1069}
1070
1071unsigned int wxThread::GetPriority() const
1072{
1073 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1074
9fc3ad34 1075 return m_internal->GetPriority();
518b5d2f
VZ
1076}
1077
acb8423c 1078unsigned long wxThread::GetId() const
518b5d2f 1079{
9fc3ad34 1080 return (unsigned long)m_internal->GetId();
518b5d2f
VZ
1081}
1082
1083// -----------------------------------------------------------------------------
1084// pause/resume
1085// -----------------------------------------------------------------------------
1086
1087wxThreadError wxThread::Pause()
1088{
4c460b34
VZ
1089 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1090 _T("a thread can't pause itself") );
1091
518b5d2f
VZ
1092 wxCriticalSectionLocker lock(m_critsect);
1093
9fc3ad34 1094 if ( m_internal->GetState() != STATE_RUNNING )
518b5d2f 1095 {
223d09f6 1096 wxLogDebug(wxT("Can't pause thread which is not running."));
518b5d2f
VZ
1097
1098 return wxTHREAD_NOT_RUNNING;
1099 }
1100
4c460b34
VZ
1101 wxLogTrace(TRACE_THREADS, _T("Asking thread %ld to pause."),
1102 GetId());
1103
9fc3ad34
VZ
1104 // just set a flag, the thread will be really paused only during the next
1105 // call to TestDestroy()
1106 m_internal->SetState(STATE_PAUSED);
518b5d2f
VZ
1107
1108 return wxTHREAD_NO_ERROR;
1109}
1110
1111wxThreadError wxThread::Resume()
1112{
4c460b34
VZ
1113 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1114 _T("a thread can't resume itself") );
518b5d2f 1115
4c460b34 1116 wxCriticalSectionLocker lock(m_critsect);
518b5d2f 1117
4c460b34 1118 wxThreadState state = m_internal->GetState();
9fc3ad34
VZ
1119
1120 switch ( state )
518b5d2f 1121 {
9fc3ad34 1122 case STATE_PAUSED:
4c460b34 1123 wxLogTrace(TRACE_THREADS, _T("Thread %ld suspended, resuming."),
9fc3ad34
VZ
1124 GetId());
1125
1126 m_internal->Resume();
1127
1128 return wxTHREAD_NO_ERROR;
1129
1130 case STATE_EXITED:
1131 wxLogTrace(TRACE_THREADS, _T("Thread %ld exited, won't resume."),
1132 GetId());
1133 return wxTHREAD_NO_ERROR;
518b5d2f 1134
9fc3ad34
VZ
1135 default:
1136 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1137
1138 return wxTHREAD_MISC_ERROR;
518b5d2f
VZ
1139 }
1140}
1141
1142// -----------------------------------------------------------------------------
1143// exiting thread
1144// -----------------------------------------------------------------------------
1145
9fc3ad34 1146wxThread::ExitCode wxThread::Wait()
b568d04f 1147{
9fc3ad34
VZ
1148 wxCHECK_MSG( This() != this, (ExitCode)-1,
1149 _T("a thread can't wait for itself") );
1150
1151 wxCHECK_MSG( !m_isDetached, (ExitCode)-1,
1152 _T("can't wait for detached thread") );
1153
1154 m_internal->Wait();
b568d04f 1155
9fc3ad34 1156 return m_internal->GetExitCode();
b568d04f
VZ
1157}
1158
1159wxThreadError wxThread::Delete(ExitCode *rc)
518b5d2f 1160{
4c460b34
VZ
1161 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1162 _T("a thread can't delete itself") );
1163
518b5d2f 1164 m_critsect.Enter();
9fc3ad34 1165 wxThreadState state = m_internal->GetState();
518b5d2f 1166
882eefb1 1167 // ask the thread to stop
9fc3ad34
VZ
1168 m_internal->SetCancelFlag();
1169
1170 if ( m_isDetached )
1171 {
1172 // detached threads won't broadcast about their termination by default
1173 // because usually nobody waits for them - but here we do, so ask the
1174 // thread to notify us
1175 m_internal->Notify();
1176 }
882eefb1 1177
9111db68
GL
1178 m_critsect.Leave();
1179
518b5d2f
VZ
1180 switch ( state )
1181 {
1182 case STATE_NEW:
4c460b34
VZ
1183 // we need to wake up the thread so that PthreadStart() will
1184 // terminate - right now it's blocking on m_condRun
1185 m_internal->SignalRun();
1186
1187 // fall through
1188
518b5d2f
VZ
1189 case STATE_EXITED:
1190 // nothing to do
1191 break;
1192
1193 case STATE_PAUSED:
9fc3ad34
VZ
1194 // resume the thread first (don't call our Resume() because this
1195 // would dead lock when it tries to enter m_critsect)
1196 m_internal->Resume();
518b5d2f
VZ
1197
1198 // fall through
1199
1200 default:
882eefb1 1201 // wait until the thread stops
9fc3ad34
VZ
1202 m_internal->Wait();
1203
1204 if ( rc )
1205 {
1206 wxASSERT_MSG( !m_isDetached,
1207 _T("no return code for detached threads") );
1208
1209 // if it's a joinable thread, it's not deleted yet
1210 *rc = m_internal->GetExitCode();
1211 }
518b5d2f
VZ
1212 }
1213
acb8423c 1214 return wxTHREAD_NO_ERROR;
518b5d2f
VZ
1215}
1216
1217wxThreadError wxThread::Kill()
1218{
9fc3ad34
VZ
1219 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1220 _T("a thread can't kill itself") );
1221
1222 switch ( m_internal->GetState() )
518b5d2f
VZ
1223 {
1224 case STATE_NEW:
1225 case STATE_EXITED:
1226 return wxTHREAD_NOT_RUNNING;
1227
9fc3ad34
VZ
1228 case STATE_PAUSED:
1229 // resume the thread first
1230 Resume();
1231
1232 // fall through
1233
518b5d2f 1234 default:
9fc3ad34
VZ
1235#ifdef HAVE_PTHREAD_CANCEL
1236 if ( pthread_cancel(m_internal->GetId()) != 0 )
34f8c26e 1237#endif
518b5d2f
VZ
1238 {
1239 wxLogError(_("Failed to terminate a thread."));
1240
1241 return wxTHREAD_MISC_ERROR;
1242 }
9fc3ad34
VZ
1243
1244 if ( m_isDetached )
1245 {
1246 // if we use cleanup function, this will be done from
1247 // PthreadCleanup()
1248#if !HAVE_THREAD_CLEANUP_FUNCTIONS
1249 ScheduleThreadForDeletion();
1250
1251 OnExit();
1252
1253 DeleteThread(this);
1254#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1255 }
1256 else
1257 {
1258 m_internal->SetExitCode(EXITCODE_CANCELLED);
1259 }
518b5d2f
VZ
1260
1261 return wxTHREAD_NO_ERROR;
1262 }
1263}
1264
b568d04f 1265void wxThread::Exit(ExitCode status)
518b5d2f 1266{
4c460b34
VZ
1267 wxASSERT_MSG( This() == this,
1268 _T("wxThread::Exit() can only be called in the "
1269 "context of the same thread") );
1270
9fc3ad34
VZ
1271 // from the moment we call OnExit(), the main program may terminate at any
1272 // moment, so mark this thread as being already in process of being
1273 // deleted or wxThreadModule::OnExit() will try to delete it again
1274 ScheduleThreadForDeletion();
1275
1276 // don't enter m_critsect before calling OnExit() because the user code
1277 // might deadlock if, for example, it signals a condition in OnExit() (a
1278 // common case) while the main thread calls any of functions entering
1279 // m_critsect on us (almost all of them do)
518b5d2f
VZ
1280 OnExit();
1281
9fc3ad34
VZ
1282 // now do enter it because SignalExit() will change our state
1283 m_critsect.Enter();
1284
518b5d2f
VZ
1285 // next wake up the threads waiting for us (OTOH, this function won't return
1286 // until someone waited for us!)
9fc3ad34 1287 m_internal->SignalExit();
5092b3ad 1288
9fc3ad34
VZ
1289 // leave the critical section before entering the dtor which tries to
1290 // enter it
1291 m_critsect.Leave();
2a4f27f2 1292
9fc3ad34
VZ
1293 // delete C++ thread object if this is a detached thread - user is
1294 // responsible for doing this for joinable ones
1295 if ( m_isDetached )
1296 {
1297 // FIXME I'm feeling bad about it - what if another thread function is
1298 // called (in another thread context) now? It will try to access
1299 // half destroyed object which will probably result in something
1300 // very bad - but we can't protect this by a crit section unless
1301 // we make it a global object, but this would mean that we can
1302 // only call one thread function at a time :-(
1303 DeleteThread(this);
1304 }
1305
1306 // terminate the thread (pthread_exit() never returns)
518b5d2f 1307 pthread_exit(status);
9fc3ad34
VZ
1308
1309 wxFAIL_MSG(_T("pthread_exit() failed"));
518b5d2f
VZ
1310}
1311
1312// also test whether we were paused
1313bool wxThread::TestDestroy()
1314{
4c460b34
VZ
1315 wxASSERT_MSG( This() == this,
1316 _T("wxThread::TestDestroy() can only be called in the "
1317 "context of the same thread") );
1318
9fc3ad34 1319 m_critsect.Enter();
518b5d2f 1320
9fc3ad34 1321 if ( m_internal->GetState() == STATE_PAUSED )
518b5d2f 1322 {
4c460b34
VZ
1323 m_internal->SetReallyPaused(TRUE);
1324
9fc3ad34
VZ
1325 // leave the crit section or the other threads will stop too if they
1326 // try to call any of (seemingly harmless) IsXXX() functions while we
1327 // sleep
518b5d2f
VZ
1328 m_critsect.Leave();
1329
9fc3ad34
VZ
1330 m_internal->Pause();
1331 }
1332 else
1333 {
1334 // thread wasn't requested to pause, nothing to do
1335 m_critsect.Leave();
518b5d2f
VZ
1336 }
1337
9fc3ad34 1338 return m_internal->WasCancelled();
518b5d2f
VZ
1339}
1340
1341wxThread::~wxThread()
1342{
9fc3ad34 1343#ifdef __WXDEBUG__
062c4861 1344 m_critsect.Enter();
9fc3ad34
VZ
1345
1346 // check that the thread either exited or couldn't be created
1347 if ( m_internal->GetState() != STATE_EXITED &&
1348 m_internal->GetState() != STATE_NEW )
bbfa0322 1349 {
4c460b34
VZ
1350 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1351 "running! The application may crash."), GetId());
bbfa0322 1352 }
062c4861
GL
1353
1354 m_critsect.Leave();
9fc3ad34 1355#endif // __WXDEBUG__
062c4861 1356
9fc3ad34 1357 delete m_internal;
bbfa0322 1358
518b5d2f
VZ
1359 // remove this thread from the global array
1360 gs_allThreads.Remove(this);
4c460b34
VZ
1361
1362 // detached thread will decrement this counter in DeleteThread(), but it
1363 // is not called for the joinable threads, so do it here
1364 if ( !m_isDetached )
1365 {
1366 MutexLock lock(gs_mutexDeleteThread);
1367 gs_nThreadsBeingDeleted--;
1368
1369 wxLogTrace(TRACE_THREADS, _T("%u scheduled for deletion threads left."),
1370 gs_nThreadsBeingDeleted - 1);
1371 }
518b5d2f
VZ
1372}
1373
1374// -----------------------------------------------------------------------------
1375// state tests
1376// -----------------------------------------------------------------------------
1377
1378bool wxThread::IsRunning() const
1379{
1380 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1381
9fc3ad34 1382 return m_internal->GetState() == STATE_RUNNING;
518b5d2f
VZ
1383}
1384
1385bool wxThread::IsAlive() const
1386{
1387 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1388
9fc3ad34 1389 switch ( m_internal->GetState() )
518b5d2f
VZ
1390 {
1391 case STATE_RUNNING:
1392 case STATE_PAUSED:
1393 return TRUE;
1394
1395 default:
1396 return FALSE;
1397 }
1398}
1399
a737331d
GL
1400bool wxThread::IsPaused() const
1401{
1402 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1403
9fc3ad34 1404 return (m_internal->GetState() == STATE_PAUSED);
a737331d
GL
1405}
1406
518b5d2f
VZ
1407//--------------------------------------------------------------------
1408// wxThreadModule
1409//--------------------------------------------------------------------
1410
1411class wxThreadModule : public wxModule
1412{
1413public:
1414 virtual bool OnInit();
1415 virtual void OnExit();
1416
1417private:
1418 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1419};
1420
1421IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1422
1423bool wxThreadModule::OnInit()
1424{
58230fb1
VZ
1425 int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */);
1426 if ( rc != 0 )
518b5d2f 1427 {
58230fb1
VZ
1428 wxLogSysError(rc, _("Thread module initialization failed: "
1429 "failed to create thread key"));
518b5d2f
VZ
1430
1431 return FALSE;
1432 }
1433
518b5d2f 1434 gs_tidMain = pthread_self();
19da4326 1435
9fc3ad34
VZ
1436#if wxUSE_GUI
1437 gs_mutexGui = new wxMutex();
1438
518b5d2f 1439 gs_mutexGui->Lock();
9fc3ad34 1440#endif // wxUSE_GUI
518b5d2f
VZ
1441
1442 return TRUE;
1443}
1444
1445void wxThreadModule::OnExit()
1446{
223d09f6 1447 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
518b5d2f 1448
9fc3ad34
VZ
1449 // are there any threads left which are being deleted right now?
1450 size_t nThreadsBeingDeleted;
1451 {
1452 MutexLock lock(gs_mutexDeleteThread);
1453 nThreadsBeingDeleted = gs_nThreadsBeingDeleted;
1454 }
1455
1456 if ( nThreadsBeingDeleted > 0 )
1457 {
1458 wxLogTrace(TRACE_THREADS, _T("Waiting for %u threads to disappear"),
1459 nThreadsBeingDeleted);
1460
1461 // have to wait until all of them disappear
1462 gs_condAllDeleted->Wait();
1463 }
1464
518b5d2f
VZ
1465 // terminate any threads left
1466 size_t count = gs_allThreads.GetCount();
1467 if ( count != 0u )
4c460b34
VZ
1468 {
1469 wxLogDebug(wxT("%u threads were not terminated by the application."),
1470 count);
1471 }
518b5d2f
VZ
1472
1473 for ( size_t n = 0u; n < count; n++ )
1474 {
bbfa0322
VZ
1475 // Delete calls the destructor which removes the current entry. We
1476 // should only delete the first one each time.
0ac77ef5 1477 gs_allThreads[0]->Delete();
518b5d2f
VZ
1478 }
1479
9fc3ad34 1480#if wxUSE_GUI
518b5d2f
VZ
1481 // destroy GUI mutex
1482 gs_mutexGui->Unlock();
1483
518b5d2f 1484 delete gs_mutexGui;
9fc3ad34 1485#endif // wxUSE_GUI
518b5d2f
VZ
1486
1487 // and free TLD slot
1488 (void)pthread_key_delete(gs_keySelf);
1489}
1490
1491// ----------------------------------------------------------------------------
1492// global functions
1493// ----------------------------------------------------------------------------
1494
9fc3ad34
VZ
1495static void ScheduleThreadForDeletion()
1496{
1497 MutexLock lock(gs_mutexDeleteThread);
1498
1499 if ( gs_nThreadsBeingDeleted == 0 )
1500 {
1501 gs_condAllDeleted = new wxCondition;
1502 }
1503
1504 gs_nThreadsBeingDeleted++;
1505
fcc3d7cb
VZ
1506 wxLogTrace(TRACE_THREADS, _T("%u thread%s waiting to be deleted"),
1507 gs_nThreadsBeingDeleted,
1508 gs_nThreadsBeingDeleted == 1 ? "" : "s");
9fc3ad34
VZ
1509}
1510
1511static void DeleteThread(wxThread *This)
1512{
1513 // gs_mutexDeleteThread should be unlocked before signalling the condition
1514 // or wxThreadModule::OnExit() would deadlock
1515 {
1516 MutexLock lock(gs_mutexDeleteThread);
1517
1518 wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId());
1519
1520 delete This;
1521
1522 wxCHECK_RET( gs_nThreadsBeingDeleted > 0,
1523 _T("no threads scheduled for deletion, yet we delete "
1524 "one?") );
1525 }
1526
4c460b34
VZ
1527 wxLogTrace(TRACE_THREADS, _T("%u scheduled for deletion threads left."),
1528 gs_nThreadsBeingDeleted - 1);
1529
9fc3ad34
VZ
1530 if ( !--gs_nThreadsBeingDeleted )
1531 {
1532 // no more threads left, signal it
1533 gs_condAllDeleted->Signal();
1534
1535 delete gs_condAllDeleted;
1536 gs_condAllDeleted = (wxCondition *)NULL;
1537 }
1538}
1539
518b5d2f
VZ
1540void wxMutexGuiEnter()
1541{
9fc3ad34
VZ
1542#if wxUSE_GUI
1543 gs_mutexGui->Lock();
1544#endif // wxUSE_GUI
518b5d2f
VZ
1545}
1546
1547void wxMutexGuiLeave()
1548{
9fc3ad34
VZ
1549#if wxUSE_GUI
1550 gs_mutexGui->Unlock();
1551#endif // wxUSE_GUI
518b5d2f 1552}
80cb83be 1553
7bcb11d3
JS
1554#endif
1555 // wxUSE_THREADS