sem_timedwait.c 515 B

12345678910111213141516171819202122232425262728
  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 *sem, const struct timespec *at)
  8. {
  9. while (sem_trywait(sem)) {
  10. int r;
  11. if (at && at->tv_nsec >= 1000000000UL) {
  12. errno = EINVAL;
  13. return -1;
  14. }
  15. a_inc(sem->__val+1);
  16. a_cas(sem->__val, 0, -1);
  17. pthread_cleanup_push(cleanup, sem->__val+1);
  18. r = __timedwait_cp(sem->__val, -1, CLOCK_REALTIME, at, 0);
  19. pthread_cleanup_pop(1);
  20. if (r) {
  21. errno = r;
  22. return -1;
  23. }
  24. }
  25. return 0;
  26. }