In the previous article, different ways to launch parallel threads was discussed. Now we'll see how to disable forked off threads.
All active threads that have been kicked off from a fork join
block can be killed by calling disable fork
.
Why disable a fork ?
The following things happen at the start of simulation for the given example:
- Main thread executes
initial
block and finds afork join_any
block - It will launch three threads in parallel, and wait for any one of them to finish
- Thread1 finishes first because of least delay
- Execution of main thread is resumed
Thread2 and Thread3 are still running even though the main thread has come out of fork join_any
block.
module tb_top;
initial begin
// Fork off 3 sub-threads in parallel and the currently executing main thread
// will finish when any of the 3 sub-threads have finished.
fork
// Thread1 : Will finish first at time 40ns
#40 $display ("[%0t ns] Show #40 $display statement", $time);
// Thread2 : Will finish at time 70ns
begin
#20 $display ("[%0t ns] Show #20 $display statement", $time);
#50 $display ("[%0t ns] Show #50 $display statement", $time);
end
// Thread3 : Will finish at time 60ns
#60 $display ("[%0t ns] TIMEOUT", $time);
join_any
// Display as soon as the fork is done
$display ("[%0tns] Fork join is done", $time);
end
endmodule
Simulation Log
ncsim> run [20 ns] Show #20 $display statement [40 ns] Show #40 $display statement [40ns] Fork join is done [60 ns] TIMEOUT [70 ns] Show #50 $display statement ncsim: *W,RNQUIE: Simulation is complete. ncsim> exit
What happens when fork is disabled ?
The same example is taken from above, and disable fork
is added towards the end.
Note that Thread2 and Thread3 got killed because of disable fork
module tb_top;
initial begin
// Fork off 3 sub-threads in parallel and the currently executing main thread
// will finish when any of the 3 sub-threads have finished.
fork
// Thread1 : Will finish first at time 40ns
#40 $display ("[%0t ns] Show #40 $display statement", $time);
// Thread2 : Will finish at time 70ns
begin
#20 $display ("[%0t ns] Show #20 $display statement", $time);
#50 $display ("[%0t ns] Show #50 $display statement", $time);
end
// Thread3 : Will finish at time 60ns
#60 $display ("[%0t ns] TIMEOUT", $time);
join_any
// Display as soon as the fork is done
$display ("[%0tns] Fork join is done, let's disable fork", $time);
disable fork;
end
endmodule
Simulation Log
ncsim> run [20 ns] Show #20 $display statement [40 ns] Show #40 $display statement [40ns] Fork join is done, let's disable fork ncsim: *W,RNQUIE: Simulation is complete. ncsim> exit