proper use of "disable fork" in systemverilog

You should consider using processes instead of disable in SystemVerilog

process process1;
process process2;
fork
  begin
    process1 = process::self();
    # do something in process 1
  end
  begin
    process2 = process::self();
    # do something in process 2
  end
join_any
#1;
if (process1 != null && process1.status != process::FINISHED)
  process1.kill();
if (process2 != null && process2.status != process::FINISHED)
  process2.kill();

It is supposed to be safer than disable.


"disable fork" kills not only the processes launched by your fork...join_any, but also any other processes that are descendants of the same process that executes the disable-fork. If you have launched any other processes (using, for example, fork...join_none) earlier in the life of this process, then those other processes will be killed too.

You can rather easily protect against this by causing your fork...join_any, and its later disable-fork, to run in a new child process of its own. This limits the effect of your disable-fork so that it can affect only the newly launched processes that you care about, and is guaranteed to have no other unwanted effects.

Do this by enclosing the whole mess in "fork begin...end join" like this:

fork begin // isolate the following code as a single child process
  fork  // launch the processes you wish to manage
    apply_input();
    update_status();
    verify_status();
  join_any // kill off the *_status threads when apply_input terminates
  disable fork;
end join // end of child process isolation

This is a well-known issue with fork...join_any and fork...join_none. It's been discussed recently on Verification Guild forum, and is described in sections #79 and #80 of the Sutherland and Mills book "Verilog and SystemVerilog Gotchas".

Putting "fork begin" and "end join" on single lines is unusual, but I like it as a way to make it very obvious that I'm synchronously forking exactly one child process. Normally that would be a useless thing to do, but in this situation it's essential.

This idiom is so common, and so easy to get wrong, that you may prefer to encapsulate it in a pair of macros (I don't like this, but...):

`define BEGIN_FIRST_OF fork begin fork
`define END_FIRST_OF join_any disable fork; end join

Now you can write...

`BEGIN_FIRST_OF
    apply_input();
    update_status();
    verify_status();
`END_FIRST_OF

where the names "...FIRST_OF" are intended to reflect the similarity to the Specman (e) language construct that does the same thing.