MMMMMCK
MMMMMCK

Reputation: 337

Pthreads: The Logic Behind Using While Loops for pthread_cond_wait

I'm having some trouble wrapping my head around why a while loop is used for pthread_cond_wait. Let's take a simple example. Here's some worker thread:

pthread_mutex_lock (&loadingLock);
while (isReadyToLoad == false){
    pthread_cond_wait(&readyCondition, &loadingLock);
} 
pthread_mutex_unlock (&loadingLock);

So, now the master thread does two things:

  1. Sets isReadyToLoad to true
  2. pthread_cond_signal(&readyCondition);

This is how I typically see the framework of pthreads laid out in examples. My question is how the while loop is valid at all. When I try and trace the logic, I get the following steps:

  1. Master sets isReadyToLoad to true
  2. X is no longer true for while(x) in the worker thread
  3. The while loop therefore is broken out of, meaning that pthread_cond_wait(&readyCondition, &loadingLock) is bypassed and will never receive the signal

Clearly my logic is flawed somewhere along the way, but I'm not sure how I should be thinking about this instead, and would appreciate any clarification.

Upvotes: 3

Views: 4820

Answers (1)

ctring
ctring

Reputation: 106

pthread_cond_wait is there so that the worker thread will drop the loadingLock lock and go to sleep when the condition isReadyToLoad == true is not yet satisfied. Therefore, if the condition is already satisfied before the worker thread reaches the while loop then there is no need to enter the while loop and run pthread_cond_wait at all.

Remember that you're in a multi-threaded environment, meaning the order of what happens can vary in an unpredictable way. One possible scenario could be that the worker thread reaches the while loop before the master thread could set isReadyToLoad to true. As a result, the worker has to call pthread_cond_wait and wait until the master actually sets isReadyToLoad to true and calls pthread_cond_signal to wake the worker up.

Like Jesper Juhl said, spurious wakeup may sometimes happen without any reason. In this case, the worker wakes up, sees that the condition is still not satisfied, and goes back to sleep again.

Upvotes: 4

Related Questions