Alex Rivera | Logout

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

Asked 2011-10-14T10:03:01.247
25

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 here. Wouldn't pthread_cond_wait just wait until the signalling thread signals cam_video_cond? OK, I know you might have a case where cam->status is not equal to WAIT_DISPAY when pthread_cond_wait is called, but in that case you could just check it through an if condition rather than using while.

Am I missing something here? My understanding of pthread_cond_wait is that it just waits for infinite if cam_video_cond is not signalled. Moreover, it unlocks the cam_video_lock mutex when called, but when the condition is signalled, before returning, it relocks cam_video_lock. Am I right?

Edit
Report

1 Answer

4

For performance reasons, the POSIX API allows the OS to wake up your thread even if the condition has not been fulfilled (that's called a spurious wakeup).

answered 2011-10-14T10:22:24.930

Your Answer