pthread_cond_timedwait.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #include "pthread_impl.h"
  2. struct cm {
  3. pthread_cond_t *c;
  4. pthread_mutex_t *m;
  5. };
  6. static void unwait(pthread_cond_t *c, pthread_mutex_t *m)
  7. {
  8. int w;
  9. /* Cannot leave waiting status if there are any live broadcasters
  10. * which might be inspecting/using the mutex. */
  11. while ((w=c->_c_bcast)) __wait(&c->_c_bcast, &c->_c_leavers, w, 0);
  12. /* If the waiter count is zero, it must be the case that the
  13. * caller's count has been moved to the mutex due to bcast. */
  14. do w = c->_c_waiters;
  15. while (w && a_cas(&c->_c_waiters, w, w-1)!=w);
  16. if (!w) a_dec(&m->_m_waiters);
  17. }
  18. static void cleanup(void *p)
  19. {
  20. struct cm *cm = p;
  21. unwait(cm->c, cm->m);
  22. pthread_mutex_lock(cm->m);
  23. }
  24. int pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, const struct timespec *ts)
  25. {
  26. struct cm cm = { .c=c, .m=m };
  27. int r, e, tid;
  28. if (ts && ts->tv_nsec >= 1000000000UL)
  29. return EINVAL;
  30. pthread_testcancel();
  31. if (c->_c_mutex != (void *)-1) c->_c_mutex = m;
  32. a_inc(&c->_c_waiters);
  33. c->_c_block = tid = pthread_self()->tid;
  34. if ((r=pthread_mutex_unlock(m))) return r;
  35. do e = __timedwait(&c->_c_block, tid, c->_c_clock, ts, cleanup, &cm, 0);
  36. while (c->_c_block == tid && (!e || e==EINTR));
  37. if (e == EINTR) e = 0;
  38. unwait(c, m);
  39. if ((r=pthread_mutex_lock(m))) return r;
  40. pthread_testcancel();
  41. return e;
  42. }