]> git.mxchange.org Git - simgear.git/blob - simgear/threads/SGThread.cxx
Expanded doxygen comments and added the SGThread::set_cancel() function.
[simgear.git] / simgear / threads / SGThread.cxx
1 #ifdef HAVE_CONFIG_H
2 #  include <config.h>
3 #endif
4
5 #include <simgear/compiler.h>
6 #include <sys/time.h>
7
8 #include "SGThread.hxx"
9
10 void*
11 start_handler( void* arg )
12 {
13     SGThread* thr = static_cast<SGThread*>(arg);
14     thr->run();
15     return 0;
16 }
17
18 void
19 SGThread::set_cancel( cancel_t mode )
20 {
21     switch (mode)
22     {
23     case CANCEL_DISABLE:
24         pthread_setcancelstate( PTHREAD_CANCEL_DISABLE, 0 );
25         break;
26     case CANCEL_DEFERRED:
27         pthread_setcanceltype( PTHREAD_CANCEL_DEFERRED, 0 );
28         pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, 0 );
29         break;
30     case CANCEL_IMMEDIATE:
31         pthread_setcanceltype( PTHREAD_CANCEL_ASYNCHRONOUS, 0 );
32         pthread_setcancelstate( PTHREAD_CANCEL_ENABLE, 0 );
33         break;
34     default:
35         break;
36     }
37 }
38
39 bool
40 SGMutex::trylock()
41 {
42     int status = pthread_mutex_lock( &mutex );
43     if (status == EBUSY)
44     {
45         return false;
46     }
47     assert( status == 0 );
48     return true;
49 }
50
51 bool
52 SGCondition::wait( SGMutex& mutex, unsigned long ms )
53 {
54     struct timeval now;
55     ::gettimeofday( &now, 0 );
56
57     // Wait time is now + ms milliseconds
58     unsigned int sec = ms / 1000;
59     unsigned int nsec = (ms % 1000) * 1000;
60     struct timespec abstime;
61     abstime.tv_sec = now.tv_sec + sec;
62     abstime.tv_nsec = now.tv_usec*1000 + nsec;
63
64     int status = pthread_cond_timedwait( &cond, &mutex.mutex, &abstime );
65     if (status == ETIMEDOUT)
66     {
67         return false;
68     }
69
70     assert( status == 0 );
71     return true;
72 }
73