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