]> git.saurik.com Git - wxWidgets.git/blame - src/unix/threadpsx.cpp
oops, typo leading to compilation problem fixed
[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
493class wxThreadInternal
494{
495public:
496 wxThreadInternal();
497 ~wxThreadInternal();
498
499 // thread entry function
500 static void *PthreadStart(void *ptr);
501
5092b3ad
GL
502#if HAVE_THREAD_CLEANUP_FUNCTIONS
503 // thread exit function
504 static void PthreadCleanup(void *ptr);
505#endif
506
518b5d2f
VZ
507 // thread actions
508 // start the thread
509 wxThreadError Run();
510 // ask the thread to terminate
882eefb1 511 void Wait();
518b5d2f
VZ
512 // wake up threads waiting for our termination
513 void SignalExit();
4c460b34
VZ
514 // wake up threads waiting for our start
515 void SignalRun() { m_condRun.Signal(); }
518b5d2f
VZ
516 // go to sleep until Resume() is called
517 void Pause();
518 // resume the thread
519 void Resume();
520
521 // accessors
522 // priority
523 int GetPriority() const { return m_prio; }
524 void SetPriority(int prio) { m_prio = prio; }
525 // state
882eefb1
VZ
526 wxThreadState GetState() const { return m_state; }
527 void SetState(wxThreadState state) { m_state = state; }
518b5d2f 528 // id
882eefb1
VZ
529 pthread_t GetId() const { return m_threadId; }
530 pthread_t *GetIdPtr() { return &m_threadId; }
518b5d2f 531 // "cancelled" flag
882eefb1 532 void SetCancelFlag() { m_cancelled = TRUE; }
518b5d2f 533 bool WasCancelled() const { return m_cancelled; }
9fc3ad34
VZ
534 // exit code
535 void SetExitCode(wxThread::ExitCode exitcode) { m_exitcode = exitcode; }
536 wxThread::ExitCode GetExitCode() const { return m_exitcode; }
537
4c460b34
VZ
538 // the pause flag
539 void SetReallyPaused(bool paused) { m_isPaused = paused; }
540 bool IsReallyPaused() const { return m_isPaused; }
541
9fc3ad34 542 // tell the thread that it is a detached one
4c460b34
VZ
543 void Detach()
544 {
545 m_shouldBeJoined = m_shouldBroadcast = FALSE;
546 m_isDetached = TRUE;
547 }
9fc3ad34
VZ
548 // but even detached threads need to notifyus about their termination
549 // sometimes - tell the thread that it should do it
550 void Notify() { m_shouldBroadcast = TRUE; }
518b5d2f 551
518b5d2f 552private:
882eefb1
VZ
553 pthread_t m_threadId; // id of the thread
554 wxThreadState m_state; // see wxThreadState enum
555 int m_prio; // in wxWindows units: from 0 to 100
518b5d2f 556
9fc3ad34 557 // this flag is set when the thread should terminate
518b5d2f
VZ
558 bool m_cancelled;
559
4c460b34
VZ
560 // this flag is set when the thread is blocking on m_condSuspend
561 bool m_isPaused;
562
9fc3ad34
VZ
563 // the thread exit code - only used for joinable (!detached) threads and
564 // is only valid after the thread termination
565 wxThread::ExitCode m_exitcode;
566
567 // many threads may call Wait(), but only one of them should call
568 // pthread_join(), so we have to keep track of this
569 wxCriticalSection m_csJoinFlag;
570 bool m_shouldBeJoined;
571 bool m_shouldBroadcast;
4c460b34 572 bool m_isDetached;
9fc3ad34
VZ
573
574 // VZ: it's possible that we might do with less than three different
575 // condition objects - for example, m_condRun and m_condEnd a priori
576 // won't be used in the same time. But for now I prefer this may be a
577 // bit less efficient but safer solution of having distinct condition
578 // variables for each purpose.
579
580 // this condition is signaled by Run() and the threads Entry() is not
581 // called before it is done
582 wxCondition m_condRun;
583
584 // this one is signaled when the thread should resume after having been
585 // Pause()d
518b5d2f 586 wxCondition m_condSuspend;
9fc3ad34
VZ
587
588 // finally this one is signalled when the thread exits
589 wxCondition m_condEnd;
518b5d2f
VZ
590};
591
9fc3ad34
VZ
592// ----------------------------------------------------------------------------
593// thread startup and exit functions
594// ----------------------------------------------------------------------------
595
518b5d2f
VZ
596void *wxThreadInternal::PthreadStart(void *ptr)
597{
598 wxThread *thread = (wxThread *)ptr;
9fc3ad34 599 wxThreadInternal *pthread = thread->m_internal;
518b5d2f 600
9fc3ad34
VZ
601 // associate the thread pointer with the newly created thread so that
602 // wxThread::This() will work
862cc6f9
VZ
603 int rc = pthread_setspecific(gs_keySelf, thread);
604 if ( rc != 0 )
518b5d2f 605 {
58230fb1 606 wxLogSysError(rc, _("Cannot start thread: error writing TLS"));
518b5d2f
VZ
607
608 return (void *)-1;
609 }
9fc3ad34 610
4c460b34
VZ
611 // have to declare this before pthread_cleanup_push() which defines a
612 // block!
613 bool dontRunAtAll;
614
5092b3ad 615#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34
VZ
616 // install the cleanup handler which will be called if the thread is
617 // cancelled
062c4861 618 pthread_cleanup_push(wxThreadInternal::PthreadCleanup, ptr);
9fc3ad34 619#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f
VZ
620
621 // wait for the condition to be signaled from Run()
9fc3ad34 622 pthread->m_condRun.Wait();
518b5d2f 623
4c460b34
VZ
624 // test whether we should run the run at all - may be it was deleted
625 // before it started to Run()?
626 {
627 wxCriticalSectionLocker lock(thread->m_critsect);
9fc3ad34 628
4c460b34
VZ
629 dontRunAtAll = pthread->GetState() == STATE_NEW &&
630 pthread->WasCancelled();
631 }
9fc3ad34 632
4c460b34 633 if ( !dontRunAtAll )
9fc3ad34 634 {
4c460b34
VZ
635 // call the main entry
636 pthread->m_exitcode = thread->Entry();
5092b3ad 637
4c460b34 638 wxLogTrace(TRACE_THREADS, _T("Thread %ld left its Entry()."),
9fc3ad34
VZ
639 pthread->GetId());
640
4c460b34
VZ
641 {
642 wxCriticalSectionLocker lock(thread->m_critsect);
643
644 wxLogTrace(TRACE_THREADS, _T("Thread %ld changes state to EXITED."),
645 pthread->GetId());
646
647 // change the state of the thread to "exited" so that
648 // PthreadCleanup handler won't do anything from now (if it's
649 // called before we do pthread_cleanup_pop below)
650 pthread->SetState(STATE_EXITED);
651 }
9fc3ad34
VZ
652 }
653
654 // NB: at least under Linux, pthread_cleanup_push/pop are macros and pop
655 // contains the matching '}' for the '{' in push, so they must be used
656 // in the same block!
5092b3ad 657#if HAVE_THREAD_CLEANUP_FUNCTIONS
9fc3ad34 658 // remove the cleanup handler without executing it
062c4861 659 pthread_cleanup_pop(FALSE);
9fc3ad34 660#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
518b5d2f 661
4c460b34
VZ
662 if ( dontRunAtAll )
663 {
664 delete thread;
518b5d2f 665
4c460b34
VZ
666 return EXITCODE_CANCELLED;
667 }
668 else
669 {
670 // terminate the thread
671 thread->Exit(pthread->m_exitcode);
672
673 wxFAIL_MSG(wxT("wxThread::Exit() can't return."));
518b5d2f 674
4c460b34
VZ
675 return NULL;
676 }
518b5d2f
VZ
677}
678
5092b3ad 679#if HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 680
9fc3ad34 681// this handler is called when the thread is cancelled
5092b3ad
GL
682void wxThreadInternal::PthreadCleanup(void *ptr)
683{
684 wxThread *thread = (wxThread *) ptr;
685
9fc3ad34
VZ
686 {
687 wxCriticalSectionLocker lock(thread->m_critsect);
688 if ( thread->m_internal->GetState() == STATE_EXITED )
689 {
690 // thread is already considered as finished.
691 return;
692 }
693 }
5092b3ad 694
9fc3ad34
VZ
695 // exit the thread gracefully
696 thread->Exit(EXITCODE_CANCELLED);
697}
5092b3ad 698
9fc3ad34 699#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
5092b3ad 700
9fc3ad34
VZ
701// ----------------------------------------------------------------------------
702// wxThreadInternal
703// ----------------------------------------------------------------------------
5092b3ad 704
518b5d2f
VZ
705wxThreadInternal::wxThreadInternal()
706{
707 m_state = STATE_NEW;
708 m_cancelled = FALSE;
bbfa0322
VZ
709 m_prio = WXTHREAD_DEFAULT_PRIORITY;
710 m_threadId = 0;
9fc3ad34 711 m_exitcode = 0;
518b5d2f 712
4c460b34
VZ
713 // set to TRUE only when the thread starts waiting on m_condSuspend
714 m_isPaused = FALSE;
715
9fc3ad34
VZ
716 // defaults for joinable threads
717 m_shouldBeJoined = TRUE;
718 m_shouldBroadcast = TRUE;
4c460b34 719 m_isDetached = FALSE;
518b5d2f
VZ
720}
721
722wxThreadInternal::~wxThreadInternal()
723{
518b5d2f
VZ
724}
725
726wxThreadError wxThreadInternal::Run()
727{
728 wxCHECK_MSG( GetState() == STATE_NEW, wxTHREAD_RUNNING,
9fc3ad34 729 wxT("thread may only be started once after Create()") );
518b5d2f 730
4c460b34 731 SignalRun();
518b5d2f 732
9fc3ad34 733 SetState(STATE_RUNNING);
518b5d2f
VZ
734
735 return wxTHREAD_NO_ERROR;
518b5d2f
VZ
736}
737
882eefb1 738void wxThreadInternal::Wait()
518b5d2f
VZ
739{
740 // if the thread we're waiting for is waiting for the GUI mutex, we will
741 // deadlock so make sure we release it temporarily
742 if ( wxThread::IsMain() )
743 wxMutexGuiLeave();
744
4c460b34 745 bool isDetached = m_isDetached;
9c2882d9 746 long id = (long)GetId();
fcc3d7cb 747 wxLogTrace(TRACE_THREADS, _T("Starting to wait for thread %ld to exit."),
4c460b34 748 id);
fcc3d7cb 749
9fc3ad34
VZ
750 // wait until the thread terminates (we're blocking in _another_ thread,
751 // of course)
752 m_condEnd.Wait();
518b5d2f 753
4c460b34 754 wxLogTrace(TRACE_THREADS, _T("Finished waiting for thread %ld."), id);
518b5d2f 755
4c460b34
VZ
756 // we can't use any member variables any more if the thread is detached
757 // because it could be already deleted
758 if ( !isDetached )
9fc3ad34 759 {
4c460b34
VZ
760 // to avoid memory leaks we should call pthread_join(), but it must
761 // only be done once
762 wxCriticalSectionLocker lock(m_csJoinFlag);
763
764 if ( m_shouldBeJoined )
9fc3ad34 765 {
4c460b34
VZ
766 // FIXME shouldn't we set cancellation type to DISABLED here? If
767 // we're cancelled inside pthread_join(), things will almost
768 // certainly break - but if we disable the cancellation, we
769 // might deadlock
d5fc4661 770 if ( pthread_join((pthread_t)id, &m_exitcode) != 0 )
4c460b34
VZ
771 {
772 wxLogError(_("Failed to join a thread, potential memory leak "
773 "detected - please restart the program"));
774 }
9fc3ad34 775
4c460b34
VZ
776 m_shouldBeJoined = FALSE;
777 }
9fc3ad34 778 }
9111db68 779
518b5d2f
VZ
780 // reacquire GUI mutex
781 if ( wxThread::IsMain() )
782 wxMutexGuiEnter();
783}
784
785void wxThreadInternal::SignalExit()
786{
9fc3ad34 787 wxLogTrace(TRACE_THREADS, _T("Thread %ld about to exit."), GetId());
518b5d2f 788
9fc3ad34 789 SetState(STATE_EXITED);
518b5d2f 790
9fc3ad34
VZ
791 // wake up all the threads waiting for our termination - if there are any
792 if ( m_shouldBroadcast )
793 {
fcc3d7cb
VZ
794 wxLogTrace(TRACE_THREADS, _T("Thread %ld signals end condition."),
795 GetId());
796
9fc3ad34
VZ
797 m_condEnd.Broadcast();
798 }
518b5d2f
VZ
799}
800
801void wxThreadInternal::Pause()
802{
882eefb1
VZ
803 // the state is set from the thread which pauses us first, this function
804 // is called later so the state should have been already set
518b5d2f 805 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 806 wxT("thread must first be paused with wxThread::Pause().") );
518b5d2f 807
9fc3ad34 808 wxLogTrace(TRACE_THREADS, _T("Thread %ld goes to sleep."), GetId());
862cc6f9 809
518b5d2f 810 // wait until the condition is signaled from Resume()
9fc3ad34 811 m_condSuspend.Wait();
518b5d2f
VZ
812}
813
814void wxThreadInternal::Resume()
815{
816 wxCHECK_RET( m_state == STATE_PAUSED,
223d09f6 817 wxT("can't resume thread which is not suspended.") );
518b5d2f 818
4c460b34
VZ
819 // the thread might be not actually paused yet - if there were no call to
820 // TestDestroy() since the last call to Pause() for example
821 if ( IsReallyPaused() )
822 {
823 wxLogTrace(TRACE_THREADS, _T("Waking up thread %ld"), GetId());
9fc3ad34 824
4c460b34
VZ
825 // wake up Pause()
826 m_condSuspend.Signal();
827
828 // reset the flag
829 SetReallyPaused(FALSE);
830 }
831 else
832 {
833 wxLogTrace(TRACE_THREADS, _T("Thread %ld is not yet really paused"),
834 GetId());
835 }
518b5d2f
VZ
836
837 SetState(STATE_RUNNING);
838}
839
840// -----------------------------------------------------------------------------
9fc3ad34 841// wxThread static functions
518b5d2f
VZ
842// -----------------------------------------------------------------------------
843
844wxThread *wxThread::This()
845{
846 return (wxThread *)pthread_getspecific(gs_keySelf);
847}
848
849bool wxThread::IsMain()
850{
851 return (bool)pthread_equal(pthread_self(), gs_tidMain);
852}
853
854void wxThread::Yield()
855{
6f837e5c 856#ifdef HAVE_SCHED_YIELD
518b5d2f 857 sched_yield();
6f837e5c 858#endif
518b5d2f
VZ
859}
860
861void wxThread::Sleep(unsigned long milliseconds)
862{
863 wxUsleep(milliseconds);
864}
865
ef8d96c2
VZ
866int wxThread::GetCPUCount()
867{
868#if defined(__LINUX__)
869 // read from proc (can't use wxTextFile here because it's a special file:
870 // it has 0 size but still can be read from)
871 wxLogNull nolog;
872
873 wxFFile file(_T("/proc/cpuinfo"));
874 if ( file.IsOpened() )
875 {
876 // slurp the whole file
877 wxString s;
878 if ( file.ReadAll(&s) )
879 {
880 // (ab)use Replace() to find the number of "processor" strings
881 size_t count = s.Replace(_T("processor"), _T(""));
882 if ( count > 0 )
883 {
884 return count;
885 }
886
887 wxLogDebug(_T("failed to parse /proc/cpuinfo"));
888 }
889 else
890 {
891 wxLogDebug(_T("failed to read /proc/cpuinfo"));
892 }
893 }
894#elif defined(_SC_NPROCESSORS_ONLN)
895 // this works for Solaris
896 int rc = sysconf(_SC_NPROCESSORS_ONLN);
897 if ( rc != -1 )
898 {
899 return rc;
900 }
901#endif // different ways to get number of CPUs
902
903 // unknown
904 return -1;
905}
906
907bool wxThread::SetConcurrency(size_t level)
908{
909#ifdef HAVE_THR_SETCONCURRENCY
910 int rc = thr_setconcurrency(level);
911 if ( rc != 0 )
912 {
913 wxLogSysError(rc, _T("thr_setconcurrency() failed"));
914 }
915
916 return rc == 0;
917#else // !HAVE_THR_SETCONCURRENCY
918 // ok only for the default value
919 return level == 0;
920#endif // HAVE_THR_SETCONCURRENCY/!HAVE_THR_SETCONCURRENCY
921}
922
518b5d2f
VZ
923// -----------------------------------------------------------------------------
924// creating thread
925// -----------------------------------------------------------------------------
926
acb8423c 927wxThread::wxThread(wxThreadKind kind)
518b5d2f
VZ
928{
929 // add this thread to the global list of all threads
930 gs_allThreads.Add(this);
931
9fc3ad34 932 m_internal = new wxThreadInternal();
acb8423c
VZ
933
934 m_isDetached = kind == wxTHREAD_DETACHED;
518b5d2f
VZ
935}
936
937wxThreadError wxThread::Create()
938{
9fc3ad34
VZ
939 if ( m_internal->GetState() != STATE_NEW )
940 {
941 // don't recreate thread
518b5d2f 942 return wxTHREAD_RUNNING;
9fc3ad34 943 }
518b5d2f
VZ
944
945 // set up the thread attribute: right now, we only set thread priority
946 pthread_attr_t attr;
947 pthread_attr_init(&attr);
948
fc9ef629 949#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
9fc3ad34
VZ
950 int policy;
951 if ( pthread_attr_getschedpolicy(&attr, &policy) != 0 )
518b5d2f 952 {
58230fb1 953 wxLogError(_("Cannot retrieve thread scheduling policy."));
518b5d2f
VZ
954 }
955
fb10f04c
JJ
956#ifdef __VMS__
957 /* the pthread.h contains too many spaces. This is a work-around */
958# undef sched_get_priority_max
959#undef sched_get_priority_min
960#define sched_get_priority_max(_pol_) \
961 (_pol_ == SCHED_OTHER ? PRI_FG_MAX_NP : PRI_FIFO_MAX)
962#define sched_get_priority_min(_pol_) \
963 (_pol_ == SCHED_OTHER ? PRI_FG_MIN_NP : PRI_FIFO_MIN)
964#endif
965
966 int max_prio = sched_get_priority_max(policy),
967 min_prio = sched_get_priority_min(policy),
9fc3ad34 968 prio = m_internal->GetPriority();
518b5d2f
VZ
969
970 if ( min_prio == -1 || max_prio == -1 )
971 {
58230fb1 972 wxLogError(_("Cannot get priority range for scheduling policy %d."),
9fc3ad34 973 policy);
518b5d2f 974 }
bbfa0322
VZ
975 else if ( max_prio == min_prio )
976 {
9fc3ad34 977 if ( prio != WXTHREAD_DEFAULT_PRIORITY )
bbfa0322
VZ
978 {
979 // notify the programmer that this doesn't work here
980 wxLogWarning(_("Thread priority setting is ignored."));
981 }
982 //else: we have default priority, so don't complain
983
984 // anyhow, don't do anything because priority is just ignored
985 }
518b5d2f
VZ
986 else
987 {
988 struct sched_param sp;
9fc3ad34
VZ
989 if ( pthread_attr_getschedparam(&attr, &sp) != 0 )
990 {
991 wxFAIL_MSG(_T("pthread_attr_getschedparam() failed"));
992 }
993
994 sp.sched_priority = min_prio + (prio*(max_prio - min_prio))/100;
995
996 if ( pthread_attr_setschedparam(&attr, &sp) != 0 )
997 {
998 wxFAIL_MSG(_T("pthread_attr_setschedparam(priority) failed"));
999 }
518b5d2f 1000 }
34f8c26e 1001#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f 1002
58230fb1
VZ
1003#ifdef HAVE_PTHREAD_ATTR_SETSCOPE
1004 // this will make the threads created by this process really concurrent
9fc3ad34
VZ
1005 if ( pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM) != 0 )
1006 {
1007 wxFAIL_MSG(_T("pthread_attr_setscope(PTHREAD_SCOPE_SYSTEM) failed"));
1008 }
58230fb1
VZ
1009#endif // HAVE_PTHREAD_ATTR_SETSCOPE
1010
9fc3ad34
VZ
1011 // VZ: assume that this one is always available (it's rather fundamental),
1012 // if this function is ever missing we should try to use
1013 // pthread_detach() instead (after thread creation)
1014 if ( m_isDetached )
1015 {
1016 if ( pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED) != 0 )
1017 {
1018 wxFAIL_MSG(_T("pthread_attr_setdetachstate(DETACHED) failed"));
1019 }
1020
1021 // never try to join detached threads
1022 m_internal->Detach();
1023 }
1024 //else: threads are created joinable by default, it's ok
1025
518b5d2f 1026 // create the new OS thread object
9fc3ad34
VZ
1027 int rc = pthread_create
1028 (
1029 m_internal->GetIdPtr(),
1030 &attr,
1031 wxThreadInternal::PthreadStart,
1032 (void *)this
1033 );
1034
1035 if ( pthread_attr_destroy(&attr) != 0 )
1036 {
1037 wxFAIL_MSG(_T("pthread_attr_destroy() failed"));
1038 }
518b5d2f
VZ
1039
1040 if ( rc != 0 )
1041 {
9fc3ad34
VZ
1042 m_internal->SetState(STATE_EXITED);
1043
518b5d2f
VZ
1044 return wxTHREAD_NO_RESOURCE;
1045 }
1046
1047 return wxTHREAD_NO_ERROR;
1048}
1049
1050wxThreadError wxThread::Run()
1051{
9fc3ad34
VZ
1052 wxCriticalSectionLocker lock(m_critsect);
1053
1054 wxCHECK_MSG( m_internal->GetId(), wxTHREAD_MISC_ERROR,
223d09f6 1055 wxT("must call wxThread::Create() first") );
bbfa0322 1056
9fc3ad34 1057 return m_internal->Run();
518b5d2f
VZ
1058}
1059
1060// -----------------------------------------------------------------------------
1061// misc accessors
1062// -----------------------------------------------------------------------------
1063
1064void wxThread::SetPriority(unsigned int prio)
1065{
34f8c26e
VZ
1066 wxCHECK_RET( ((int)WXTHREAD_MIN_PRIORITY <= (int)prio) &&
1067 ((int)prio <= (int)WXTHREAD_MAX_PRIORITY),
223d09f6 1068 wxT("invalid thread priority") );
518b5d2f
VZ
1069
1070 wxCriticalSectionLocker lock(m_critsect);
1071
9fc3ad34 1072 switch ( m_internal->GetState() )
518b5d2f
VZ
1073 {
1074 case STATE_NEW:
1075 // thread not yet started, priority will be set when it is
9fc3ad34 1076 m_internal->SetPriority(prio);
518b5d2f
VZ
1077 break;
1078
1079 case STATE_RUNNING:
1080 case STATE_PAUSED:
34f8c26e 1081#ifdef HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
1082 {
1083 struct sched_param sparam;
1084 sparam.sched_priority = prio;
1085
9fc3ad34 1086 if ( pthread_setschedparam(m_internal->GetId(),
518b5d2f
VZ
1087 SCHED_OTHER, &sparam) != 0 )
1088 {
1089 wxLogError(_("Failed to set thread priority %d."), prio);
1090 }
1091 }
34f8c26e 1092#endif // HAVE_THREAD_PRIORITY_FUNCTIONS
518b5d2f
VZ
1093 break;
1094
1095 case STATE_EXITED:
1096 default:
223d09f6 1097 wxFAIL_MSG(wxT("impossible to set thread priority in this state"));
518b5d2f
VZ
1098 }
1099}
1100
1101unsigned int wxThread::GetPriority() const
1102{
1103 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1104
9fc3ad34 1105 return m_internal->GetPriority();
518b5d2f
VZ
1106}
1107
acb8423c 1108unsigned long wxThread::GetId() const
518b5d2f 1109{
9fc3ad34 1110 return (unsigned long)m_internal->GetId();
518b5d2f
VZ
1111}
1112
1113// -----------------------------------------------------------------------------
1114// pause/resume
1115// -----------------------------------------------------------------------------
1116
1117wxThreadError wxThread::Pause()
1118{
4c460b34
VZ
1119 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1120 _T("a thread can't pause itself") );
1121
518b5d2f
VZ
1122 wxCriticalSectionLocker lock(m_critsect);
1123
9fc3ad34 1124 if ( m_internal->GetState() != STATE_RUNNING )
518b5d2f 1125 {
223d09f6 1126 wxLogDebug(wxT("Can't pause thread which is not running."));
518b5d2f
VZ
1127
1128 return wxTHREAD_NOT_RUNNING;
1129 }
1130
4c460b34
VZ
1131 wxLogTrace(TRACE_THREADS, _T("Asking thread %ld to pause."),
1132 GetId());
1133
9fc3ad34
VZ
1134 // just set a flag, the thread will be really paused only during the next
1135 // call to TestDestroy()
1136 m_internal->SetState(STATE_PAUSED);
518b5d2f
VZ
1137
1138 return wxTHREAD_NO_ERROR;
1139}
1140
1141wxThreadError wxThread::Resume()
1142{
4c460b34
VZ
1143 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1144 _T("a thread can't resume itself") );
518b5d2f 1145
4c460b34 1146 wxCriticalSectionLocker lock(m_critsect);
518b5d2f 1147
4c460b34 1148 wxThreadState state = m_internal->GetState();
9fc3ad34
VZ
1149
1150 switch ( state )
518b5d2f 1151 {
9fc3ad34 1152 case STATE_PAUSED:
4c460b34 1153 wxLogTrace(TRACE_THREADS, _T("Thread %ld suspended, resuming."),
9fc3ad34
VZ
1154 GetId());
1155
1156 m_internal->Resume();
1157
1158 return wxTHREAD_NO_ERROR;
1159
1160 case STATE_EXITED:
1161 wxLogTrace(TRACE_THREADS, _T("Thread %ld exited, won't resume."),
1162 GetId());
1163 return wxTHREAD_NO_ERROR;
518b5d2f 1164
9fc3ad34
VZ
1165 default:
1166 wxLogDebug(_T("Attempt to resume a thread which is not paused."));
1167
1168 return wxTHREAD_MISC_ERROR;
518b5d2f
VZ
1169 }
1170}
1171
1172// -----------------------------------------------------------------------------
1173// exiting thread
1174// -----------------------------------------------------------------------------
1175
9fc3ad34 1176wxThread::ExitCode wxThread::Wait()
b568d04f 1177{
9fc3ad34
VZ
1178 wxCHECK_MSG( This() != this, (ExitCode)-1,
1179 _T("a thread can't wait for itself") );
1180
1181 wxCHECK_MSG( !m_isDetached, (ExitCode)-1,
1182 _T("can't wait for detached thread") );
1183
1184 m_internal->Wait();
b568d04f 1185
9fc3ad34 1186 return m_internal->GetExitCode();
b568d04f
VZ
1187}
1188
1189wxThreadError wxThread::Delete(ExitCode *rc)
518b5d2f 1190{
4c460b34
VZ
1191 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1192 _T("a thread can't delete itself") );
1193
518b5d2f 1194 m_critsect.Enter();
9fc3ad34 1195 wxThreadState state = m_internal->GetState();
518b5d2f 1196
882eefb1 1197 // ask the thread to stop
9fc3ad34
VZ
1198 m_internal->SetCancelFlag();
1199
1200 if ( m_isDetached )
1201 {
1202 // detached threads won't broadcast about their termination by default
1203 // because usually nobody waits for them - but here we do, so ask the
1204 // thread to notify us
1205 m_internal->Notify();
1206 }
882eefb1 1207
9111db68
GL
1208 m_critsect.Leave();
1209
518b5d2f
VZ
1210 switch ( state )
1211 {
1212 case STATE_NEW:
4c460b34
VZ
1213 // we need to wake up the thread so that PthreadStart() will
1214 // terminate - right now it's blocking on m_condRun
1215 m_internal->SignalRun();
1216
1217 // fall through
1218
518b5d2f
VZ
1219 case STATE_EXITED:
1220 // nothing to do
1221 break;
1222
1223 case STATE_PAUSED:
9fc3ad34
VZ
1224 // resume the thread first (don't call our Resume() because this
1225 // would dead lock when it tries to enter m_critsect)
1226 m_internal->Resume();
518b5d2f
VZ
1227
1228 // fall through
1229
1230 default:
882eefb1 1231 // wait until the thread stops
9fc3ad34
VZ
1232 m_internal->Wait();
1233
1234 if ( rc )
1235 {
1236 wxASSERT_MSG( !m_isDetached,
1237 _T("no return code for detached threads") );
1238
1239 // if it's a joinable thread, it's not deleted yet
1240 *rc = m_internal->GetExitCode();
1241 }
518b5d2f
VZ
1242 }
1243
acb8423c 1244 return wxTHREAD_NO_ERROR;
518b5d2f
VZ
1245}
1246
1247wxThreadError wxThread::Kill()
1248{
9fc3ad34
VZ
1249 wxCHECK_MSG( This() != this, wxTHREAD_MISC_ERROR,
1250 _T("a thread can't kill itself") );
1251
1252 switch ( m_internal->GetState() )
518b5d2f
VZ
1253 {
1254 case STATE_NEW:
1255 case STATE_EXITED:
1256 return wxTHREAD_NOT_RUNNING;
1257
9fc3ad34
VZ
1258 case STATE_PAUSED:
1259 // resume the thread first
1260 Resume();
1261
1262 // fall through
1263
518b5d2f 1264 default:
9fc3ad34
VZ
1265#ifdef HAVE_PTHREAD_CANCEL
1266 if ( pthread_cancel(m_internal->GetId()) != 0 )
34f8c26e 1267#endif
518b5d2f
VZ
1268 {
1269 wxLogError(_("Failed to terminate a thread."));
1270
1271 return wxTHREAD_MISC_ERROR;
1272 }
9fc3ad34
VZ
1273
1274 if ( m_isDetached )
1275 {
1276 // if we use cleanup function, this will be done from
1277 // PthreadCleanup()
1278#if !HAVE_THREAD_CLEANUP_FUNCTIONS
1279 ScheduleThreadForDeletion();
1280
b18cfdd9
VZ
1281 // don't call OnExit() here, it can only be called in the
1282 // threads context and we're in the context of another thread
9fc3ad34
VZ
1283
1284 DeleteThread(this);
1285#endif // HAVE_THREAD_CLEANUP_FUNCTIONS
1286 }
1287 else
1288 {
1289 m_internal->SetExitCode(EXITCODE_CANCELLED);
1290 }
518b5d2f
VZ
1291
1292 return wxTHREAD_NO_ERROR;
1293 }
1294}
1295
b568d04f 1296void wxThread::Exit(ExitCode status)
518b5d2f 1297{
4c460b34
VZ
1298 wxASSERT_MSG( This() == this,
1299 _T("wxThread::Exit() can only be called in the "
1300 "context of the same thread") );
1301
9fc3ad34
VZ
1302 // from the moment we call OnExit(), the main program may terminate at any
1303 // moment, so mark this thread as being already in process of being
1304 // deleted or wxThreadModule::OnExit() will try to delete it again
1305 ScheduleThreadForDeletion();
1306
1307 // don't enter m_critsect before calling OnExit() because the user code
1308 // might deadlock if, for example, it signals a condition in OnExit() (a
1309 // common case) while the main thread calls any of functions entering
1310 // m_critsect on us (almost all of them do)
518b5d2f
VZ
1311 OnExit();
1312
9fc3ad34
VZ
1313 // now do enter it because SignalExit() will change our state
1314 m_critsect.Enter();
1315
518b5d2f
VZ
1316 // next wake up the threads waiting for us (OTOH, this function won't return
1317 // until someone waited for us!)
9fc3ad34 1318 m_internal->SignalExit();
5092b3ad 1319
9fc3ad34
VZ
1320 // leave the critical section before entering the dtor which tries to
1321 // enter it
1322 m_critsect.Leave();
2a4f27f2 1323
9fc3ad34
VZ
1324 // delete C++ thread object if this is a detached thread - user is
1325 // responsible for doing this for joinable ones
1326 if ( m_isDetached )
1327 {
1328 // FIXME I'm feeling bad about it - what if another thread function is
1329 // called (in another thread context) now? It will try to access
1330 // half destroyed object which will probably result in something
1331 // very bad - but we can't protect this by a crit section unless
1332 // we make it a global object, but this would mean that we can
1333 // only call one thread function at a time :-(
1334 DeleteThread(this);
1335 }
1336
1337 // terminate the thread (pthread_exit() never returns)
518b5d2f 1338 pthread_exit(status);
9fc3ad34
VZ
1339
1340 wxFAIL_MSG(_T("pthread_exit() failed"));
518b5d2f
VZ
1341}
1342
1343// also test whether we were paused
1344bool wxThread::TestDestroy()
1345{
4c460b34
VZ
1346 wxASSERT_MSG( This() == this,
1347 _T("wxThread::TestDestroy() can only be called in the "
1348 "context of the same thread") );
1349
9fc3ad34 1350 m_critsect.Enter();
518b5d2f 1351
9fc3ad34 1352 if ( m_internal->GetState() == STATE_PAUSED )
518b5d2f 1353 {
4c460b34
VZ
1354 m_internal->SetReallyPaused(TRUE);
1355
9fc3ad34
VZ
1356 // leave the crit section or the other threads will stop too if they
1357 // try to call any of (seemingly harmless) IsXXX() functions while we
1358 // sleep
518b5d2f
VZ
1359 m_critsect.Leave();
1360
9fc3ad34
VZ
1361 m_internal->Pause();
1362 }
1363 else
1364 {
1365 // thread wasn't requested to pause, nothing to do
1366 m_critsect.Leave();
518b5d2f
VZ
1367 }
1368
9fc3ad34 1369 return m_internal->WasCancelled();
518b5d2f
VZ
1370}
1371
1372wxThread::~wxThread()
1373{
9fc3ad34 1374#ifdef __WXDEBUG__
062c4861 1375 m_critsect.Enter();
9fc3ad34
VZ
1376
1377 // check that the thread either exited or couldn't be created
1378 if ( m_internal->GetState() != STATE_EXITED &&
1379 m_internal->GetState() != STATE_NEW )
bbfa0322 1380 {
4c460b34
VZ
1381 wxLogDebug(_T("The thread %ld is being destroyed although it is still "
1382 "running! The application may crash."), GetId());
bbfa0322 1383 }
062c4861
GL
1384
1385 m_critsect.Leave();
9fc3ad34 1386#endif // __WXDEBUG__
062c4861 1387
9fc3ad34 1388 delete m_internal;
bbfa0322 1389
518b5d2f
VZ
1390 // remove this thread from the global array
1391 gs_allThreads.Remove(this);
4c460b34
VZ
1392
1393 // detached thread will decrement this counter in DeleteThread(), but it
1394 // is not called for the joinable threads, so do it here
1395 if ( !m_isDetached )
1396 {
1397 MutexLock lock(gs_mutexDeleteThread);
1398 gs_nThreadsBeingDeleted--;
1399
1400 wxLogTrace(TRACE_THREADS, _T("%u scheduled for deletion threads left."),
1401 gs_nThreadsBeingDeleted - 1);
1402 }
518b5d2f
VZ
1403}
1404
1405// -----------------------------------------------------------------------------
1406// state tests
1407// -----------------------------------------------------------------------------
1408
1409bool wxThread::IsRunning() const
1410{
1411 wxCriticalSectionLocker lock((wxCriticalSection &)m_critsect);
1412
9fc3ad34 1413 return m_internal->GetState() == STATE_RUNNING;
518b5d2f
VZ
1414}
1415
1416bool wxThread::IsAlive() const
1417{
1418 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1419
9fc3ad34 1420 switch ( m_internal->GetState() )
518b5d2f
VZ
1421 {
1422 case STATE_RUNNING:
1423 case STATE_PAUSED:
1424 return TRUE;
1425
1426 default:
1427 return FALSE;
1428 }
1429}
1430
a737331d
GL
1431bool wxThread::IsPaused() const
1432{
1433 wxCriticalSectionLocker lock((wxCriticalSection&)m_critsect);
1434
9fc3ad34 1435 return (m_internal->GetState() == STATE_PAUSED);
a737331d
GL
1436}
1437
518b5d2f
VZ
1438//--------------------------------------------------------------------
1439// wxThreadModule
1440//--------------------------------------------------------------------
1441
1442class wxThreadModule : public wxModule
1443{
1444public:
1445 virtual bool OnInit();
1446 virtual void OnExit();
1447
1448private:
1449 DECLARE_DYNAMIC_CLASS(wxThreadModule)
1450};
1451
1452IMPLEMENT_DYNAMIC_CLASS(wxThreadModule, wxModule)
1453
1454bool wxThreadModule::OnInit()
1455{
58230fb1
VZ
1456 int rc = pthread_key_create(&gs_keySelf, NULL /* dtor function */);
1457 if ( rc != 0 )
518b5d2f 1458 {
58230fb1
VZ
1459 wxLogSysError(rc, _("Thread module initialization failed: "
1460 "failed to create thread key"));
518b5d2f
VZ
1461
1462 return FALSE;
1463 }
1464
518b5d2f 1465 gs_tidMain = pthread_self();
19da4326 1466
9fc3ad34
VZ
1467#if wxUSE_GUI
1468 gs_mutexGui = new wxMutex();
1469
518b5d2f 1470 gs_mutexGui->Lock();
9fc3ad34 1471#endif // wxUSE_GUI
518b5d2f 1472
88e243b2
VZ
1473 // under Solaris we get a warning from CC when using
1474 // PTHREAD_MUTEX_INITIALIZER, so do it dynamically
1475 pthread_mutex_init(&gs_mutexDeleteThread, NULL);
1476
518b5d2f
VZ
1477 return TRUE;
1478}
1479
1480void wxThreadModule::OnExit()
1481{
223d09f6 1482 wxASSERT_MSG( wxThread::IsMain(), wxT("only main thread can be here") );
518b5d2f 1483
9fc3ad34
VZ
1484 // are there any threads left which are being deleted right now?
1485 size_t nThreadsBeingDeleted;
1486 {
1487 MutexLock lock(gs_mutexDeleteThread);
1488 nThreadsBeingDeleted = gs_nThreadsBeingDeleted;
1489 }
1490
1491 if ( nThreadsBeingDeleted > 0 )
1492 {
1493 wxLogTrace(TRACE_THREADS, _T("Waiting for %u threads to disappear"),
1494 nThreadsBeingDeleted);
1495
1496 // have to wait until all of them disappear
1497 gs_condAllDeleted->Wait();
1498 }
1499
518b5d2f
VZ
1500 // terminate any threads left
1501 size_t count = gs_allThreads.GetCount();
1502 if ( count != 0u )
4c460b34
VZ
1503 {
1504 wxLogDebug(wxT("%u threads were not terminated by the application."),
1505 count);
1506 }
518b5d2f
VZ
1507
1508 for ( size_t n = 0u; n < count; n++ )
1509 {
bbfa0322
VZ
1510 // Delete calls the destructor which removes the current entry. We
1511 // should only delete the first one each time.
0ac77ef5 1512 gs_allThreads[0]->Delete();
518b5d2f
VZ
1513 }
1514
9fc3ad34 1515#if wxUSE_GUI
518b5d2f
VZ
1516 // destroy GUI mutex
1517 gs_mutexGui->Unlock();
1518
518b5d2f 1519 delete gs_mutexGui;
9fc3ad34 1520#endif // wxUSE_GUI
518b5d2f
VZ
1521
1522 // and free TLD slot
1523 (void)pthread_key_delete(gs_keySelf);
1524}
1525
1526// ----------------------------------------------------------------------------
1527// global functions
1528// ----------------------------------------------------------------------------
1529
9fc3ad34
VZ
1530static void ScheduleThreadForDeletion()
1531{
1532 MutexLock lock(gs_mutexDeleteThread);
1533
1534 if ( gs_nThreadsBeingDeleted == 0 )
1535 {
1536 gs_condAllDeleted = new wxCondition;
1537 }
1538
1539 gs_nThreadsBeingDeleted++;
1540
fcc3d7cb
VZ
1541 wxLogTrace(TRACE_THREADS, _T("%u thread%s waiting to be deleted"),
1542 gs_nThreadsBeingDeleted,
1543 gs_nThreadsBeingDeleted == 1 ? "" : "s");
9fc3ad34
VZ
1544}
1545
1546static void DeleteThread(wxThread *This)
1547{
1548 // gs_mutexDeleteThread should be unlocked before signalling the condition
1549 // or wxThreadModule::OnExit() would deadlock
1550 {
1551 MutexLock lock(gs_mutexDeleteThread);
1552
1553 wxLogTrace(TRACE_THREADS, _T("Thread %ld auto deletes."), This->GetId());
1554
1555 delete This;
1556
1557 wxCHECK_RET( gs_nThreadsBeingDeleted > 0,
1558 _T("no threads scheduled for deletion, yet we delete "
1559 "one?") );
1560 }
1561
4c460b34
VZ
1562 wxLogTrace(TRACE_THREADS, _T("%u scheduled for deletion threads left."),
1563 gs_nThreadsBeingDeleted - 1);
1564
9fc3ad34
VZ
1565 if ( !--gs_nThreadsBeingDeleted )
1566 {
1567 // no more threads left, signal it
1568 gs_condAllDeleted->Signal();
1569
1570 delete gs_condAllDeleted;
1571 gs_condAllDeleted = (wxCondition *)NULL;
1572 }
1573}
1574
518b5d2f
VZ
1575void wxMutexGuiEnter()
1576{
9fc3ad34
VZ
1577#if wxUSE_GUI
1578 gs_mutexGui->Lock();
1579#endif // wxUSE_GUI
518b5d2f
VZ
1580}
1581
1582void wxMutexGuiLeave()
1583{
9fc3ad34
VZ
1584#if wxUSE_GUI
1585 gs_mutexGui->Unlock();
1586#endif // wxUSE_GUI
518b5d2f 1587}
80cb83be 1588
7bcb11d3
JS
1589#endif
1590 // wxUSE_THREADS