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

后端 未结 3 1637
囚心锁ツ
囚心锁ツ 2020-12-13 02:37

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\'         


        
相关标签:
3条回答
  • 2020-12-13 03:15

    It is recommended that all threads check the condition after returning from pthread_cond_wait because there are several reasons the condition might not be true. One of these reasons is a spurious wakeup; that is, a thread might get woken up even though no thread signalled the condition.

    Source : Spurious wakeup

    0 讨论(0)
  • 2020-12-13 03:16

    Spurious wakeups are one reason, but legitimate but extraneous wakeups are another.

    Consider:

    1. You put a job on a queue.

    2. You signal the condition variable, waking thread A.

    3. You put a job on a queue.

    4. You signal the condition variable, waking thread B.

    5. Thread A gets scheduled, does the first job.

    6. Thread A finds the queue non-empty and does the second job.

    7. Thread B gets scheduled, having been woken, but finds the queue still empty.

    0 讨论(0)
  • 2020-12-13 03:34

    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).

    0 讨论(0)
提交回复
热议问题