变量的生命周期指的是该变量在整个仿真过程中存在的时间。生命周期的长短对仿真的影响,一是仿真环境访问static变量可能出现冲突导致结果不符合预期,二是直接影响了内存的占用。
一、lifetime的基本原则
- 变量在module、program、interface、checker、task、function外定义:static lifetime(在整个仿真时间内存在)
- 变量在module、program、interface、checker内,且在task、function、process外定义:static lifetime
- 变量在static task、static function、block内定义:default static lifetime
- 变量在static task、static function、block内定义,但变量加上automatic修饰符:lifetime of the call or block(随用随生成)
- 变量在automatic task、automatic function、automatic block内定义:default lifetime of the call or block
- 变量在automatic task、automatic function、automatic block内定义,但变量加上static修饰符:static lifetime
上面情况分的有点多,但总的来说就是看离这个变量最近的属性是什么就行了。而task、function是什么类型由下面规则来确定。
- 定义在module、interface、program、package内的task、function默认是static的;反之外面的默认就是automatic。
- 类的task和function、for循环的loop变量默认是automatic的,而不管它们是在哪里被定义的。
- 你也可以自己加上static、automatic修饰符来限定。
几个例子:
module msl;
int st0; // static
initial begin
int st1; // static
static int st2; // static
automatic int auto1; // automatic
end
task automatic t1();
int auto2; // automatic
static int st3; // static
automatic int auto3; // automatic
endtask
endmodule
二、变量初始化与static、automatic的关系
- 由于static变量在整个仿真时间内存在,所以static变量的初始化实际上是在仿真开始前就进行了的。即使在for循环内声明+初始化的static变量,其初始化只做一次。
- 与之对应的automatic变量随用随生成。for循环内的声明+初始化就会执行多次。
module top_legal;
int svar1 = 1; // static keyword optional
initial begin
for (int i=0; i<3; i++) begin
automatic int loop3 = 0; // executes every loop
for (int j=0; j<3; j++) begin
loop3++;
$display(loop3);
end
end // prints 1 2 3 1 2 3 1 2 3
for (int i=0; i<3; i++) begin
static int loop2 = 0; // executes once before time 0
for (int j=0; j<3; j++) begin
loop2++;
$display(loop2);
end
end // prints 1 2 3 4 5 6 7 8 9
end
endmodule : top_legal