fix lost signals in cond vars
[musl] / src / thread / pthread_cond_timedwait.c
1 #include "pthread_impl.h"
2
3 struct cm {
4         pthread_cond_t *c;
5         pthread_mutex_t *m;
6 };
7
8 static void unwait(pthread_cond_t *c, pthread_mutex_t *m)
9 {
10         int w;
11
12         /* Removing a waiter is non-trivial if we could be using requeue
13          * based broadcast signals, due to mutex access issues, etc. */
14
15         if (c->_c_mutex == (void *)-1) {
16                 a_dec(&c->_c_waiters);
17                 return;
18         }
19
20         while (a_swap(&c->_c_lock, 1))
21                 __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
22
23         /* Atomically decrement waiters2 if positive, else mutex waiters. */
24         do w = c->_c_waiters2;
25         while (w && a_cas(&c->_c_waiters2, w, w-1)!=w);
26         if (!w) a_dec(&m->_m_waiters);
27
28         a_store(&c->_c_lock, 0);
29         if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
30 }
31
32 static void cleanup(void *p)
33 {
34         struct cm *cm = p;
35         unwait(cm->c, cm->m);
36         pthread_mutex_lock(cm->m);
37 }
38
39 int pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, const struct timespec *ts)
40 {
41         struct cm cm = { .c=c, .m=m };
42         int r, e=0, seq;
43
44         if (ts && ts->tv_nsec >= 1000000000UL)
45                 return EINVAL;
46
47         pthread_testcancel();
48
49         if (c->_c_mutex != (void *)-1) c->_c_mutex = m;
50
51         a_inc(&c->_c_waiters);
52         a_inc(&c->_c_waiters2);
53
54         seq = c->_c_seq;
55
56         if ((r=pthread_mutex_unlock(m))) return r;
57
58         do e = __timedwait(&c->_c_seq, seq, c->_c_clock, ts, cleanup, &cm, 0);
59         while (c->_c_seq == seq && (!e || e==EINTR));
60         if (e == EINTR) e = 0;
61
62         unwait(c, m);
63
64         if ((r=pthread_mutex_lock(m))) return r;
65
66         return e;
67 }