Hello! What could be the output of this program?
task double (int a , string s);
#5;
a = a * 2;
$display($time,"\ts=%0s\ta=%0d ",a,s);
endtask
initial begin
fork
begin
double (5,"Thread: 1");
end
begin
#2;
double (4,"Thread: 2");
end
join end
In reply to Shashank Gurijala:
This task is declared inside module. so, it by default static.
//output
5 s=Thread: 2 a=8
7 s=Thread: 2 a=16
0ns → Thread 1 call to double : a = 5, s=Thread:1
2ns → Thread 2 call to double : a = 4, s=Thread:2
5ns → a = a * 2 = 4 *2 = 8 , display statement executed for Thread 1 call
7ns → a = a * 2 = 8 *2 = 16 , display statement executed for Thread 2 call
https://www.linkedin.com/in/rahulkumar-patel-04327a54/
In reply to Rahulkumar:
Thanks and this is the correct output. Can you elaborate on the explanation, please?
In reply to Shashank Gurijala:
static lifetimes of method:
// lifetime of variable is static, you have only one copy of a and s which you are modifying with every call
task double (int a , string s);
time | a | s | comment
0ns | 5 | Thread:1 | this is due to double call by thread 1
2ns | 4 | Thread:2 | this is due to double call by thread 2
5ns | 8 | Thread:2 | a = 4 => thread 1 reach at a = a * 2 => a= 8 ; $display statement executed
7ns | 16 | Thread:2 | a = 8 => thread 2 reach at a = a * 2 => a= 16 ; $display statement executed
automatic lifetimes of method :
//lifetime of variable is automatic then new copy of a & s will be created on every call
//automatic keyword added after task
task automatic double (int a , string s);
//output
5 s=Thread: 1 a=10
7 s=Thread: 2 a=8
// double call by thread 1
time | a | s | comment
0ns | 5 | Thread:1 | this is due to double call by thread 1
5ns | 8 | Thread:1 | a = 5 => thread 1 reach at a = a * 2 => a = 10 ; $display statement executed
// double call by thread 2
time | a | s | comment
2ns | 4 | Thread:2 | this is due to double call by thread 2
7ns | 8 | Thread:2 | a = 4 => thread 2 reach at a = a * 2 => a = 8 ; $display statement executed
https://www.linkedin.com/in/patel-rahulkumar/