Why do you need a while loop waiting for a condition variable

Say you have this code

pthread_mutex_lock(&cam->video_lock); while(cam->status == WAIT_DISPLAY) // <-- Why is this a 'while' and not an 'if'? pthread_cond_wait(&cam->video_cond, &cam->video_lock); pthread_mutex_unlock(&cam->video_lock); 

My question is: why do you need a while loop. Would pthread_cond_wait just wait for the signal thread to report cam_video_cond ? Well, I know that you might have a case where cam-> status is not equal to WAIT_DISPAY when pthread_cond_wait is called, but in this case you can just check it using the if condition, and not using , but .

Am I missing something? My understanding of pthread_cond_wait is that it just waits for the infinite if cam_video_cond is not signaled. In addition, it unlocks the cam_video_lock mutex when called, but when the condition is signaled, it blocks cam_video_lock before returning. I'm right?

+8
c linux pthreads signals
source share
3 answers

It is recommended that all threads check the state after returning from pthread_cond_wait , because there are several reasons for the condition to be incorrect. One of these causes is false awakening; that is, the thread may wake up, although the thread did not signal a state.

Source: Slave Awakening

+17
source share

Fake awakenings are one of the reasons, but legitimate, but extraneous awakenings are others.

Consider:

  • You queue a job.

  • You signal a condition variable by waking flow A.

  • You queue a job.

  • You signal a condition variable by waking flow B.

  • Theme A gets planned, performs the first task.

  • Thread A finds the queue nonempty and performs the second task.

  • Thread B gets scheduled as it wakes up, but discovers that the queue is still empty.

+9
source share

For performance reasons, the POSIX API allows the OS to wake your thread, even if the condition is not met (this is called a false awakening ).

+2
source share

All Articles