9c6a462b781bd5bb6435df47f6890c02c41b2f4a
[musl] / src / thread / pthread_cond_broadcast.c
1 #include "pthread_impl.h"
2
3 int pthread_cond_broadcast(pthread_cond_t *c)
4 {
5         pthread_mutex_t *m;
6
7         if (!c->_c_waiters) return 0;
8
9         a_inc(&c->_c_seq);
10
11         /* If cond var is process-shared, simply wake all waiters. */
12         if (c->_c_mutex == (void *)-1) {
13                 __wake(&c->_c_seq, -1, 0);
14                 return 0;
15         }
16
17         /* Block waiters from returning so we can use the mutex. */
18         while (a_swap(&c->_c_lock, 1))
19                 __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
20         if (!c->_c_waiters)
21                 goto out;
22         m = c->_c_mutex;
23
24         /* Move waiter count to the mutex */
25         for (;;) {
26                 int w = c->_c_waiters2;
27                 a_fetch_add(&m->_m_waiters, w);
28                 if (a_cas(&c->_c_waiters2, w, 0) == w) break;
29                 a_fetch_add(&m->_m_waiters, -w);
30         }
31
32         /* Perform the futex requeue, waking one waiter unless we know
33          * that the calling thread holds the mutex. */
34         __syscall(SYS_futex, &c->_c_seq, FUTEX_REQUEUE,
35                 !m->_m_type || (m->_m_lock&INT_MAX)!=pthread_self()->tid,
36                 INT_MAX, &m->_m_lock);
37
38 out:
39         a_store(&c->_c_lock, 0);
40         if (c->_c_lockwait) __wake(&c->_c_lock, 1, 0);
41
42         return 0;
43 }