Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atomicity of pthread_cond_wait()'s unlock-and-wait?

How atomic is the unlock-and-wait of pthread_cond_wait() call?
Is there a window where mutex is already unlocked but the thread is not yet in the part where it is actually waiting and able to receive notifications?
IOW, is there a potential for missed wakeups in the pthread_cond_wait() function itself?

like image 491
wilx Avatar asked Dec 03 '25 20:12

wilx


1 Answers

The POSIX.1-2008 specification of pthread_cond_wait addresses this question in its second paragraph:

These functions [pthread_cond_wait and pthread_cond_timedwait] atomically release mutex and cause the calling thread to block on the condition variable cond; atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable". That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.

So, to first order, the answer is "yes, it's atomic", but pay careful attention to the last sentence. There is no missed-wakeup window as long as the call to pthread_cond_broadcast or pthread_cond_signal comes from a thread that successfully acquired the mutex after the sleeping thread released it, and then, perhaps, released it again. If the call comes from a thread that has not acquired the mutex at least once since it was released, the wakeup might get lost.

like image 53
zwol Avatar answered Dec 05 '25 09:12

zwol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!