]> git.mxchange.org Git - simgear.git/blob - simgear/threads/SGThread.cxx
Cosmetic changes for new code moved into simgear to make the naming scheme
[simgear.git] / simgear / threads / SGThread.cxx
1 #include <simgear/compiler.h>
2
3 #if defined(_MSC_VER) || defined(__MINGW32__)
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 #if defined(_MSC_VER) || defined(__MINGW32__)
53 int gettimeofday(struct timeval* tp, void* tzp) {
54     LARGE_INTEGER t;
55
56     if(QueryPerformanceCounter(&t)) {
57         /* hardware supports a performance counter */
58         LARGE_INTEGER f;
59         QueryPerformanceFrequency(&f);
60         tp->tv_sec = t.QuadPart/f.QuadPart;
61         tp->tv_usec = ((float)t.QuadPart/f.QuadPart*1000*1000)
62             - (tp->tv_sec*1000*1000);
63     } else {
64         /* hardware doesn't support a performance counter, so get the
65            time in a more traditional way. */
66         DWORD t;
67         t = timeGetTime();
68         tp->tv_sec = t / 1000;
69         tp->tv_usec = t % 1000;
70     }
71
72     /* 0 indicates that the call succeeded. */
73     return 0;
74 }
75 #endif
76
77 bool
78 SGPthreadCond::wait( SGMutex& mutex, unsigned long ms )
79 {
80     struct timeval now;
81     ::gettimeofday( &now, 0 );
82
83     // Wait time is now + ms milliseconds
84     unsigned int sec = ms / 1000;
85     unsigned int nsec = (ms % 1000) * 1000;
86     struct timespec abstime;
87     abstime.tv_sec = now.tv_sec + sec;
88     abstime.tv_nsec = now.tv_usec*1000 + nsec;
89
90     int status = pthread_cond_timedwait( &cond, &mutex.mutex, &abstime );
91     if (status == ETIMEDOUT)
92     {
93         return false;
94     }
95
96     assert( status == 0 );
97     return true;
98 }
99