Sunday, March 17, 2013

fork join_none inside a for loop

To spawn multiple threads with each thread having an index input argument like

for (int i = 0;i < 5;i++) begin
fork
thread(i)
join_none
end

since 'i' is a common variable for all threads, all threads are spawned with index 4.
I don't want to use join_all as i want all threads to be spawned simultaneously.


To work as expected try the below 
This is explained in the LRM. See the last example in section 9.3.2 Parallel blocks that explains fork/join_none.

for(int i = 0; i < 5; i++) begin
automatic int j;
j = i;
fork
thread(j);
join_none
end

What makes it work is that for each iteration of the for loop, a local automatic variable is created with a lifetime that is extended by the lifetime of the fork/join_none block that references it. The statements inside the fork/join_none block begin execution after finishing the for loop. It doesn't mater if the function/task call passes its arguments by value or by reference; each call has an independent copy of the automatic variable that was set to a value as the for loop went through its iterations.