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