sem_timedwait.c 423 B

1234567891011121314151617181920212223
  1. #include <semaphore.h>
  2. #include "pthread_impl.h"
  3. static void cleanup(void *p)
  4. {
  5. a_dec(p);
  6. }
  7. int sem_timedwait(sem_t *restrict sem, const struct timespec *restrict at)
  8. {
  9. while (sem_trywait(sem)) {
  10. int r;
  11. a_inc(sem->__val+1);
  12. a_cas(sem->__val, 0, -1);
  13. r = __timedwait(sem->__val, -1, CLOCK_REALTIME, at, cleanup, sem->__val+1, 0);
  14. a_dec(sem->__val+1);
  15. if (r) {
  16. errno = r;
  17. return -1;
  18. }
  19. }
  20. return 0;
  21. }