Questions about argument passing by ref

Hi All,

I have some questions about task behaviour and argument passing by reference.
For the following piece of code,

module top;
 event e1, e2;
 task  trigger(event local_event, input time wait_time);

 #wait_time;
 ->local_event; 
 endtask

initial begin
 fork
   trigger(e1, 10ns);
  begin
   wait(e1.triggered);
    $display("%0t: e1 triggered", $time);
  end
 join 
end

initial begin
 fork
  trigger(e2, 20ns);
  begin
    wait(e2.triggered);
    $display("%0t: e2 triggered", $time);
  end
 join 
end
endmodule

The result is

10: e2 triggered

However, after I change the argument local_event to ref event local_event like the following,

task  trigger(ref event local_event, input time wait_time);
     #wait_time;
     ->local_event; 
endtask

The sim result becomes

10: e1 triggered
20: e2 triggered

I have two confusions about these behaviours:

  1. Why in code version_1, only one event is triggered and why the result is “10: e2 triggered", instead of “10: e1 triggered”?
  2. I know that if task trigger() is declared as automatic (which requires us to run the code inside a program instead of a module), task trigger() will get executed twice and e1 is triggered at 10ns, e2 is triggered at 20ns. But I wonder why we can get the same effect by simply declaring local_event argument as ref inside a module?

Thanks for your help!

In reply to peterjin:

Your problem is the same as your last question. You have a task with a static lifetime, and the second call to trigger overwrites the arguments to the first call. The order of the calls is a race condition. Changing the task to automatic gives you the behavior I think you are looking for.

Your change to a ref argument should be a compiler error because tasks with static lifetimes are not allowed to have ref arguments. You are supposed to have access to static arguments from outside the task, like any other static variable.

In any case, passing event and class variables by reference creates a unnecessary double reference.

In reply to dave_59:

Thanks for the explanation, that solved my confusions!

Hao