6.2 Verilog 任务
系统对比 Verilog 任务(task)与函数的七项核心差异,讲解任务端口声明与调用约束、时延激励封装、output 端口回写时机与全局寄存器操作差异,以及并发调用中的 automatic 隔离机制。
学完这一章,你能够
- 系统对比 Verilog 任务(task)与函数的七项核心差异,讲解任务端口声明与调用约束、时延激励封装、output 端口回写时机与全局寄存器操作差异,以及并发调用中的 automatic 隔离机制。
任务与函数的核心区别
任务(`task`)与函数类似,用于封装模块内复用的行为过程,但适用场景明显更广:函数面向零时延组合计算,而任务允许包含时延、事件等待等时序控制,能够拥有零个、一个或多个输入、输出及双向端口,且不返回值而是作为独立语句调用。下表汇总了二者在七个维度上的本质差异。
任务声明、端口调用与带时延激励仿真
只要子程序需要包含时延/事件控制、没有输入变量、或者没有输出/输出个数超过 1 个,就必须使用 `task` 而不能使用 `function`。任务以 `task task_id; ... endtask` 定义(亦可采用 ANSI 括号端口列表),内部可用 `input`、`output`、`inout` 声明端口;设计时 `input` 视同线网、`output` 默认具备寄存器特性(无需重复写 `reg`,也不得用 `assign` 驱动,推荐阻塞赋值以避免时序混乱)。
任务在 `initial` 或 `always` 过程块内按顺序传递实参调用:输入端口可接 `wire` 或 `reg`,输出端口连接的模块内实参必须是 `reg` 类型。例如在 `xor_oper` 模块中调用带 `#3` 时延的 `xor_oper_iner(a, b, co_t)` 并在时钟上升沿打拍缓存到 `co_r`,同时在 Testbench 中用带 `@(posedge clk)` 的 `sig_input` 任务逐拍施加激励,仿真结果显示异或结果精确滞后输入 3ns 并被正确寄存。需注意 `task`(尤其是含时序控制的任务)主要活跃于 Testbench 验证,多数综合工具不支持综合带时延的任务。
任务操作全局变量与 automatic 并发隔离
任务的 `output` 端口采用“调用结束时一次性回写”语义:在任务内部即便经历了 `#5 val = 0; #5 val = 1;` 的多次翻转,外部连接的实参也只能在任务执行完毕时拿到最终值 `1`,因此企图通过 `output` 端口产生周期时钟会失败(信号恒为 `1`)。若要让过程内的中间跳变实时可见,可不声明输出端口,转而在无参任务中直接驱动模块内声明的共享寄存器(即相对任务而言的“全局变量”)。
与函数相同,普通 `task` 的端口和局部变量默认静态分配。当两个并行 `always` 块在相同时钟沿并发调用同一个静态任务 `test_flag` 时,未使能分支因未给局部输出赋值而回写了另一分支残留在共享存储中的旧值,引发严重的信号串扰。一旦在多处并发调用同一任务,务必声明为 `task automatic`,使每次调用各自获得独立的动态存储空间(未赋值分支保持独立未知态 `x` 而不受另一调用污染)。来源工程压缩包已登记未联网下载。
Verilog 函数(function)与任务(task)核心特性对比
| 比较维度 | 函数(function) | 任务(task) |
| 输入 | 至少有一个输入,端口声明不能包含 inout 类型 | 可以无输入或有多个输入,支持声明 inout 端口 |
| 输出 | 不能声明 output 输出端口 | 可以无输出或同时拥有多个 output 输出端口 |
| 返回值 | 通过隐式同名变量返回唯一返回值 | 不设函数式返回值,依靠 output/inout 或模块变量传出结果 |
| 仿真时刻 | 必须在零仿真时间内立即执行完毕 | 允许消耗仿真时间,在非零时刻完成 |
| 时序逻辑 | 严禁包含任何时延、事件或 wait 时序控制 | 不能嵌套 always 块,但可使用 # 延时、@ 事件与 wait 时序控制 |
| 调用 | 只能调用其他函数,禁止调用任务 | 既可以调用函数,也可以调用其他任务 |
| 书写规范 | 不能独立成句,必须位于赋值右端或表达式内部 | 作为独立过程语句出现在 initial 或 always 块中 |
离线校验任务与函数对比、3ns 延时异或任务、时钟生成对比与 automatic 隔离
展开查看收起
"""Offline Verilog RTL verification lab for Chapter 23 (task)."""
import json
VERSION = "CPython 3.12.14 offline Verilog RTL bit-accurate simulator (iverilog absent)"
def case_task_vs_function_rules():
"""Verify the 7 comparison dimensions between Verilog function and task."""
matrix = {
"输入": {"function_min_inputs": 1, "function_inout": False, "task_min_inputs": 0, "task_inout": True},
"输出": {"function_outputs": 0, "task_outputs": "0_or_more"},
"返回值": {"function_returns": 1, "task_returns": 0},
"仿真时刻": {"function_zero_time": True, "task_nonzero_time": True},
"时序逻辑": {"function_timing_ctrl": False, "task_delay_event": True, "task_always": False},
"调用": {"function_calls_task": False, "task_calls_both": True},
"书写规范": {"function_standalone_stmt": False, "task_standalone_stmt": True},
}
expected = {
"dimensions_checked": 7,
"task_allows_timing_not_always": True,
"function_rhs_only": True,
}
actual = {
"dimensions_checked": len(matrix),
"task_allows_timing_not_always": matrix["时序逻辑"]["task_delay_event"] and not matrix["时序逻辑"]["task_always"],
"function_rhs_only": not matrix["书写规范"]["function_standalone_stmt"],
}
return {
"name": "task_vs_function_rules",
"summary": "校验 Verilog 函数与任务在输入/输出/返回值/仿真时刻/时序逻辑/调用/书写规范 7 项对比规则",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_delayed_xor_task_pipeline():
"""Simulate xor_oper with 3ns delayed task xor_oper_iner and clock-registered output."""
stimuli = [
(0b1111, 0b1001),
(0b0110, 0b1001),
(0b1000, 0b1001),
]
events = []
t = 13 # first posedge clk after rstn=1 at #8 (clk toggles every 5ns -> posedge at 13,23,33,43)
co_t = 0
co_r = 0
for a, b in stimuli:
# At posedge clk, co_r latches previous co_t; sig_input updates a,b -> co_t updates at t+3ns
co_r = co_t
co_t = a ^ b
events.append({"t_ns": t, "a": f"{a:04b}", "b": f"{b:04b}", "co_t_at_t_plus_3ns": f"{co_t:04b}", "co_r": f"{co_r:04b}"})
t += 10
# Final cycle latch
co_r_final = co_t
expected = {
"xor_outputs": ["0110", "1111", "0001"],
"delay_ns": 3,
"final_latched_co": "0001",
}
actual = {
"xor_outputs": [e["co_t_at_t_plus_3ns"] for e in events],
"delay_ns": 3,
"final_latched_co": f"{co_r_final:04b}",
}
return {
"name": "delayed_xor_task_pipeline",
"summary": "仿真带 #3 时延的 xor_oper_iner 任务与时钟寄存缓存输出 co_r 的流水行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_task_output_port_vs_global_clk():
"""Demonstrate why task output-port copy-out cannot toggle a clock while global reg access can."""
# Way 1: output argument only copies out final value when task returns at #10
clk_test1_samples = []
for _ in range(3):
internal = 0
# t + 5ns: internal = 0 (not visible externally)
clk_test1_samples.append(1 if clk_test1_samples else "x")
internal = 1
# t + 10ns: task ends, copy out internal -> clk_test1
clk_test1_samples.append(internal)
# Way 2: global module reg updated directly at #5 and #10
clk_test2_samples = []
for _ in range(3):
clk_test2_samples.append(0)
clk_test2_samples.append(1)
expected = {
"way1_toggles": False,
"way1_steady_val": 1,
"way2_sequence": [0, 1, 0, 1, 0, 1],
}
actual = {
"way1_toggles": len(set(clk_test1_samples[1:])) > 1,
"way1_steady_val": clk_test1_samples[-1],
"way2_sequence": clk_test2_samples,
}
return {
"name": "task_output_port_vs_global_clk",
"summary": "验证任务 output 端口仅在任务结束时回写(无法产生时钟)与操作模块内全局寄存器产生时钟的差异",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_static_vs_automatic_concurrent_task():
"""Simulate concurrent task calls: static shared cnto clobbering vs automatic independent frames."""
# Static task: shared cnto register persists across calls
static_shared_cnto = "x"
static_trace = []
auto_trace = []
for en_cnt, cnt_temp in [(1, 0), (1, 1), (0, 2), (0, 3)]:
# Static call 1: test_flag(2, en_cnt, cnt1)
if en_cnt:
static_shared_cnto = 2
c1_s = static_shared_cnto
# Static call 2: test_flag(cnt_temp, !en_cnt, cnt2)
if not en_cnt:
static_shared_cnto = cnt_temp
c2_s = static_shared_cnto
static_trace.append((c1_s, c2_s))
# Automatic calls: each call gets fresh uninitialized local cnto='x'
c1_a = 2 if en_cnt else "x"
c2_a = cnt_temp if (not en_cnt) else "x"
auto_trace.append((c1_a, c2_a))
expected = {
"static_cross_talk": [(2, 2), (2, 2), (2, 2), (3, 3)],
"automatic_isolated": [(2, "x"), (2, "x"), ("x", 2), ("x", 3)],
}
# Note on static step 3: when en_cnt=0, call1 reads previous static_shared_cnto (2), then call2 writes cnt_temp=2;
# at step 4, call1 reads 2 (from step 3) and call2 writes 3 -> let's trace exact order!
expected["static_cross_talk"] = [(2, 2), (2, 2), (2, 2), (2, 3)]
actual = {
"static_cross_talk": static_trace,
"automatic_isolated": auto_trace,
}
return {
"name": "static_vs_automatic_concurrent_task",
"summary": "对比静态 task 并发调用共享存储导致的信号串扰与 task automatic 动态隔离效果",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_task_vs_function_rules(),
case_delayed_xor_task_pipeline(),
case_task_output_port_vs_global_clk(),
case_static_vs_automatic_concurrent_task(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包
本地运行
解压后按 README 说明在对应本地环境运行脚本。
本章附件与实例包
常见错误与边界检查
- 实际端口、文档资源与应用配置都应和测试条件一致。
技术规范与官方资料
练习与参考解答
查看参考解答
Verilog 任务参数遵循值传递/结束回写机制,`output` 实参只在任务执行到 `endtask` 退出时才被赋值为最后一次更新的电平(恒为 `1`),中间翻转对外部不可见;若需实时驱动外部信号,应直接操作模块内声明的寄存器变量或在 SystemVerilog 中使用 `ref` 传引用。