Difficulty: Hard · Puzzle 5 of 6 · Topic: Race Condition Puzzles
Compute final hits and explain why four increments do not always produce four.
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
endmoduleRead-modify-write is not atomic across concurrent threads.
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: Final hits is typically 2, not 4, due to concurrent stale snapshots and overwrite races.
Candidates assume integer assignment is 'thread-safe' in simulation. It is not.
Show a semaphore-based rewrite that guarantees hits=4.