4f45c17211bcd1d4da1142c73da44b10e4a7b518
[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         int r;
12
13         if (a_fetch_add(sem->__val, -1) > 0) return 0;
14         a_inc(sem->__val);
15
16         if (at && at->tv_nsec >= 1000000000UL) {
17                 errno = EINVAL;
18                 return -1;
19         }
20
21         a_inc(sem->__val+1);
22         pthread_cleanup_push(cleanup, sem->__val+1)
23
24         CANCELPT_BEGIN;
25         for (;;) {
26                 r = 0;
27                 if (!sem_trywait(sem)) break;
28                 r = __timedwait(sem->__val, 0, CLOCK_REALTIME, at, 0);
29                 if (r) {
30                         errno = r;
31                         r = -1;
32                         break;
33                 }
34                 CANCELPT_TRY;
35         }
36         CANCELPT_END;
37
38         pthread_cleanup_pop(1);
39
40         return r;
41 }