| 1 | #include "cor_platform.h" |
| 2 | #include <assert.h> |
| 3 | #include "timespec_utils.h" |
| 4 | |
| 5 | void _Cor_Mutex_ctor(_Cor_Mutex *mut){ |
| 6 | int r; |
| 7 | r = pthread_mutex_init(&mut->mut, NULL); |
| 8 | assert(r == 0); |
| 9 | } |
| 10 | |
| 11 | |
| 12 | void _Cor_Mutex_dtor(_Cor_Mutex *mut){ |
| 13 | int r; |
| 14 | r = pthread_mutex_destroy(&mut->mut); |
| 15 | assert(r == 0); |
| 16 | } |
| 17 | |
| 18 | |
| 19 | void _Cor_Mutex_Lock(_Cor_Mutex *mut){ |
| 20 | int r; |
| 21 | r = pthread_mutex_lock(&mut->mut); |
| 22 | assert(r == 0); |
| 23 | } |
| 24 | |
| 25 | |
| 26 | void _Cor_Mutex_Unlock(_Cor_Mutex *mut){ |
| 27 | int r; |
| 28 | r = pthread_mutex_unlock(&mut->mut); |
| 29 | assert(r == 0); |
| 30 | } |
| 31 | |
| 32 | |
| 33 | int64_t _Cor_Realtime_Now(){ |
| 34 | int r; |
| 35 | struct timespec now; |
| 36 | r = clock_gettime(CLOCK_REALTIME, &now); |
| 37 | assert(r == 0); |
| 38 | return int64_ns_from_timespec(now); |
| 39 | } |
| 40 | |
| 41 | |
| 42 | void _Cor_Semaphore_ctor(_Cor_Semaphore *sem){ |
| 43 | int r; |
| 44 | r = pthread_mutex_init(&sem->mut, NULL); |
| 45 | assert(r == 0); |
| 46 | r = pthread_cond_init(&sem->cond, NULL); |
| 47 | assert(r == 0); |
| 48 | sem->count = 0; |
| 49 | } |
| 50 | |
| 51 | |
| 52 | void _Cor_Sempahore_dtor(_Cor_Semaphore *sem){ |
| 53 | int r; |
| 54 | r = pthread_cond_destroy(&sem->cond); |
| 55 | assert(r == 0); |
| 56 | r = pthread_mutex_destroy(&sem->mut); |
| 57 | assert(r == 0); |
| 58 | } |
| 59 | |
| 60 | |
| 61 | // timeout_when < 0 means 'wait forever' |
| 62 | // Returns true for success, false for timeout |
| 63 | bool _Cor_Semaphore_Wait(_Cor_Semaphore *sem, int64_t timeout_when){ |
| 64 | int r; |
| 65 | r = pthread_mutex_lock(&sem->mut); |
| 66 | assert(r == 0); |
| 67 | if (sem->count == 0) { |
| 68 | if (timeout_when >= 0) { |
| 69 | struct timespec ts = timespec_from_int64_ns(timeout_when); |
| 70 | r = pthread_cond_timedwait(&sem->cond, &sem->mut, &ts); |
| 71 | } |
| 72 | else { |
| 73 | r = pthread_cond_wait(&sem->cond, &sem->mut); |
| 74 | } |
| 75 | } |
| 76 | assert(r == 0 || r == ETIMEDOUT); |
| 77 | bool res; |
| 78 | if (sem->count > 0) { |
| 79 | sem->count--; |
| 80 | res = true; |
| 81 | } else { |
| 82 | res = false; |
| 83 | } |
| 84 | r = pthread_mutex_unlock(&sem->mut); |
| 85 | assert(r == 0); |
| 86 | |
| 87 | return res; |
| 88 | } |
| 89 | |
| 90 | |
| 91 | void _Cor_Semaphore_Signal(_Cor_Semaphore *sem){ |
| 92 | int r; |
| 93 | r = pthread_mutex_lock(&sem->mut); |
| 94 | assert(r == 0); |
| 95 | sem->count++; |
| 96 | r = pthread_cond_signal(&sem->cond); |
| 97 | assert(r == 0); |
| 98 | r = pthread_mutex_unlock(&sem->mut); |
| 99 | assert(r == 0); |
| 100 | } |
| 101 | |