VLSI DV Interview Puzzles · All levels

Loop Variable Capture in Detached Threads

What does this print three times, and why is it not 0,1,2?

Puzzle

Difficulty: Medium · Puzzle 2 of 6 · Topic: Fork Join Puzzles

What does this print three times, and why is it not 0,1,2?

Code

systemverilog
module p2;
  initial begin
    for (int i = 0; i < 3; i++) begin
      fork
        #1 $display("i=%0d", i);
      join_none
    end
    #2;
  end
endmodule

Hint

The child runs later than loop progression. Think about what value `i` has by time #1.

Step-by-step solution

diagram
1) Each iteration spawns a detached child that waits #1 before printing.
2) The parent loop completes all iterations in the same time slot and exits with `i == 3`.
3) At t=1, all children evaluate `i` and see 3, so each prints the same value.

Answer

Answer: The output is `i=3` three times

Why candidates get it wrong

Candidates assume each forked branch gets a copied loop index automatically.

Interviewer follow-up

How do you fix it so each child prints its own index value deterministically?

Related topics