In reply to sriharifoxtrot:
Two things you need to understand:
- Each statement inside a fork/join_none gets put into a new child thread that does not start until the parent thread blocks or terminates. In both code examples, that means after the initial block terminates. At that point, the for-loop has already finished and the variable
i has the value 4. But in code 1, there are two statements that get forked into a total of 8 threads. They are all in a race, so if the
$display(k); executes first, the output would be 0. Since there is only one shared static variable
k, once the assignment
k = i occurs, the $displays that execute after that will all display 4. - Automatic variables get created and initialized upon entry into a procedural block (begin, fork, task or function). Each entry into the block creates a new variable. In the code 2 example, 4 different
k variables get created and initialized each time through the loop with the current value of
i. You would get the same behavior if you placed the declaration of
k outside the fork, but inside the inner most begin/end block.