Threads is not terminating as expected

Hi All,

I have a question about fork-join let’s suppose I have four threads if any of the two threads are completed fork-join need to be disabled.


module top;
  
  semaphore sema = new();;
  
  task display(int i);
    begin
      automatic int j = i;
      #j;
      $display("%t %d", $time, j);
      sema.put(1);
    end
  endtask
  
  initial
    begin
      fork
        display(0);
        display(1);
        display(2);
        display(3);
      join_none
      $display("fork out");
      sema.get(2);
      disable fork;
    end
endmodule

run -all

fork out

0 0

1 1

exit

this is the out for the code


module top;
  
  semaphore sema = new();;
  
  task display(int i);
    begin
      automatic int j = i;
      
      $display("%t %d", $time, j);
      sema.put(1);
    end
  endtask
  
  initial
    begin
      fork
        display(0);
        display(1);
        display(2);
        display(3);
      join_none
      $display("fork out");
      sema.get(2);
      disable fork;
    end
endmodule

run -all

fork out

0 0

0 1

0 2

0 3

exit

this is the output for the code

My doubt is if I want to run a task with zero simulation time the threads are not terminating. In the first code If the task is consuming time threads are disabling as expected. Can anyone help me why the second task is not working as expected

In reply to marathuteja:

It usually makes no sense having a fork statement with threads that do not include delays.

Your first code finishes the the two calls to display() at time 1 before executing the disable fork. The other two threads are suspended until times 2 and 3, so they get terminated.

Your second code is a race condition. Although the parent thread with the get(2) might resume after the second put(1), there is nothing preventing the other fork threads from continuing first.