Yesterday a friend and I were stuck debugging some multithreaded code. The bug was really simple and right in front of our eyes, but it still took me almost half a day to find it. I’m putting a simplified version of it here in case anyone finds it interesting.
Challenge: find the sequence of operations that causes the assertion on line 3.1 of the second thread to fail.
Initial state:
sync = source = is_processing = 0
READY_VALUE = 2
Pseudocode (all 3 threads run in an infinite loop):
Thread 1:
loop:
1. if source != READY_VALUE:
1.2. source += 1
1.3. // some heavy processing
2. if source == READY_VALUE:
2.2. sync = READY_VALUE
Thread 2:
loop:
3. if (sync != 0 && is_processing == 0):
3.1. assert (sync != 0)
3.2. is_processing = 1
3.3. // some heavy processing
3.3. queue+=1 // triggering thread 2
Thread 3:
loop:
4. if queue>0:
4.1. queue -= 1
4.2. sync = 0
4.3. is_processing = 0
4.4. source = 0
Assumptions:
- All reads (loads) are performed atomically with
Ordering::Acquire, and all writes (stores) are performed atomically withOrdering::Release. - No integer overflow occurs in this code.
- If you solve it, I’d love to hear your answer: the sequence of line indices in the order they execute.
- I modeled this system in Rust here and hooked a model checker up to it. If you’re curious, you can give it a run. The model checker is called loom, and it basically checks every possible execution of the code and tells you which interleavings make your assertions fail.
Verification really is a beautiful field.