Fork join statement with for loop

I’m trying to work on below code. Let it say we have the index from 0 to 4 for each tasks we process and we want them spawned together without time-consumed. And below code is the simplest to work but somehow it’s too cumbersome… How to use for-loop to achieve the same purpose ?


task my_task1(int idx);
  // do something
endtask

task my_task2(int idx);
  // do something
endtask

fork
  my_task1(0);
  my_task2(0);
  my_task1(1);
  my_task2(1);
  my_task1(2);
  my_task2(2);
  my_task1(3);
  my_task2(3);
  my_task1(4);
  my_task2(4);
join_none


In reply to zz8318:

for(int i=0;i<5;i++)
   fork
     automatic int j = i;
     my_task1(j);
     my_task2(j);
   end

Note, the automatic keyword is needed if the context of the code in not already automatic.

In reply to dave_59:

Hi Dave, What’s the difference if we code “automatic int j = i” inside the fork, or outside the fork ?


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


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

In reply to zz8318:

No difference except you need an extra begin/end scope to put the variable declaration outside the fork.