Doubts on automatic variable

I have one question regarding fork-join let’s say I have one automatic variable “a”. In fork-join, I have two threads in one thread “a” is incrementing, and in another thread “a” is decrementing. I am expecting the display one answer to be 3 and display 2 answer to be 1 because I am thinking each time “a” is called it will allocate memory. Can anyone correct me if my thinking is wrong.


module top;
  initial
    begin
      automatic int a = 2;
      fork
        begin //: 1
          a = a + 1;
          $display("1 %d", a);
        end
        begin //: 2
          a = a - 1;
          $display("2 %d", a);
        end
      join
      
    end
endmodule

run -all

1 3

2 2

exit

along with that what if we don’t have an automatic keyword and what is the behaviour of the code? I think it is a race condition correct me If I am wrong.

Thank You.

In reply to marathuteja:

In this particular example, it makes no difference if ‘a’ is declared with a static or automatic lifetime. There is only one instance of the variable ‘a’ shared between the two threads. And yes, it is a race condition which thread starts first

In reply to dave_59:

If we take an automatic task or function, when we call the function or task each time then it allocates space each time for that task or function.
for example :


module top;
function automatic int factorial(int N);// when we call this function space is created for factorial
if(N>2)
return factorial(N-1) * N; // again it will create another space here
else
return 1;
endfunction
function int factorial(int N);// when we call this function space is created for factorial
if(N>2)
return factorial(N-1) * N; // the created space is used again here right.
else
return 1;
endfunction
endmodule

Likewise, when automatic variables get space allocated each time can you explain with an example