0

I found this on SO here:

void mrevent_wait(struct mrevent *ev) {
    pthread_mutex_lock(&ev->mutex);
    while (!ev->triggered)
         pthread_cond_wait(&ev->cond, &ev->mutex);
    pthread_mutex_unlock(&ev->mutex);
}

The manpage sais:

The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result.

These functions atomically release mutex and cause the calling thread to block on the condition variable cond;

Then shouldn't the mutex be captured before each call to pthread_cond_wait. Also, why is the mutex unlocked when the manpage sais that pthread_cond_wait do that for you.

Community
  • 1
  • 1
user877329
  • 6,717
  • 8
  • 46
  • 88

1 Answers1

0

You're reading the documentation slightly wrong. What it is saying is that, within the call to pthread_cond_wait(), the mutex is unlocked (which is required, or otherwise the pthread_cond_signal() or pthread_cond_broadcast() would never be able to trigger the condition variable). After the condition variable has been triggered, the mutex will be re-locked before pthread_cond_wait() returns. That is the reason that you must then unlock it again.

Because pthread_cond_wait() needs to re-acquire the mutex before returning to you, there is the possibility that a different thread may get the mutex first, which means that by the time pthread_cond_wait() returns to you, the condition you are waiting on may have already passed, which is why you must test the condition in the while loop.

twalberg
  • 59,951
  • 11
  • 89
  • 84