Search code examples
c++cpthreadscondition-variable

order of calling pthread_cond_signal and change condition variable


I know that pthread_cond_signal/pthread_cond_broadcast should be called after changing the condition variable to indicate a condition change, but if they both happen with lock held, does the order matter? For example

  1. pthread_mutex_lock(&mutex);
  2. pthread_cond_signal(&cond);
  3. condition = true
  4. pthread_mutex_unlock(&mutex);

the waiter's wakeup must happen after step 4(to retrieve the mutex), so the waiter must have seen the update condition variaable


Solution

  • I think you are right. If the code checking this condition is written in a correct way, this should not be a problem.

    e.g.

    pthread_mutex_lock(&lock);
    while(!state)
    {
        pthread_cond_wait(&cond, &lock);
    }
    pthread_mutex_unlock(&lock);