1d0f578cc2a89cee9f13b8708605fda52c7d3f35
[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         /* Removing a waiter is non-trivial if we could be using requeue
11          * based broadcast signals, due to mutex access issues, etc. */
12
13         if (c->_c_mutex == (void *)-1) {
14                 a_dec(&c->_c_waiters);
15                 if (c->_c_destroy) __wake(&c->_c_waiters, 1, 0);
16                 return;
17         }
18
19         while (a_swap(&c->_c_lock, 1))
20                 __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
21
22         if (c->_c_waiters2) c->_c_waiters2--;
23         else a_dec(&m->_m_waiters);
24
25         a_store(&c->_c_lock, 0);
26         if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
27
28         a_dec(&c->_c_waiters);
29         if (c->_c_destroy) __wake(&c->_c_waiters, 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 (m->_m_type && (m->_m_lock&INT_MAX) != pthread_self()->tid)
45                 return EPERM;
46
47         if (ts && ts->tv_nsec >= 1000000000UL)
48                 return EINVAL;
49
50         pthread_testcancel();
51
52         a_inc(&c->_c_waiters);
53
54         if (c->_c_mutex != (void *)-1) {
55                 c->_c_mutex = m;
56                 while (a_swap(&c->_c_lock, 1))
57                         __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
58                 c->_c_waiters2++;
59                 a_store(&c->_c_lock, 0);
60                 if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
61         }
62
63         seq = c->_c_seq;
64
65         pthread_mutex_unlock(m);
66
67         do e = __timedwait(&c->_c_seq, seq, c->_c_clock, ts, cleanup, &cm, 0);
68         while (c->_c_seq == seq && (!e || e==EINTR));
69         if (e == EINTR) e = 0;
70
71         unwait(c, m);
72
73         if ((r=pthread_mutex_lock(m))) return r;
74
75         return e;
76 }