Fork join

Whst is different between
fork
for( int i= 0; i<4; i++)
method(i);
join_none

and

for ( int i= 0; i<4; i++)
fork
method(i);
join_none

In reply to marathuteja:

If you are just looking for the difference, I added a few more lines to your code to demonstrate it. I also added comments that may help.


module test();

  
  task method(int ii);
    #1 ; //I am adding a delay to highlight the difference.
    $display("time = %0d; i = %0d", $time,ii);
  endtask
  
  task fork_1();
    fork   //The below is all a single thread. 
      for(int i= 0; i<4; i++)
        method(i);
    join_none;
  endtask

  task fork_2();
    for ( int i= 0; i<4; i++) //There are 4 parallel thread here. You will see that all values being printed are i = 4. You will i to be "automatic" to fix that.
      fork
        method(i);
      join_none;
    endtask
  
  initial begin
    $display("Calling fork_1");
    fork_1();
    #5;  // Introducing a delay to move simulation time. Remove this to see how behaviour changes.
    $display("Calling fork_2");
    fork_2();
    #1;
    $display("The end");
  end
  
endmodule

Output :

xcelium> run
Calling fork_1
time = 1; i = 0
time = 2; i = 1
time = 3; i = 2
time = 4; i = 3
Calling fork_2
The end
time = 6; i = 4
time = 6; i = 4
time = 6; i = 4
time = 6; i = 4
xmsim: *W,RNQUIE: Simulation is complete.
xcelium> exit

In reply to KillSteal:

Another way of saying what is happening is the first fork only creates one process, which is the for loop statement. The second fork is inside the for loop, so each iteration forks another process.

The the reason the second loop only prints i=4 is because there is only one instance of the variable i shared by all the forked processes., and its value has reached 4 by the time each process calls the method(i). To fix that, you need to declare another variable that gets activated for each iteration of the loop.

 task fork_2();
    for ( int i= 0; i<4; i++)
      fork
        automatic int j = i;
        method(j);
      join_none;
    endtask

In reply to marathuteja:

Thank you for your answers it helps me a lot