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