Advanced · Module 7 · Lesson 3 of 8
Condition Variables: pthread_cond_wait, Predicate Loops, and Spurious Wakeups
Coordinate thread state transitions without busy-waiting using pthread_cond_wait, eliminate lost wakeups, defend against spurious wakeups with predicate loops, and evaluate futex requeueing.
By the end you can
- Coordinate thread execution across state transitions using pthread_cond_wait, pthread_cond_signal, and pthread_cond_broadcast
- Explain the atomic release-and-sleep contract of pthread_cond_wait that eliminates lost-wakeup race windows
- Construct robust while-loop predicate guards to defend against spurious wakeups and stolen signals
- Trace kernel futex requeue optimization (FUTEX_CMP_REQUEUE) preventing thundering herd bottlenecks
Builds on Mutual Exclusion: Mutexes, Deadlock Prevention, and Lock Hierarchies.
01 · A question first
Why does using if (!ready) pthread_cond_wait(&cv, &m); instead of a while loop randomly corrupt shared state under high load, even when you only signaled the condition variable once? And how does the kernel release a mutex and put a thread to sleep without a lost-wakeup race window?
Make a guess before you read on.
02 · The idea
Members only
Unlock the full lesson
This lesson is part of the membership. Join to read it in full, along with every other premium deep dive.
What's inside
- Start with the problem
- How the idea works
- Why it is correct: The Dual Threats
- What it costs
- Complete Implementation: Thread-Safe Bounded Queue
- Pitfalls and variations
- Where it is used
03 · Practice
Asked in interviews
Something wrong with this lesson? Report a problem