b5a60addb0aa7fc398f7a9d7ea93f504d4da16ee
[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 *restrict sem, const struct timespec *restrict at)
10 {
11         if (!sem_trywait(sem)) return 0;
12
13         int spins = 100;
14         while (spins-- && sem->__val[0] <= 0 && !sem->__val[1]) a_spin();
15
16         while (sem_trywait(sem)) {
17                 int r;
18                 a_inc(sem->__val+1);
19                 a_cas(sem->__val, 0, -1);
20                 r = __timedwait(sem->__val, -1, CLOCK_REALTIME, at, cleanup, sem->__val+1, sem->__val[2]);
21                 a_dec(sem->__val+1);
22                 if (r) {
23                         errno = r;
24                         return -1;
25                 }
26         }
27         return 0;
28 }