SystemVerilog Fork Join: Syntax and Thread Control
In SystemVerilog, fork ... join runs procedural branches concurrently and waits until every branch finishes before continuing the parent process. The alternatives, join_any and join_none, change when the parent resumes, not whether unfinished branches keep running. This guide covers the syntax, runnable examples, automatic variables, and the thread-control rules that prevent missing output, runaway workers, and accidental cancellation.
How Forked Processes Work
A fork block creates a separate child process for each statement directly inside it. Those processes execute concurrently within the simulator.
Concurrency here means independent execution on the simulation timeline, not necessarily execution on different CPU cores.
The important distinction is between a branch and the statements inside that branch:
- Statements directly inside
forkbecome separate processes. - Statements grouped inside
begin ... endexecute sequentially within one process. - A task call directly inside
forkforms one branch. Statements inside that task run sequentially unless the task creates additional processes.
For example, if driving a transaction and checking its immediate result must happen in sequence, put both operations in one begin ... end branch. Put an independent monitor in another branch.
Branches do not execute in a guaranteed source-code order. If two branches access the same variable in the same scheduling region without synchronization, their interaction can be a race.
How to Use Fork Join in a Testbench
Choose the ending keyword based on when the parent should continue and what should happen to unfinished work.
| Ending Keyword | Parent Continues When | Unfinished Branches | Typical Use |
|---|---|---|---|
join |
All direct child processes finish | None remain among those children | Complete several operations before checking results |
join_any |
Any direct child process finishes | Continue unless explicitly stopped | Race an operation against a timeout |
join_none |
Immediately, without waiting for children | Remain scheduled to run | Launch background workers and synchronize later |
Step 1: Group Each Sequential Operation Into a Branch
- Identify the operations that can run independently.
- Wrap each multistatement operation in
begin ... end. - Choose join to wait for all branches, join_any to wait for one, or join_none to continue without waiting.
Be especially careful with delays. A delay followed by a statement belongs to that statement; it does not delay other statements elsewhere in the fork.
For example, a delayed assignment and a separate logging statement directly inside fork would be independent branches. Group them if the log must occur after the assignment.
Step 2: Run a Complete Fork Join Example
- Save this example in a SystemVerilog source file.
- Compile and run it in SystemVerilog mode using a simulator that supports these process-control constructs.
The delays below are illustrative testbench inputs, chosen to make the execution order visible, not timing recommendations for a device.
module fork_join_demo;
timeunit 1ns;
timeprecision 1ns;
initial begin
$display("Starting at %0d ns", $time);
fork
begin : worker_a
#10ns;
$display("A finished at %0d ns", $time);
end
begin : worker_b
#20ns;
$display("B finished at %0d ns", $time);
end
join
$display("Parent resumed at %0d ns", $time);
wait fork;
$display("All direct children finished");
$finish;
end
endmodule
Both branch delays start from the fork’s execution, rather than one after the other. The parent resumes after the longer branch finishes.
With join, the final wait fork has nothing left to wait for in this example. It is included so the next experiment also lets every worker finish before ending the simulation.
Step 3: Compare the Other Join Forms
- Replace only the ending
joinwithjoin_any, then rerun the example. - Replace it with
join_none, then rerun again. - Keep
wait forkbefore$finishin both versions.
Watch the position of the Parent resumed message:
- With
join, it appears after both worker-completion messages. - With
join_any, it appears between the worker-completion messages. - With
join_none, it appears before either worker-completion message.
With join_none , the parent continues without waiting for either delayed worker to finish. In this example, the parent prints its message and then suspends at wait fork.
A blocking assignment does not, by itself, count as suspension. Neither does calling a task that returns without blocking.
Do not replace wait fork with an immediate $finish and expect the workers to run. $finish ends the simulation; it is not a request to wait for background work.
How to Stop Forked Threads Safely
Choosing when the parent continues and choosing which workers to cancel are separate decisions.
For a timeout, allowing the parent to resume is only part of the job. The losing branch should usually stop so it cannot later report a false timeout or keep touching testbench state.
The standard cancellation statement is disable fork, but its scope is easy to misunderstand: it terminates the calling process’s active child processes and their descendants. It does not simply target whichever textual fork appears closest to it.
That means it can also cancel unrelated children launched earlier by the same process.
Isolate a Completion-Versus-Timeout Race
Use an outer fork with a single branch to create a dedicated controlling process. That process launches the competing workers and cancels its own remaining children.
module fork_timeout_demo;
timeunit 1ns;
timeprecision 1ns;
bit done;
bit timed_out;
initial begin : stimulus
#10ns;
done = 1;
end
initial begin : test
timed_out = 0;
fork
begin : isolated_wait
fork
begin : completion_worker
wait (done);
end
begin : timeout_worker
#20ns;
timed_out = 1;
end
join_any
disable fork;
end
join
if (timed_out)
$fatal(1, "Timed out waiting for done");
$display("Completion observed; timeout worker canceled");
$finish;
end
endmodule
Here, the completion worker finishes first. The isolated controlling process resumes, cancels its timeout worker, and then finishes. The outer join ensures that cancellation is complete before the test checks the result.
To exercise the failure path, remove the assignment that sets done. The timeout worker will then finish first, cancel the waiting worker, and end the test with a fatal error.
If completion and timeout become eligible in the same simulation time slot, this pattern alone does not establish a deterministic tie-break. A deadline-sensitive test needs an explicit rule for whether completion at the deadline counts as success and a sampling scheme that implements that rule.
Avoid Accidental Cancellation
A plain begin ... end block does not create a new process, so adding one around disable fork does not provide isolation. Calling a task also does not create a new process: a disable fork executed by the task acts in the calling process’s context.
Other details matter when cancellation becomes more complex:
- Killing a process is not cleanup. Code after the blocked statement will not run, so do not rely on it to release a semaphore, restore a driven signal, or complete a protocol transaction.
- Cancellation is permanent for that process instance. Executing the fork again creates new child processes; it does not resume the canceled ones.
Keep cleanup under the control of a surviving process, especially when workers acquire shared resources.
Automatic Variables in Fork Loops
Loop-launched join_none workers commonly print the same index because they read the loop variable after the parent has finished iterating.
Declaring the loop index inside the for statement does not give each spawned branch its own snapshot. The branches still refer to that loop variable, and their execution is deferred while the parent continues running.
Capture the value in an automatic variable declared directly in the fork scope:
module fork_loop_demo;
initial begin
for (int i = 0; i < 3; i++) begin
fork
automatic int id = i;
begin
$display("Worker id = %0d", id);
end
join_none
end
wait fork;
$display("Every worker completed");
$finish;
end
endmodule
Each entry into the fork creates and initializes a separate id. The declaration itself is not another concurrent branch.
The workers print the captured values 0, 1, and 2, although their printing order is unspecified.
Why Declaration Placement Matters
The initialization in the fork’s declaration area happens when the parent enters that fork scope, before its child statements begin executing.
Moving the declaration inside the child branch changes that timing:
fork
begin
automatic int id = i; // Runs when this child starts
$display("Worker id = %0d", id);
end
join_none
This is not an equivalent capture. If the parent completes the loop before suspending, the child initializes id from the loop variable’s final value.
The distinction is not simply “automatic versus static.” It is also when the initializer executes.
Why an Automatic Task Does Not Fix Capture by Itself
An automatic task gives concurrent calls separate storage for arguments and local variables. It does not make the caller evaluate a deferred task call earlier.
If a child branch eventually calls a task with the shared loop variable as its argument, the argument is evaluated when that child executes the call. The loop may already be finished.
Capture the loop value before deferred execution, then pass the captured value to an automatic task. This separates two different requirements: preserving the intended argument and keeping concurrent task invocations from sharing local storage.
Nested Forks and Background Processes
The process tree, not the visual indentation, determines what a wait or cancellation reaches.
Use wait fork to synchronize with background workers before continuing with dependent work. It is not limited to the most recently written fork, and it is not a global wait for all simulation activity.
A Worker Can Finish Before Its Background Work
Suppose an outer fork branch calls a task. That task launches work with join_none and returns without waiting.
The outer branch can finish while the newly launched background processes are still active. Consequently, the outer join can complete without proving that every descendant has finished.
If the task’s contract is “return when this operation is complete,” make it wait for the work it owns before returning. Use join for work that should complete together, or use wait fork within the owning process after it has launched its children.
A useful design rule is to keep a controlling process alive until the children it owns have either finished or been canceled.
Background Work Needs an Explicit Owner
A background monitor or driver needs a defined lifecycle:
- Which process launches it?
- Which event or condition tells it to stop?
- Which process waits for its termination?
- Which surviving process restores any shared state?
An unbounded monitor inside fork ... join prevents that join from completing. Putting the same monitor under join_none avoids the immediate wait, but does not solve its shutdown problem.
For long-lived workers, prefer a deliberate stop condition and orderly completion when practical. Use forced cancellation when the design genuinely calls for abandoning the operation.
How to Verify Fork Join Behavior
Verify both the useful work and the lifecycle of its workers. A test can produce the expected result while still leaving a timeout or monitor running.
Use these checks before moving the pattern into a larger testbench:
- Record completion explicitly. Have each required worker set a completion flag or publish a result, and check those results before consuming them.
- Check canceled workers for later activity. A losing timeout or transaction worker should not produce subsequent side effects.
- Exercise success and failure paths. Test both normal completion and missing completion, rather than validating only the fast path.
- Test repeated invocation. Run the operation again to expose stale flags, shared task storage, and incorrectly scoped cancellation.
Also check that repeating workers genuinely allow simulation to progress. A forever loop with no suspending operation can prevent time from advancing.
A wait expression does not suspend if its condition is already true. If a loop is intended to wait for a new signal transition, use an appropriate event control rather than repeatedly testing a condition that remains satisfied.
Similarly, #0 does not advance simulation time. It is not a substitute for waiting on meaningful protocol or clock progress.
Start with the standalone example, verify the parent and worker lifecycles, and then add shared state and nesting one operation at a time.
Frequently Asked Questions
Can You Use Fork Join Inside a SystemVerilog Function?
A SystemVerilog function cannot use blocking fork ... join or fork ... join_any, but it can launch background processes with fork ... join_none. Use a task with fork … join when concurrent work must finish before the operation returns. With fork … join_none , the parent continues without waiting for background work. Do not depend on the background work to calculate the function’s immediate return value.
Is Fork Join Synthesizable?
Treat fork ... join as a testbench and verification construct, not a portable way to synthesize parallel hardware. Express hardware concurrency through module instances, continuous assignments, and procedural RTL constructs supported by the synthesis tool. Concurrent simulation processes do not automatically correspond to separately synthesized hardware.
What Is Time in SystemVerilog?
Time in SystemVerilog is the simulator’s logical timeline, not elapsed wall-clock time. A time variable stores integral simulation-time values, and $time returns the current simulation time scaled to the calling scope’s time unit. timeunit defines that local unit, while timeprecision determines how delay values are rounded.
