18e778f39b624f62fe4bcf8cea8f770d692b292c
[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         a_fetch_add(&m->_m_waiters, c->_c_waiters2);
26         c->_c_waiters2 = 0;
27
28         /* Perform the futex requeue, waking one waiter unless we know
29          * that the calling thread holds the mutex. */
30         int wake_cnt = !(m->_m_type & 3)
31                 || (m->_m_lock&INT_MAX)!=__pthread_self()->tid;
32         if (m->_m_type & 128) wake_cnt = INT_MAX;
33         __syscall(SYS_futex, &c->_c_seq, FUTEX_REQUEUE | 128,
34                 wake_cnt, INT_MAX, &m->_m_lock) != -EINVAL ||
35         __syscall(SYS_futex, &c->_c_seq, FUTEX_REQUEUE,
36                 wake_cnt, 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, 1);
41
42         return 0;
43 }