在 initial 块中,通过 fork join_none 开辟的子线程和其他线程之间的执行顺序:
program test;
initial begin
fork
$display("thread A");
$display("thread B");
$display("thread C");
join_none
$display("thred D");
end
endprogram
thread D
thread A
thread B
thread C
fork join_none开辟的子线程需要等待父线程的程序块的顺序语句运行完再运行。
加入 #0 进行调度:
program test;
initial begin
fork
$display("thread A");
$display("thread B");
$display("thread C");
join_none
#0;
$display("thred D");
end
endprogram
thread A
thread B
thread C
thread D
#0 当前程序的运行,直到下个time slot再执行。
program test;
initial begin
fork
$display("thread A");
$display("thread B");
$display("thread C");
join_none
$display("thread D1");
#0;
$display("thread D2");
fork
$display("thread E");
$display("thread F");
$display("thread G");
join_none
end
endprogram
thread D1
thread A
thread B
thread C
thread D2
thread E
thread F
thread G
在 for 循环或 foreach 中使用 fork join_none 的注意事项:
1. for 循环中有 fork join_none 线程和另一个线程的情况
program test;
initial begin
for(int i = 0; i < 5; i++) begin
fork
$display("fork join_none thread %0d", i);
join_none
$display("parent thread %0d", i);
end
end
endprogram
parent thread 0
parent thread 1
parent thread 2
parent thread 3
parent thread 4
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
2. 同理,在 foreach 循环中情况类似:
program test;
int arr[5] = '{1,2,3,4,5};
initial begin
foreach(arr[i]) begin
fork
$display("fork join_none thread %0d", arr[i]);
join_none
$display("parent thread %0d", arr[i]);
end
end
endprogram
parent thread 1
parent thread 2
parent thread 3
parent thread 4
parent thread 5
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
fork join_none thread 5
3. 在两个线程之间加入 #0 进行区域调度的情况:
program test;
int arr[5] = '{1,2,3,4,5};
initial begin
foreach(arr[i]) begin
fork
$display("fork join_none thread %0d", arr[i]);
join_none
#0;
$display("parent thread %0d", arr[i]);
end
end
endprogram
fork join_none thread 1
parent thread 1
fork join_none thread 2
parent thread 2
fork join_none thread 3
parent thread 3
fork join_none thread 4
parent thread 4
fork join_none thread 5
parent thread 5
4. 在两个线程前加入 #0 进行线程调度的情况:
program test;
int arr[5] = '{1,2,3,4,5};
initial begin
foreach(arr[i]) begin
#0;
fork
$display("fork join_none thread %0d", arr[i]);
join_none
$display("parent thread %0d", arr[i]);
end
end
endprogram
parent thread 1
fork join_none thread 2
parent thread 2
fork join_none thread 3
parent thread 3
fork join_none thread 4
parent thread 4
fork join_none thread 5
parent thread 5
fork join_none thread 0