wilx
wilx

Reputation: 18228

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?

Upvotes: 3

Views: 693

Answers (1)

zwol
zwol

Reputation: 140445

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.

Upvotes: 5

Related Questions