VLSI DV Interview Puzzles · All levels
Lost Update in Forked Counter
Compute final hits and explain why four increments do not always produce four.
Puzzle
Difficulty: Hard · Puzzle 5 of 6 · Topic: Race Condition Puzzles
Compute final hits and explain why four increments do not always produce four.
Code
systemverilog
module tb;
int hits = 0;
task automatic add_hit();
int snap;
snap = hits;
#0 hits = snap + 1;
endtask
initial begin
fork
repeat (2) add_hit();
repeat (2) add_hit();
join
$display("[%0t] hits=%0d", $time, hits);
end
endmoduleHint
Read-modify-write is not atomic across concurrent threads.
Step-by-step solution
diagram
1) Multiple threads read same hits snapshot before any #0 write occurs.
2) Writes happen later in inactive and overwrite each other.
3) Typical final result is 2 instead of 4 because two updates are lost.
4) Correct fix needs synchronization (semaphore/atomic handoff), not timing hacks.Answer
Answer: Final hits is typically 2, not 4, due to concurrent stale snapshots and overwrite races.
Why candidates get it wrong
Candidates assume integer assignment is 'thread-safe' in simulation. It is not.
Interviewer follow-up
Show a semaphore-based rewrite that guarantees hits=4.