2

The typical pattern I've seen for using pthread_cond_wait is:

pthread_mutex_lock(&lock);
  while (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);

Why can't an if statement be used instead of a while loop.

pthread_mutex_lock(&lock);
  if (!test)
    pthread_cond_wait(&condition, &lock);
pthread_mutex_unlock(&lock);

3 Answers 3

9

http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_cond_timedwait.html

When using condition variables there is always a Boolean predicate involving shared variables associated with each condition wait that is true if the thread should proceed. Spurious wakeups from the pthread_cond_timedwait() or pthread_cond_wait() functions may occur. Since the return from pthread_cond_timedwait() or pthread_cond_wait() does not imply anything about the value of this predicate, the predicate should be re-evaluated upon such return.

The while loop is a very standard way of re-evaluating the predicate, as required by POSIX.

Sign up to request clarification or add additional context in comments.

Comments

1

The if is possible but rarely used. You just would have to be sure that the state of your application is as you come out of the wait. Usually you would have to ensure that you'd only use pthread_cond_signal at the other end (and not broadcast), e.g.

1 Comment

As per R's answer, spurious wakeups are allowed, which means an if is not guaranteed safe irrespective of using signal over broadcast.
1

There are two reasons. One is spurious wakeups, as mentioned in other answers. The other is real wakeups. Imagine this:

You have two threads, A and B, blocked on the same condition variable that protects a queue, the queue is empty. Some thread puts a job on the queue, waking thread A. Another thread puts a job on the queue, waking thread B. Thread A starts running first, and does the first job. It gets back to the if and sees that the condition is still true (since there's a second job), so it does that job too. Now thread B gets the processor, returning from pthread_cond_wait, but the predicate is not false, since the queue is empty.

You only know that the predicate was true when some other thread asked that you be woken up. You have no way to know that it will still be true when you finally do get scheduled and are able to re-acquire the mutex.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.