fix some semaphore wait semantics (race condition deadlock and error checking)
[musl] / src / thread / sem_trywait.c
1 #include <semaphore.h>
2 #include "pthread_impl.h"
3
4 int sem_trywait(sem_t *sem)
5 {
6         int val = a_fetch_add(sem->__val, -1);
7         if (val > 0) return 0;
8         if (!a_fetch_add(sem->__val, 1))
9                 __wake(sem->__val, 1, 0);
10         errno = EAGAIN;
11         return -1;
12 }