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