another cond var fix: requeue count race condition
[musl] / src / thread / pthread_cond_timedwait.c
index e3dc814..db2744b 100644 (file)
@@ -7,8 +7,6 @@ struct cm {
 
 static void unwait(pthread_cond_t *c, pthread_mutex_t *m)
 {
-       int w;
-
        /* Removing a waiter is non-trivial if we could be using requeue
         * based broadcast signals, due to mutex access issues, etc. */
 
@@ -20,10 +18,8 @@ static void unwait(pthread_cond_t *c, pthread_mutex_t *m)
        while (a_swap(&c->_c_lock, 1))
                __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
 
-       /* Atomically decrement waiters2 if positive, else mutex waiters. */
-       do w = c->_c_waiters2;
-       while (w && a_cas(&c->_c_waiters2, w, w-1)!=w);
-       if (!w) a_dec(&m->_m_waiters);
+       if (c->_c_waiters2) c->_c_waiters2--;
+       else a_dec(&m->_m_waiters);
 
        a_store(&c->_c_lock, 0);
        if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
@@ -46,10 +42,16 @@ int pthread_cond_timedwait(pthread_cond_t *c, pthread_mutex_t *m, const struct t
 
        pthread_testcancel();
 
-       if (c->_c_mutex != (void *)-1) c->_c_mutex = m;
-
        a_inc(&c->_c_waiters);
-       a_inc(&c->_c_waiters2);
+
+       if (c->_c_mutex != (void *)-1) {
+               c->_c_mutex = m;
+               while (a_swap(&c->_c_lock, 1))
+                       __wait(&c->_c_lock, &c->_c_lockwait, 1, 1);
+               c->_c_waiters2++;
+               a_store(&c->_c_lock, 0);
+               if (c->_c_lockwait) __wake(&c->_c_lock, 1, 1);
+       }
 
        seq = c->_c_seq;