statictaskverilogsystem-verilog

Static vs. automatic tasks


I'm trying to understand static tasks. Here I understand that Thread1, 2 & 3 occur concurrently and that _time & t_name are static variables inside the task. When I simulate the code, I get:

[0] Main Thread: Fork join going to start
[0] Main Thread: Fork join has finished
[0] Nested fork has finished
[10] Thread2
[20] Thread2
[30] Thread2

But, then I thought since "Thread2" gets shared with the other two thread's t_name, I thought even _time would be 20 for all the three threads? The answer I was expecting was:

[0] Main Thread: Fork join going to start
[0] Main Thread: Fork join has finished
[0] Nested fork has finished
[20] Thread2
[20] Thread2
[20] Thread2

Can someone please help me understand?

module tb; 
  initial begin 
    $display("[%0t] Main Thread: Fork join going to start", $time); 
    fork 
      begin 
        fork 
          print(10, "Thread1"); 
          print(20, "Thread2"); 
        join_none
        $display("[%0t] Nested fork has finished", $time); 
      end  
      print(30, "Thread3");  
    join_none
    $display("[%0t] Main Thread: Fork join has finished", $time);
  end 
 
  task print (int _time, string t_name); 
    #(_time) $display ("[%0t] %s", $time, t_name); 
  endtask 
endmodule 

Solution

  • First realize there are five threads in your example. There's the parent thread created by the initial block—what you call the "main" thread. The main thread forks off 2 threads—the begin/end block containing the nested fork and the call to print(30, "Thread3"); statement.

    Those 2 forked threads do not start until after the main thread terminates(or gets suspended). It's a race condition as to which of the two forked threads start first. And the nested fork thread creates 2 more threads which also start in a race after the nested fork thread terminates.

    Ultimately, the three calls to print() are in a race to be entered at time 0. Although Verilog rules allow interleaving of those threads, all single-core implementations of SystemVerilog simulators do not switch to another thread until it blocks or terminates. So regardless of whether the task has a static or automatic lifetime, each call to print() enters the task and its first argument _timegets used to block the thread for the specified time before the static argument has a chance to be overwritten. Note that once a procedure encounters a #(delay_expression), that expression only gets evaluated once. Changing the variables afterward do not change scheduled waiting time. That is why the print $times are 10,20, and 30.

    However since the task was declared with an static lifetime, there is only one set of argument variables and they do get overwritten as each call to print() happens. . If you $display both task arguments, you would see the values from last call to print() in all three $display statements.