Mutex status after spurious wakeup

后端 未结 1 1517
心在旅途
心在旅途 2021-01-23 05:51

Consider this basic multithreading program using pthreads. We have a main thread, creating another thread that does some work.

bool done = false;
mutex m; 
condi         


        
相关标签:
1条回答
  • 2021-01-23 06:37

    The pthread_cond_wait() call cannot 'spuriously' wake while some other thread is holding the associated mutex. When pthread_cond_wait() returns successfully, it will have claimed the mutex, so it cannot successfully return until the mutex is available.

    In your example, a spurious wake could occur because foo() can call pthread_cond_wait() and have the spurious wake occur before child() ever gets a chance to call pthread_mutex_lock() in the first place.

    Another problem in your example (with the commented code left disabled) has is that it's possible for the pthread_cond_wait() call to never wake. This scenario can happen if child() completes all of it's processing before foo() manages to acquire the mutex. in that scenario, child() will call pthread_cond_broadcast() before the main thread is waiting in pthread_cond_wait() so the main thread will miss the broadcast. Since foo() never checks done while holding the mutex, it won't notice that child() has finished its work.

    That's why pthread_cond_wait() pretty much always has to be performed in a loop that checks the condition.

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