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