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