Components in a testbench often need to communicate with each other to exchange data and check output values of the design. A few mechanisms allow components or threads to affect each other's control flow:
| Mechanism | What it's for |
|---|---|
| Events | Different threads synchronize with each other via event handles |
| Semaphores | Different threads take turns accessing the same shared resource |
| Mailbox | Threads or components exchange data — data is put into a mailbox and sent |
8 min read | Intermediate Level
What You'll Learn
- What an event, a semaphore, and a mailbox each solve, and how they differ
- How to trigger and wait for an event across two separate processes
- How a semaphore lets only a limited number of processes access a shared resource at once
- How a mailbox passes data safely from one component to another
What Are Events?
An event is a way to synchronize two or more different processes. One process waits for the event to happen while another process triggers it. When the event is triggered, the process waiting for it resumes execution.
1. Create an event using event
event eventA; // Creates an event called "eventA"
2. Trigger an event using the -> operator
->eventA; // Any process that has access to "eventA" can trigger the event
3. Wait for the event to happen
@eventA; // Use "@" to wait for an event
wait (eventA.triggered); // Or use a wait statement with "eventA.triggered"
4. Pass events as arguments to tasks or functions
module tb_top;
event eventA; // Declare an event handle called "eventA"
initial begin
fork
waitForTrigger (eventA); // Task waits for eventA to happen
#5 ->eventA; // Triggers eventA
join
end
// The event is passed as an argument to this task. It simply waits for the event
// to be triggered
task waitForTrigger (event eventA);
$display ("[%0t] Waiting for EventA to be triggered", $time);
wait (eventA.triggered);
$display ("[%0t] EventA has triggered", $time);
endtask
endmodule
Output
[0] Waiting for EventA to be triggered [5] EventA has triggered ncsim: *W,RNQUIE: Simulation is complete.
SystemVerilog Event covers this in more depth.
Quick Check
Q: If ->eventA; fires, and only 5ns later does a separate process execute @eventA;, will that process see the trigger?
Show Answer
No. An event isn't queued or remembered — a trigger only wakes up processes that are actively waiting for it at that exact moment. A process that starts waiting after the trigger already happened will simply keep waiting for the next trigger, if one ever comes.
What's a Semaphore?
Say you wanted to rent a room in a library for a few hours. The admin desk gives you a key to use the room for the time you've requested. After you're done, you return the key, which is then given to someone else who wants to use the same room — this way, two people never use the room at the same time. The key is a semaphore in this context.
A semaphore is used to control access to a resource and is also known as a mutex (mutually exclusive), because only one entity can hold it at a time:
module tb_top;
semaphore key; // Create a semaphore handle called "key"
initial begin
key = new (1); // Create only a single key; multiple keys are also possible
fork
personA (); // personA tries to get the room and puts it back after work
personB (); // personB also tries to get the room and puts it back after work
#25 personA (); // personA tries to get the room a second time
join_none
end
task getRoom (bit [1:0] id);
$display ("[%0t] Trying to get a room for id[%0d] ...", $time, id);
key.get (1);
$display ("[%0t] Room Key retrieved for id[%0d]", $time, id);
endtask
task putRoom (bit [1:0] id);
$display ("[%0t] Leaving room id[%0d] ...", $time, id);
key.put (1);
$display ("[%0t] Room Key put back id[%0d]", $time, id);
endtask
// This person tries to get the room immediately and puts
// it back 20 time units later
task personA ();
getRoom (1);
#20 putRoom (1);
endtask
// This person tries to get the room after 5 time units and puts it back after
// 10 time units
task personB ();
#5 getRoom (2);
#10 putRoom (2);
endtask
endmodule
Output
[0] Trying to get a room for id[1] ... [0] Room Key retrieved for id[1] [5] Trying to get a room for id[2] ... [20] Leaving room id[1] ... [20] Room Key put back id[1] [20] Room Key retrieved for id[2] [25] Trying to get a room for id[1] ... [30] Leaving room id[2] ... [30] Room Key put back id[2] [30] Room Key retrieved for id[1] [50] Leaving room id[1] ... [50] Room Key put back id[1]
key starts with a single available token. personA grabs it immediately at 0ns. When personB tries at 5ns, key.get(1) blocks — there's nothing left to give — until personA returns the key at 20ns, at which point personB's blocked call immediately succeeds. The same pattern repeats when personA's second call tries to get the key at 25ns while personB still holds it, and has to wait until 30ns.
A few things worth noting about semaphores:
- A semaphore object like key is declared and created with
new(); the argument tonew()sets how many keys exist - You get a key with
get(), which blocks (waits) until one is available - You put a key back with
put()
SystemVerilog Semaphore covers this in more depth.
Quick Check
Q: If key = new(2) instead of new(1), would personB's getRoom(2) call at 5ns still have to wait for personA to return anything?
Show Answer
No. With 2 keys available, both personA (at 0ns) and personB (at 5ns) could each get their own key without blocking — only a third concurrent request, with both keys already out, would have to wait.
What's a Mailbox?
A mailbox is like a dedicated channel for sending data between two components. A mailbox can be created and its handle passed to a data generator and a driver: the generator pushes a data object into the mailbox, and the driver retrieves it and drives the signals onto the bus.
// Data packet in this environment
class transaction;
rand bit [7:0] data;
function display ();
$display ("[%0t] Data = 0x%0h", $time, data);
endfunction
endclass
// Generator class - Generate a transaction object and put into mailbox
class generator;
mailbox mbx;
function new (mailbox mbx);
this.mbx = mbx;
endfunction
task genData ();
transaction trns = new ();
trns.randomize ();
trns.display ();
$display ("[%0t] [Generator] Going to put data packet into mailbox", $time);
mbx.put (trns);
$display ("[%0t] [Generator] Data put into mailbox", $time);
endtask
endclass
// Driver class - Get the transaction object from Generator
class driver;
mailbox mbx;
function new (mailbox mbx);
this.mbx = mbx;
endfunction
task drvData ();
transaction drvTrns = new ();
$display ("[%0t] [Driver] Waiting for available data", $time);
mbx.get (drvTrns);
$display ("[%0t] [Driver] Data received from Mailbox", $time);
drvTrns.display ();
endtask
endclass
// Top Level environment that will connect Gen and Drv with a mailbox
module tb_top;
mailbox mbx;
generator Gen;
driver Drv;
initial begin
mbx = new ();
Gen = new (mbx);
Drv = new (mbx);
fork
#10 Gen.genData ();
Drv.drvData ();
join_none
end
endmodule
Output
[0] [Driver] Waiting for available data [10] Data = 0x9d [10] [Generator] Going to put data packet into mailbox [10] [Generator] Data put into mailbox [10] [Driver] Data received from Mailbox [10] Data = 0x9d ncsim: *W,RNQUIE: Simulation is complete.
Drv starts waiting on an empty mailbox at 0ns. Gen creates and randomizes a transaction at 10ns, then puts it into the mailbox — which immediately unblocks Drv's pending get() call. Both trns and drvTrns print the exact same data value, because mbx.get(drvTrns) reassigns the drvTrns handle to point at the very same object Gen put in — it's not a copy.
SystemVerilog Mailbox covers this in more depth.
Quick Check
Q: If Drv were removed from the fork block entirely, so nothing ever called mbx.get(), what would happen to Gen's mbx.put(trns) call?
Show Answer
It would still succeed immediately. A mailbox created with new() and no size argument is unbounded, so put() doesn't need a waiting receiver to succeed — the transaction would simply sit in the mailbox, unread, until something eventually calls get().
Where Are These Used in a Real Testbench?
Events are common for synchronizing on things like reset deassertion or a test phase starting. Semaphores show up wherever multiple components share one physical resource, like a single bus that only one driver can use at a time. Mailboxes are the standard way a generator hands transactions off to a driver — the same producer-consumer pattern UVM's sequencer-to-driver connection is built on.
Common Beginner Mistakes
Mistake #1: Assuming an event trigger is remembered if no one's waiting yet
As the Quick Check above shows, a trigger that fires with nobody currently waiting on it is simply lost. Why? Events aren't queued the way mailbox data is — if the timing between the trigger and the wait doesn't line up, the waiting process can end up stuck indefinitely.
Mistake #2: Forgetting to put a semaphore key back
Every get() needs a matching put(), or the key never becomes available again. Why? If a task takes a key and then exits early (through an error path, for instance) without calling put(), every other process waiting for that same key blocks forever — a classic deadlock.
Mistake #3: Assuming mailbox.get() always blocks
get() only blocks when the mailbox is currently empty. Why? If data is already sitting in the mailbox when get() is called, it returns immediately — the blocking behavior only kicks in when there's genuinely nothing there yet.
Practice Exercise
Challenge: Give the Library Two Rooms
Using the semaphore example above, change the library to have 2 rooms available instead of 1, and add a third person, personC, who tries to get a room at time 0, alongside personA.
Hint
Only the argument to new() and the fork list need to change — the getRoom/putRoom tasks themselves don't need any modification.
Solution
module tb_top;
semaphore key;
initial begin
key = new (2); // Two rooms available now
fork
personA ();
personC (); // Tries to get a room at time 0, alongside personA
personB ();
#25 personA ();
join_none
end
// getRoom, putRoom, personA, personB tasks unchanged
task personC ();
getRoom (3);
#15 putRoom (3);
endtask
endmodule
With 2 keys available, both personA and personC can get a room at 0ns without either one blocking — only once both keys are out does a third concurrent request have to wait, exactly like personB did against a single key in the original example.
Summary
In this tutorial, you learned:
- Events synchronize two or more processes — one triggers with
->, another waits with@orwait(event.triggered), but a trigger with nobody waiting is simply lost - Semaphores control access to a shared resource using a limited number of keys, obtained with
get()and returned withput() - Mailboxes pass data between components —
put()andget()hand a class handle across, not a copy of the object mailbox.get()only blocks when the mailbox is empty; a semaphore'sget()only blocks when no key is currently available- Each mechanism solves a different coordination problem — see SystemVerilog Event, SystemVerilog Semaphore, and SystemVerilog Mailbox for the full depth on each
Before writing any coverage code, it helps to know what you're actually trying to measure. This article covers what functional coverage means in practice, where it tends to fall short, and the three pieces — covergroup, coverpoint, and bins — that every coverage model is built from.
7 min read | Intermediate Level
What You'll Learn
- What functional coverage measures, and why it matters in constrained-random verification
- Why functional coverage is only as complete as the code written for it
- The basic building blocks:
covergroup,coverpoint, and bins - How to control when and under what conditions a covergroup samples
What Is Functional Coverage?
Functional coverage is a measure of what functionalities or features of the design have been exercised by the tests. This is especially useful in constrained random verification (CRV), where it tells you what features a set of tests in a regression has actually covered — rather than just trusting that "enough" random stimulus was generated.
What Are Its Limitations?
Functional coverage is only as good as the code written for it. Say a design document lists 10 features, and 3 of them were overlooked, missed, or simply not known about when the coverage model was written — you'll only end up with coverage code for the other 7. If all 7 are hit during testing, it's easy to conclude the design is fully covered, when in reality 3 features were never measured at all. Make sure everything relevant from the design specification actually makes it into the functional coverage block.
How Is Functional Coverage Done in SystemVerilog?
The idea is to sample interesting variables in the testbench and analyze whether they've reached a certain set of values:
module test;
bit [3:0] mode;
bit [1:0] key;
// Other testbench code
endmodule
mode can take 16 values (it's 4 bits wide), while key can take 4 values (2 bits wide). If something monitors these two variables during simulation and reports which values were actually exercised, you'll know whether a test covered a particular feature or not. Simulators typically let you dump these coverage details to a file for review after the run finishes, and you can merge coverage files from different tests into a single database and review them as a whole — if test A covered feature X and test B covered feature Y, the merged database shows both X and Y as covered.
The Building Blocks: Covergroup, Coverpoint, and Bins
Three pieces work together to turn "monitor these variables" into an actual coverage measurement:
- A coverpoint tracks one variable or expression and records which of its legal values have actually occurred
- A covergroup is the container that groups one or more coverpoints together, along with the event that decides when they're sampled
- A bin represents one value, or a group of values, that a coverpoint is tracking — by default, SystemVerilog creates one automatic bin per legal value
Default bins aren't always what you want. A bin can also be defined explicitly to cover a single value or a whole range at once:
coverpoint mode {
bins featureA = {0};
bins featureB = {[1:3]};
}
Here, featureA is a single bin that's hit only when mode equals 0, while featureB is one bin covering the whole range 1 through 3. SystemVerilog also supports array bins (one bin per value across a range), a catch-all default bin, and more — SystemVerilog Coverpoint Bins covers all of that in depth, and SystemVerilog Covergroup and Coverpoint walks through a complete worked example with actual coverage percentages.
Quick Check
Q: A coverpoint has no custom bins defined for a 2-bit variable. How many bins does it get by default?
Show Answer
4 — one automatic bin per legal value, since a 2-bit variable has exactly 4 possible values (0 through 3).
Why Are Coverage Metrics Missing From My Simulation?
By default, most simulators don't dump coverage data unless you ask for it. You'll need to enable a tool-vendor-specific command-line switch to dump coverage details, then open a coverage viewer tool (such as Cadence ICCR/IMC) to load and review the resulting coverage dump file.
How Do You Control When a Covergroup Samples?
There are two ways to trigger coverage collection in a covergroup.
The first is to call the covergroup instance's built-in sample() method yourself, wherever in your code makes sense:
class myCov;
covergroup CovGrp;
...
endgroup
function new ();
CovGrp = new; // Create an instance of the covergroup
endfunction
endclass
module tb_top;
myCov myCov0 = new (); // Create an instance of the class
initial begin
myCov0.CovGrp.sample ();
end
endmodule
The second is to specify an event when the covergroup is declared, and let it sample automatically every time that event occurs:
covergroup CovGrp @ (posedge clk); // Sample coverpoints at posedge clk
covergroup CovGrp @ (eventA); // eventA can be triggered with ->eventA;
How Do You Conditionally Enable Coverage?
There are two ways to conditionally enable or disable coverage collection.
The first is the iff construct, attached directly to a coverpoint so it only samples when a condition holds:
covergroup CovGrp;
coverpoint mode iff (!_if.reset) {
// bins for mode
}
endgroup
The second is to call the covergroup instance's built-in start() and stop() functions to toggle sampling for the whole group:
CovGrp cg = new;
initial begin
#1 _if.reset = 0;
cg.stop ();
#10 _if.reset = 1;
cg.start();
end
Where Does This Fit Into a Verification Flow?
Coverage-driven verification uses exactly these mechanisms to decide where to focus effort next — a regression's merged coverage database highlights which bins are still unhit, pointing directly at the scenarios that need more targeted random constraints or a dedicated directed test, rather than just running more of the same stimulus and hoping for the best.
Common Beginner Mistakes
Mistake #1: Treating full coverage code as full feature coverage
Hitting every bin you've written doesn't mean every feature in the design specification has been tested. Why? Coverage can only measure what someone remembered to write a coverpoint for — features that were missed when the coverage model was written stay invisible no matter how many tests you run.
Mistake #2: Forgetting to guard coverage during reset or invalid states
Without an iff condition or a stop()/start() pair around reset, a coverpoint happily samples whatever garbage or default values exist during reset. Why? This can pollute your coverage results with bins that were only ever hit by an uninitialized or reset value, not by any meaningful stimulus.
Mistake #3: Assuming a covergroup samples automatically with no event specified
If a covergroup is declared without a sampling event, nothing samples it unless you explicitly call sample() yourself. Why? It's easy to declare a covergroup, forget the @ (event) clause, and never notice coverage staying at 0% because there's no error — it's simply never being sampled.
Practice Exercise
Challenge: Split key Into Two Custom Bins
Instead of letting key use its 4 default automatic bins, write a bins block that groups it into two custom bins: low for values 0 and 1, and high for values 2 and 3.
Hint
Use the same bins name = {range}; pattern shown for featureA and featureB above.
Solution
coverpoint key {
bins low = {[0:1]};
bins high = {[2:3]};
}
This replaces the 4 default automatic bins with just 2 custom ones, so key reaches 100% coverage as soon as at least one value from each half of its range has been seen — useful when you only care about which half of the range was exercised, not every individual value.
Summary
In this tutorial, you learned:
- Functional coverage measures what features of a design have actually been exercised by testing, which is especially useful in constrained-random verification
- Coverage is only as complete as the code written for it — a missed feature in the coverage model stays invisible even at 100% reported coverage
- A coverpoint tracks a variable or expression, a covergroup groups coverpoints together, and a bin represents the values being tracked
- A covergroup samples either through an explicit
sample()call or automatically via a declared event iff, and thestart()/stop()functions, let you conditionally control when coverage is collected
SystemVerilog offers a lot of flexibility for building data structures through its different array types. Picking the right one matters: a testbench scoreboard, a sparse lookup table, and a fixed-width register file all call for a different kind of array, and each one is recognized by a distinct declaration syntax.
This article gives a quick overview of the four array categories — static, dynamic, associative, and queue — so you can recognize each one and know where to dig deeper.
6 min read | Intermediate Level
What You'll Learn
- The four array categories in SystemVerilog and how to recognize each one
- How static arrays split further into packed and unpacked forms
- When to reach for a dynamic array, an associative array, or a queue
- Where to go for a deeper dive into each array type
Static Arrays
A static array is one whose size is known before compilation. The example below declares an 8-bit wide static array, assigns it a value, and iterates over it to print each bit.
module tb;
bit [7:0] m_data; // A vector or 1D packed array
initial begin
// 1. Assign a value to the vector
m_data = 8'hA2;
// 2. Iterate through each bit of the vector and print value
for (int i = 0; i < $size(m_data); i++) begin
$display ("m_data[%0d] = %b", i, m_data[i]);
end
end
endmodule
Output
ncsim> run m_data[0] = 0 m_data[1] = 1 m_data[2] = 0 m_data[3] = 0 m_data[4] = 0 m_data[5] = 1 m_data[6] = 0 m_data[7] = 1 ncsim: *W,RNQUIE: Simulation is complete.
Static arrays are further categorized into packed and unpacked arrays, based on whether the dimensions are declared before or after the variable name.
bit [2:0][7:0] m_data; // Packed
bit [15:0] m_mem [10:0]; // Packed + Unpacked
Learn more about SystemVerilog Packed Arrays
Unpacked arrays may be fixed-size arrays, dynamic arrays, associative arrays, or queues — the rest of this article covers those non-fixed-size forms.
Learn more about SystemVerilog Unpacked Arrays
Static arrays (packed or unpacked-fixed-size) are the default choice for RTL and for any testbench structure whose size you already know, like a fixed-depth register file or a bus with a known number of lanes.
Quick Check
Q: Is bit [15:0] m_mem [10:0]; a packed array, an unpacked array, or both?
Show Answer
Both. [15:0] is written before the name, so it's a packed dimension (each element is a 16-bit vector). [10:0] is written after the name, so it's an unpacked dimension (11 separate elements).
Dynamic Arrays
A dynamic array is one whose size isn't known at compile time — it's allocated and resized during runtime instead. It's easily recognized by its empty square brackets [ ].
int m_mem []; // Dynamic array, size unknown but it holds integer values
Learn more about SystemVerilog Dynamic Arrays
Dynamic arrays are a good fit when you know you're storing a list of same-typed elements, but the count depends on something learned at runtime — for example, the number of packets to send for a given test scenario.
Associative Arrays
An associative array stores content against a key rather than a sequential index. It's recognized by a data type sitting inside the square brackets — that type is the key.
int m_data [int]; // Key is of type int, and data is also of type int
int m_name [string]; // Key is of type string, and data is of type int
m_name ["Rachel"] = 30;
m_name ["Orange"] = 2;
m_data [32'h123] = 3333;
Learn more about SystemVerilog Associative Arrays
Associative arrays are the natural fit for sparse data, like tracking scoreboard entries by transaction ID or counting coverage hits by an address that could be anywhere in a huge memory space, without allocating storage for every possible index.
Quick Check
Q: In int m_name [string];, what is string — the data type or the key type?
Show Answer
The key type. The type inside the square brackets always describes the key used to look up an entry; the type before the variable name (int here) is the data stored at each key.
Queues
A queue lets you push data in and pop data out from either end. It's recognized by the $ symbol inside the square brackets.
int m_queue [$]; // Unbound queue, no size
m_queue.push_back(23); // Push into the queue
int data = m_queue.pop_front(); // Pop from the queue
Learn more about SystemVerilog Queues
Queues are the go-to structure for scoreboards, transaction pipelines, and any place you need strict ordering with fast insertion and removal at either end — something a plain dynamic array doesn't give you as conveniently.
Common Mistakes
Mistake #1: Reaching for a static array when the size isn't actually known
Declaring int m_mem [100]; "just to be safe" wastes storage if you rarely need that many entries, and still fails if you occasionally need more than 100. If the count depends on runtime conditions, use a dynamic array or a queue instead of guessing a fixed size.
Mistake #2: Assuming an associative array preserves insertion order
Associative arrays are indexed by key, not by position, so iterating with foreach does not guarantee the order entries were added in. If order matters, use a queue instead.
Mistake #3: Confusing the key type with the data type
In int m_name [string];, it's easy to misread which side is the key. The type before the name (int) is what's stored; the type inside the brackets (string) is what you index with.
Mistake #4: Popping from an empty queue
Calling pop_front() or pop_back() on an empty queue is not a runtime error — it returns the type's default value, leaves the queue unchanged, and may just issue a warning. That's easy to rely on by accident, so it's still worth checking m_queue.size() (or tracking expected pushes/pops) before popping in code that isn't guaranteed to have an entry waiting, since a silently-returned default value can mask a real bug.
Practice Exercise
Challenge: Pick the Right Array Type
You're writing a testbench component that tracks outstanding read requests by their unique transaction ID (a random 32-bit value), so you can look up and remove a request once its response arrives. Which array type fits best, and how would you declare it?
Hint
Transaction IDs are random 32-bit values, not a small sequential range, and you need to look one up directly rather than scan through a list.
Solution
// Associative array: key = transaction ID, data = the outstanding request
my_transaction pending_reqs [bit [31:0]];
// Add an outstanding request
pending_reqs[tx_id] = req;
// Look up and remove it once the response arrives
if (pending_reqs.exists(resp_id)) begin
my_transaction original_req = pending_reqs[resp_id];
pending_reqs.delete(resp_id);
end
An associative array is the right choice here: transaction IDs are sparse (not a small, dense 0..N range), and you need direct key-based lookup rather than positional access — exactly what a static or dynamic array isn't built for.
Summary
In this tutorial, you learned:
- Static arrays have a size known at compile time, and split further into packed and unpacked forms
- Dynamic arrays use empty
[ ]brackets and are sized at runtime - Associative arrays use a data type inside
[ ]to represent the key, ideal for sparse or non-sequential data - Queues use
[$]and support fastpush_back()/pop_front()-style insertion and removal at either end - Choosing the right array type up front avoids wasted storage, missing-order bugs, and runtime errors later on
Wiring a design's ports directly to a handful of testbench variables works fine for a simple design like a binary counter. But real designs have hundreds of ports, dozens of test scenarios, and teams of engineers who all need to reuse the same verification code across projects. A single, tangled testbench module doesn't hold up at that scale. This article breaks a testbench down into the standard components that make it modular, scalable, and reusable.
9 min read | Beginner Level
What You'll Learn
- Why a simple, directly-wired testbench doesn't scale to real designs
- The standard components of a SystemVerilog testbench and what each one does
- How stimulus flows from generator to DUT, and results flow back to the scoreboard
- Why environments and tests are kept as separate, reusable layers
What Is the Purpose of a Testbench?
A testbench is the environment that lets you verify a design's functionality through simulation. It's a container where the design is placed and driven with input stimulus. At a high level, a testbench needs to:
- Generate different types of input stimulus
- Drive the design's inputs with that stimulus
- Let the design process the input and produce an output
- Check the output against expected behavior to catch functional defects
- If a bug is found, fix the design and repeat until no defects remain
Components of a Testbench
Wiring a design's ports directly to testbench variables works for a small example, but it isn't modular, scalable, or reusable. A proper testbench splits these responsibilities across dedicated components:
| Component | Description |
|---|---|
| Generator | Generates different input stimulus to be driven to the DUT |
| Interface | Contains design signals that can be driven or monitored |
| Driver | Drives the generated stimulus to the design |
| Monitor | Watches the design's input-output ports to capture design activity |
| Scoreboard | Checks output from the design against expected behavior |
| Environment | Contains the generator, driver, monitor and scoreboard. The interface itself is instantiated outside it, in the top-level module, and the environment only holds a virtual interface handle to it |
| Test | Contains the environment, configured with specific settings |
What Is DUT?
DUT stands for Design Under Test — the hardware design written in Verilog, SystemVerilog, or VHDL. The term DUT is typically used in post-silicon validation, once the chip has been fabricated. In pre-silicon verification, the same design is often called DUV (Design Under Verification) instead.
// All verification components are placed in this top testbench module
module tb_top;
// Declare variables that need to be connected to the design instance
// These variables are assigned some values that in turn gets transferred to
// the design as inputs because they are connected with the ports in the design
reg clk;
wire en;
wire wr;
wire data;
// Instantiate the design module and connect the variables declared above
// with the ports in the design
design myDsn ( .clk (clk),
.en (en),
.wr (wr),
. ...
.rdata);
// Develop rest of the testbench and write stimulus that can be driven to the design
endmodule
Click here for a complete SystemVerilog testbench example !
What Is an Interface?
If a design has hundreds of port signals, connecting, maintaining, and reusing them individually gets cumbersome fast. Instead, all of the design's input-output ports are bundled into a single container called an interface. The design is then driven and observed entirely through this interface rather than through loose, individually-declared signals.
What Is a Driver?
The driver is the component that does the actual pin-wiggling on the DUT, through tasks defined in the interface. When the driver needs to send input values to the design, it simply calls a pre-defined task in the interface — it doesn't need to know the timing relationships between signals, since that timing is already encoded inside the task. This abstraction is what makes testbenches flexible and scalable: if the interface's timing changes later, the driver still calls the same task and doesn't need to be rewritten.
How Does the Driver Know What to Drive?
The generator creates valid data transactions and sends them to the driver, which simply drives whatever data it receives through the interface. These transactions are implemented as class objects. The driver's job is to take a data object from the generator and translate it into signal-level activity the DUT can understand.
Quick Check
Q: If the driver doesn't decide what data to send to the DUT, which component does?
Show Answer
The generator. It creates the data transactions; the driver's only job is to translate and drive whatever it's handed.
Why Is a Monitor Required?
Driving data into the DUT is only half the job — the real goal is verifying the design's behavior. The DUT processes input data and produces output on its pins. The monitor passively observes this processed data, converts it into a data object, and sends it to the scoreboard for checking.
Common Misconception: The monitor never drives any signal. It's a purely passive, observe-only component — driving is strictly the driver's job.
What Is the Purpose of a Scoreboard?
The scoreboard typically contains a reference model that mimics the DUT's expected behavior. The same input sent to the DUT is also sent to this reference model. If the DUT has a functional bug, its output won't match the reference model's output. Comparing the two tells you whether the design has a functional defect — and this comparison is usually done inside the scoreboard.
Where Are These Components Used?
UVM (Universal Verification Methodology) formalizes exactly these roles into base classes — uvm_driver, uvm_monitor, uvm_scoreboard, uvm_env, and uvm_test — so verification teams working on processors, GPUs, or SoC sub-blocks build on a standardized version of this same architecture rather than reinventing it each time.
Why Is an Environment Required?
The environment bundles the generator, driver, monitor, and scoreboard together into one reusable unit. This makes verification more flexible and scalable, since the same environment can be reused across many tests — and even future projects — without being rebuilt each time.
What Does the Test Do?
The test instantiates the environment and configures it however that particular test scenario needs. A real project might have thousands of tests, and it wouldn't be feasible to directly modify the environment for each one. Instead, the environment exposes knobs and parameters that each test can tweak, giving the test writer control over stimulus generation without touching the environment's internals.
This is the layering that makes verification reusable: the environment defines reusable structure, and each test only supplies configuration on top of it.
If you only had to verify a simple digital counter with 50 lines of RTL, wiring signals directly (as in the intro article) would honestly be enough. But as design complexity grows, so does the need for this layered abstraction.
What Are Abstraction Levels?
Earlier examples toggled the design using individual signal assignments directly:
#5 resetn <= 0;
#20 resetn <= 1;
Instead, wrapping these two lines in a task called apply_reset creates a reusable component that hides the details of exactly which signals get asserted and for how long:
module tb_top;
bit resetn;
task apply_reset ();
#5 resetn <= 0;
#20 resetn <= 1;
endtask
initial begin
apply_reset();
end
endmodule
This is exactly the kind of abstraction a testbench should provide — hiding the "how" so the test writer can focus on "when" and "why" a task should be used. In practice, a test writer mostly calls tasks and configures the environment, rather than writing raw signal assignments.
Click here for another complete SystemVerilog testbench example !
Common Beginner Mistakes
Mistake #1: Confusing the generator with the driver.
The generator decides what data to send; the driver decides how to physically wiggle pins to send it. Beginners often assume the driver also creates the data — it doesn't, it only translates and drives what the generator hands it.
Mistake #2: Putting signal timing (when to sample or drive) directly in the driver or test instead of inside interface tasks.
If timing details leak outside the interface, changing the DUT's timing later means changing every place that touches those signals, instead of just the interface task.
Mistake #3: Treating the environment and the test as the same thing.
The environment holds the reusable verification components; the test only configures and runs that environment with specific settings. One environment is typically reused across many tests.
Practice Exercise
Challenge: Map the Components
Sketch (on paper or in a text file) the path data takes through a testbench for a single transaction, from stimulus creation to pass/fail result. Label each step with the component responsible: Generator, Driver, Interface, DUT, Monitor, Scoreboard.
Hint
There are two directions of data flow to trace separately: one path drives data into the DUT, and a second path carries the DUT's response back out for checking.
Solution
Drive path: Generator creates a transaction → Driver receives it → Driver calls an interface task → Interface drives DUT input pins.
Check path: DUT produces output pins → Interface signals are observed → Monitor samples the activity and builds a data object → Scoreboard compares it against its reference model's expected result.
Summary
In this tutorial, you learned:
- A directly-wired testbench doesn't scale — real testbenches split responsibilities across dedicated components
- The Generator creates stimulus, the Driver applies it, and the Interface bundles the signals in between
- The Monitor passively observes DUT activity and reports it to the Scoreboard for checking
- The Environment bundles all verification components into one reusable unit
- The Test configures and runs an Environment with specific settings, without modifying the Environment itself
disable fork and wait fork both act on every process spawned by the current process at once — there's no way to target just one of them. SystemVerilog's built-in process class fills that gap: it gives you a handle to one specific process, letting you check its status and control it individually, without touching anything else running alongside it.
7 min read | Intermediate Level
What You'll Learn
- What the
processclass is, and howprocess::self()gives you a handle to the currently executing process - The different states a process can be in, and how to check them with
status() - How to suspend, resume, and kill one specific process without affecting any others
- How
process::kill()differs fromdisable forkin scope
What Is the process Class?
Every thread — an initial or always block, or a thread spawned by fork — has a built-in process object associated with it automatically. You can't create a process object yourself with new(); SystemVerilog creates one internally whenever a process is spawned. To get a handle to a process, you call the static method process::self() from within that process — it always returns a handle to whichever process is calling it, never to some other thread.
Process States
A process object's status() method returns one of five states:
| State | Meaning |
|---|---|
| RUNNING | Currently executing, not blocked |
| WAITING | Blocked on an event, delay, or other timing control |
| SUSPENDED | Explicitly paused by a call to suspend() |
| FINISHED | Completed normally |
| KILLED | Forcibly terminated by kill() or disable |
Basic Syntax
The built-in process class provides these members:
class process;
typedef enum { FINISHED, RUNNING, WAITING, SUSPENDED, KILLED } state;
static function process self(); // handle to the calling process
function state status(); // current state of this process
function void suspend(); // pause this process
function void resume(); // resume a suspended process
function void kill(); // terminate this process and its descendants
task await(); // wait for this process to finish
function void srandom (int seed); // reseed this process's own random generator
function string get_randstate(); // save this process's random state
function void set_randstate (string state); // restore a previously saved random state
endclass
Parameters:
self()— a static method, called asprocess::self(), with no arguments- All other methods are called on a
processhandle you've already obtained, such asmy_proc.status()
A Complete Example
A common pattern is to spawn a background task with fork...join_none, capture its own process handle from inside itself, and store that handle somewhere the rest of the code can reach:
module tb;
process bg_proc;
task background_task ();
bg_proc = process::self(); // capture this task's own process handle
forever begin
#10 $display ("[%0t] Background task running", $time);
end
endtask
initial begin
fork
background_task ();
join_none
#25;
$display ("[%0t] Status before kill: %s", $time, bg_proc.status().name());
bg_proc.kill();
$display ("[%0t] Background task killed", $time);
#20 $finish;
end
endmodule
background_task captures its own handle into bg_proc the moment it starts, then loops forever, printing every 10ns. The main thread, meanwhile, continues immediately after join_none, waits 25ns, then checks bg_proc's status. At that point, background_task has already printed at 10ns and 20ns, and is currently blocked inside its third #10 delay — so status() returns WAITING. Calling bg_proc.kill() right after terminates it for good, so it never reaches its next scheduled print at 30ns.
Quick Check
Q: In the example above, what would bg_proc.status() return if it were checked at exactly 10ns, in the same instant background_task executes its $display statement?
Show Answer
RUNNING — at that exact moment it's actively executing a statement, not blocked on anything. It only becomes WAITING again once it re-enters the #10 delay on the next iteration of the forever loop.
Suspending and Resuming a Process
suspend() pauses a process without terminating it, and resume() lets it continue from exactly where it left off:
initial begin
process p;
fork
begin
p = process::self();
forever #5 $display ("[%0t] Tick", $time);
end
join_none
#12 p.suspend(); // pause the ticking process mid-cycle
#20 p.resume(); // let it continue from where it left off
end
Unlike kill(), suspend() doesn't lose the process's place — once resume() is called, it picks back up exactly where it was paused.
process vs disable fork: Which Should You Use?
disable fork terminates every active descendant of the calling process at once — a blunt, all-or-nothing tool. A process handle lets you target one specific process instead, which matters when a single parent has spawned several independent background threads and you only want to stop one of them. That said, kill() isn't perfectly surgical either: killing a process also terminates all of its own descendant processes, so it's scoped to one process's subtree, not just that single process in isolation.
Where Is the process Class Used?
The process class is useful whenever a testbench spawns several independent long-running background components — multiple monitors, multiple scoreboards — and needs to stop or pause just one of them based on some runtime condition, without disturbing the others still running alongside it.
Common Beginner Mistakes
Mistake #1: Calling process::self() from the wrong place
process::self() only ever returns a handle to whichever process is calling it. Why? Calling it from the main thread doesn't give you a handle to a thread you forked elsewhere — to get a handle to a specific forked thread, that thread has to call process::self() on itself, typically as its very first statement.
Mistake #2: Assuming kill() leaves a process's own children running
Killing a process also terminates every one of its own descendant processes. Why? If that process had itself forked off further threads, expecting them to keep running after the parent is killed will be wrong — they're terminated right along with it.
Mistake #3: Trying to construct a process object with new()
process objects can't be created manually. Why? SystemVerilog creates one internally whenever a thread is spawned; attempting process p = new(); yourself is a compile-time error — the only way to obtain a handle is process::self(), called from inside the process you want a handle to.
Practice Exercise
Challenge: Kill One of Two Background Monitors
Fork two independent background tasks, each printing a different message every 5ns via a forever loop, each capturing its own process handle. After 22ns, kill only the first one and let the second keep running.
Hint
Each task needs its own process variable to store its own handle — don't reuse a single variable for both.
Solution
module tb;
process proc_a, proc_b;
task monitor_a ();
proc_a = process::self();
forever #5 $display ("[%0t] Monitor A", $time);
endtask
task monitor_b ();
proc_b = process::self();
forever #5 $display ("[%0t] Monitor B", $time);
endtask
initial begin
fork
monitor_a ();
monitor_b ();
join_none
#22 proc_a.kill();
$display ("[%0t] Monitor A killed, Monitor B still running", $time);
#20 $finish;
end
endmodule
Because each task captures its handle into its own separate variable (proc_a and proc_b), killing proc_a only stops Monitor A — Monitor B keeps printing every 5ns, completely unaffected.
Summary
In this tutorial, you learned:
- Every thread has a built-in
processobject;process::self(), called from within a process, returns a handle to it - A process can be
RUNNING,WAITING,SUSPENDED,FINISHED, orKILLED, checked viastatus() suspend()andresume()pause and continue a process without losing its place;kill()terminates it permanentlykill()also terminates all of that process's own descendant processes, not just the process itself- Unlike
disable fork, which acts on every descendant of the calling process at once, aprocesshandle lets you target one specific process individually
Continuing the Threads & Processes Chapter
See SystemVerilog disable fork join for terminating every spawned process at once, and SystemVerilog wait fork for waiting on all of them instead of just one.
Quiz
No quiz questions available for this article.