minor locking optimizations
[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         for (;;) {
25                 r = 0;
26                 if (!sem_trywait(sem)) break;
27                 r = __timedwait_cp(sem->__val, 0, CLOCK_REALTIME, at, 0);
28                 if (r) {
29                         errno = r;
30                         r = -1;
31                         break;
32                 }
33         }
34
35         pthread_cleanup_pop(1);
36
37         return r;
38 }