another cond var fix: requeue count race condition
[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         __syscall(SYS_futex, &c->_c_seq, FUTEX_REQUEUE,
31                 !m->_m_type || (m->_m_lock&INT_MAX)!=pthread_self()->tid,
32                 INT_MAX, &m->_m_lock);
33
34 out:
35         a_store(&c->_c_lock, 0);
36         if (c->_c_lockwait) __wake(&c->_c_lock, 1, 0);
37
38         return 0;
39 }