1d4b3e2c161534d33189f59b58743851013abfb9
[musl] / src / thread / sem_timedwait.c
1 #include <semaphore.h>
2 #include "pthread_impl.h"
3
4 static void cleanup(void *p)
5 {
6         a_dec(p);
7 }
8
9 int sem_timedwait(sem_t *sem, const struct timespec *at)
10 {
11         while (sem_trywait(sem)) {
12                 int r;
13                 if (at && at->tv_nsec >= 1000000000UL) {
14                         errno = EINVAL;
15                         return -1;
16                 }
17                 a_inc(sem->__val+1);
18                 a_cas(sem->__val, 0, -1);
19                 pthread_cleanup_push(cleanup, sem->__val+1);
20                 r = __timedwait_cp(sem->__val, -1, CLOCK_REALTIME, at, 0);
21                 pthread_cleanup_pop(1);
22                 if (r) {
23                         errno = r;
24                         return -1;
25                 }
26         }
27         return 0;
28 }