SystemVerilog arrays store many values in a single variable. The foreach loop is built just for walking through them, and it is the simplest way to do so. You don't declare an index variable or work out the array size. foreach declares the loop variable for you and steps it through every valid index, so you can never index past the end of the array.
7 min read | Intermediate Level
What You'll Learn
- The syntax of
foreachfor one-dimensional and multidimensional arrays - The order in which
foreachvisits indices, which is not always from 0 - How
foreachworks with dynamic arrays, queues and associative arrays in testbenches - When
foreachcan be used in synthesizable RTL
Syntax
When the loop body has more than one statement, wrap them in begin and end, as with any other procedural block.
foreach(<variable>[<iterator>])
// Single statement
foreach(<variable>[<iterator>]) begin
// Multiple statements
end
- variable: the array to walk through. It can be a fixed-size, dynamic, associative or queue array.
- iterator: the loop variable name, which can be any identifier. For a multidimensional array, list one name per dimension, separated by commas:
[i, j].
The loop variable is declared automatically. It exists only inside the loop and is read-only, so you cannot assign to it.
Example #1: Single-Dimensional Arrays
module tb;
int array[5] = '{1, 2, 3, 4, 5};
int sum;
initial begin
// Here, "i" is the iterator and can be named as anything you like
// Iterate through each element from index 0 to end using a foreach
// loop.
foreach (array[i])
$display ("array[%0d] = %0d", i, array[i]);
// Multiple statements in foreach loop requires begin end
// Here, we are calculating the sum of all numbers in the array
// And because there are 2 statements within foreach there should
// be a begin-end
foreach (array[l_index]) begin
sum += array[l_index];
$display ("array[%0d] = %0d, sum = %0d", l_index, array[l_index], sum);
end
end
endmodule
ncsim> run array[0] = 1 array[1] = 2 array[2] = 3 array[3] = 4 array[4] = 5 array[0] = 1, sum = 1 array[1] = 2, sum = 3 array[2] = 3, sum = 6 array[3] = 4, sum = 10 array[4] = 5, sum = 15 ncsim: *W,RNQUIE: Simulation is complete.
For an array declared as int array[5], which is shorthand for [0:4], the foreach loop does the same job as this for loop:
for (int i = 0; i < $size(array); i++) begin
// Statements inside the for loop
end
The two are only equivalent for arrays whose indices start at 0 and count up. The next section shows why.
Iteration Order
foreach does not always start at 0. It goes from the left bound of the declared range to the right bound:
| Array type | Order of indices |
|---|---|
Fixed-size, written [N] or [0:N-1] | 0 up to N-1 |
Fixed-size, written [N-1:0] (including packed vectors) | N-1 down to 0 |
| Dynamic array, queue | 0 up to size-1 |
| Associative array | Ascending order of the index (key) |
module tb;
bit [3:0] nibble = 4'b0110; // packed vector, declared [3:0]
int arr [3:0]; // unpacked array, declared high-to-low
initial begin
foreach (nibble[i]) // i = 3, 2, 1, 0
$display ("nibble[%0d] = %0b", i, nibble[i]);
foreach (arr[i]) // i = 3, 2, 1, 0
$display ("arr index %0d", i);
end
endmodule
Both loops count down from 3 to 0, because both arrays are declared with the larger number on the left.
Quick Check
Q: In what order does foreach (mem[a]) visit indices if mem is declared as logic [7:0] mem [1:4]?
Show Answer
1, 2, 3, 4. The unpacked range is [1:4], so iteration runs from the left bound 1 to the right bound 4. The packed width [7:0] of each element is not part of the loop.
Example #2: Multidimensional Arrays
The example below walks a 5x2 array by nesting one foreach inside another.
module tb;
int md_array [5][2] = '{'{1,2}, '{3,4}, '{5,6}, '{7,8}, '{9,10}};
initial begin
// First iterate through the first dimension using "i"
foreach (md_array[i])
// For each element in first dimension "i", iterate through the
// second dimension using "j"
foreach (md_array[i][j])
$display("md_array[%0d][%0d] = %0d", i, j, md_array[i][j]);
end
endmodule
ncsim> run md_array[0][0] = 1 md_array[0][1] = 2 md_array[1][0] = 3 md_array[1][1] = 4 md_array[2][0] = 5 md_array[2][1] = 6 md_array[3][0] = 7 md_array[3][1] = 8 md_array[4][0] = 9 md_array[4][1] = 10 ncsim: *W,RNQUIE: Simulation is complete.
The IEEE 1800 standard defines a shorter form: one foreach with a comma-separated list of loop variables. The first variable walks the first dimension and the second walks the second, which gives the same nested order and the same output as above. This is the most portable form across simulators.
module tb;
int md_array [5][2] = '{'{1,2}, '{3,4}, '{5,6}, '{7,8}, '{9,10}};
initial begin
// i walks the first dimension (outer), j walks the second (inner)
foreach (md_array[i, j])
$display ("md_array[%0d][%0d] = %0d", i, j, md_array[i][j]);
end
endmodule
To skip a dimension, leave its slot empty. foreach (md_array[, j]) loops over the second dimension only.
Using foreach in Verification
foreach is most useful with arrays whose size changes at run time. With dynamic arrays and queues it adapts to the current size automatically. With associative arrays it visits only the keys that actually exist.
module tb;
int pkt_count [string]; // associative array indexed by a string
initial begin
pkt_count["write"] = 7;
pkt_count["read"] = 12;
pkt_count["idle"] = 30;
// Visits existing keys in ascending order: "idle", "read", "write"
foreach (pkt_count[key])
$display ("%s : %0d", key, pkt_count[key]);
end
endmodule
For an associative array the loop variable takes the index type, a string here. For fixed-size arrays, dynamic arrays and queues it is an int.
Where is foreach used in verification?
Scoreboards keep expected transactions in queues or associative arrays keyed by address or ID, and use foreach at the end of a test to report anything never matched. Constraint blocks also use foreach to constrain every element of a randomized array, for example to keep every byte of a payload within a legal range.
Using foreach in Digital Design
foreach over a fixed-size array is supported by most current synthesis tools. Its iteration count is known at elaboration time, so it unrolls just like a for loop with constant bounds.
Because the bounds come from the array declaration, a foreach loop resizes itself when a parameter changes the array width. The bit-reversal block below compiles to pure wiring, with no logic gates.
module bit_reverse (
input logic [7:0] din,
output logic [7:0] dout
);
always_comb begin
foreach (din[i]) // i = 7 down to 0, from the [7:0] declaration
dout[i] = din[7 - i]; // swap bit order: dout[7] = din[0], ...
end
endmodule
Dynamic arrays, queues and associative arrays are not synthesizable, so foreach over them is testbench-only. In RTL, use it only on fixed-size packed or unpacked arrays.
Common Beginner Mistakes
Mistake #1: Assuming the index always starts at 0
For logic [7:0] data, foreach (data[i]) visits 7 first and 0 last. Why? foreach follows the declared range from left to right. Order matters whenever the body depends on earlier iterations, such as a running sum written to an output, or "first match wins" logic.
Mistake #2: Assigning to the loop variable
Wrong: foreach (arr[i]) begin if (skip) i++; ... end
Right: foreach (arr[i]) begin if (skip) continue; ... end
Why? foreach loop variables are read-only, so the first version will not compile. Use continue to skip an element.
Mistake #3: Changing the array size inside the loop
Calling q.delete(i) or q.push_back() on the queue being walked gives undefined results. Why? The standard does not define what happens when a dynamically sized array changes size during a foreach. Collect the indices to delete in the loop and remove them afterwards, or use a while loop that checks q.size() on every pass.
Practice Exercise
Challenge: Find the largest value
Given a queue int data[$] = {12, 45, 7, 33};, use foreach to find the largest value and print it.
Hint
Start with max_val set to the first element, then compare every element against it inside the loop.
Solution
module tb;
int data[$] = {12, 45, 7, 33};
int max_val;
initial begin
max_val = data[0]; // start with the first element
foreach (data[i])
if (data[i] > max_val)
max_val = data[i]; // keep the larger value
$display ("max = %0d", max_val); // prints: max = 45
end
endmodule
foreach follows the queue's current size, so the same code works whether the queue holds 4 elements or 4,000.
Summary
In this tutorial, you learned:
foreachwalks every index of an array without a manual index variable or size check- The loop variable is declared automatically, is local to the loop, and is read-only
- Iteration runs from the left bound to the right bound, so
[7:0]arrays are visited from 7 down to 0 - Multidimensional arrays use a comma-separated list such as
[i, j], and a slot can be left empty to skip a dimension - Associative arrays are visited in ascending key order, only for keys that exist
foreachover fixed-size arrays is synthesizable in most tools; over dynamic arrays it is testbench-only
A for loop in SystemVerilog repeats a set of statements as long as a condition stays true. The starting value, the exit condition and the step are all written in the loop header. That makes it the most common loop in both RTL design and testbenches. When the body has more than one statement, wrap them in begin and end, just like any other procedural block.
7 min read | Intermediate Level
What You'll Learn
- The syntax of a
forloop and the order in which its parts run - How to declare loop variables in the header and use several of them at once
- How a
forloop inalways_combsynthesizes into hardware - The loop variable mistakes that cause infinite loops and compile errors
Syntax
A for loop runs in three steps:
- Initialization runs once, before the first pass. It usually declares and sets the loop variable.
- Condition is checked before every pass, including the first. If it is false, the loop ends.
- Modifier (the step) runs at the end of every pass, and then the condition is checked again.
for ( [initialization]; <condition>; [modifier])
// Single statement
for ( [initialization]; <condition>; [modifier]) begin
// Multiple statements
end
- initialization (optional): for example
int i = 0. Variables declared here exist only inside the loop. - condition: for example
i < 8. Leaving it out, as infor (;;), creates an infinite loop. - modifier (optional): for example
i++,i += 2ori--.
SystemVerilog adds C-style increment and decrement operators, which are the usual way to write the step. They can be used as a pre-increment or a post-increment:
| Statement | Description |
|---|---|
j = i++ | Post-increment: assign i to j, then increment i by 1 |
j = ++i | Pre-increment: increment i by 1, then assign i to j |
j = i-- | Post-decrement: assign i to j, then decrement i by 1 |
j = --i | Pre-decrement: decrement i by 1, then assign i to j |
Used on its own as a loop step, i++ and ++i do the same thing.
Using the for Loop in Digital Design
A for loop is synthesizable when its bounds are constants (literals or parameters) and its body has no timing controls such as # or @.
The synthesis tool unrolls the loop. It makes one copy of the body for each iteration and turns all the copies into logic. A loop that runs eight times in simulation becomes eight slices of hardware that all work in parallel.
A priority encoder is a good example. It outputs the position of the highest-priority active input. Unlike a plain encoder, which assumes only one input is active, it handles several active inputs at once and picks the one with the highest priority, here the highest index.
module priority_encoder #(parameter WIDTH = 8) (
input logic [WIDTH-1:0] req,
output logic [$clog2(WIDTH)-1:0] grant,
output logic valid
);
always_comb begin
grant = '0;
valid = 1'b0;
// Process from LOW to HIGH priority, so higher index overwrites lower
for (int i = 0; i < WIDTH; i++) begin
if (req[i]) begin
grant = i;
valid = 1'b1;
end
end
end
endmodule
The loop scans req from bit 0 upwards. Every set bit overwrites grant, so after the last iteration grant holds the index of the highest set bit. For example, req = 8'b0010_0110 gives grant = 5. Because WIDTH is a parameter, the loop unrolls into a chain of 2-to-1 muxes, one per request bit. Changing WIDTH resizes the hardware with no other code changes.
The order of the iterations matters. In unrolled hardware, a later iteration's assignment sits closer to the output, so it wins. That is how this loop gives the highest index priority.
Where is the for loop used in RTL?
Arbiters, leading-zero counters, parity and CRC generators, and population counters are all commonly written as parameterized for loops in always_comb. A single module can then serve a 4-requester arbiter in one block and a 32-requester arbiter in another.
Using the for Loop in Verification
In a testbench there are no synthesis limits. Bounds can come from variables or $size(), and the body can wait on clocks. The example below prints every element of a string array of fruit names.
The initialization declares a local variable i that holds the current index. The condition keeps i below the size of the array, and the step moves i to the next index on every pass.
module tb;
string array [5] = '{"apple", "orange", "pear", "blueberry", "lemon"};
initial begin
for (int i = 0; i < $size(array); i++)
$display ("array[%0d] = %s", i, array[i]);
end
endmodule
ncsim> run array[0] = apple array[1] = orange array[2] = pear array[3] = blueberry array[4] = lemon ncsim: *W,RNQUIE: Simulation is complete.
Use $size(array) instead of a hard-coded 5. The loop then stays correct if the array size changes. To visit every element of an array, foreach is even shorter.
Quick Check
Q: How many times does the body of for (int i = 10; i > 0; i -= 3) run?
Show Answer
Four times, with i = 10, 7, 4 and 1. After the fourth pass i becomes -2, the condition i > 0 fails, and the loop ends.
Multiple Initializations
The initialization part can set up more than one variable, separated by commas. Below, i and j are both declared as int when the loop starts. Each pass replaces the character at index j = 2 of the current string with "0".
module tb;
string array [5] = '{"apple", "orange", "pear", "blueberry", "lemon"};
initial begin
for (int i = 0, j = 2; i < $size(array); i++) begin
array[i][j] = "0";
$display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
end
end
endmodule
ncsim> run array[0] = ap0le, 2th index replaced by 0 array[1] = or0nge, 2th index replaced by 0 array[2] = pe0r, 2th index replaced by 0 array[3] = bl0eberry, 2th index replaced by 0 array[4] = le0on, 2th index replaced by 0 ncsim: *W,RNQUIE: Simulation is complete.
String characters are indexed from 0, so index 2 is the third character: the first "p" in "apple" and the "a" in "orange".
Multiple Modifiers
The modifier part can also hold several comma-separated expressions. Here i counts up while j counts down. j starts at the last index of the first string ("apple", so 4) and decreases by one on every pass.
module tb;
string array [5] = '{"apple", "orange", "pear", "blueberry", "lemon"};
initial begin
for (int i = 0, j = array[i].len() - 1; i < $size(array); i++, j--) begin
array[i][j] = "0";
$display ("array[%0d] = %s, %0dth index replaced by 0", i, array[i], j);
end
end
endmodule
ncsim> run array[0] = appl0, 4th index replaced by 0 array[1] = ora0ge, 3th index replaced by 0 array[2] = pe0r, 2th index replaced by 0 array[3] = b0ueberry, 1th index replaced by 0 array[4] = 0emon, 0th index replaced by 0 ncsim: *W,RNQUIE: Simulation is complete.
j is calculated only once, from the first string. After that it just counts down 4, 3, 2, 1, 0. It is not the last index of each string, which is why "orange" has its fourth character replaced rather than its last.
Common Beginner Mistakes
Mistake #1: A loop variable too narrow for the condition
Wrong: for (bit [2:0] i = 0; i < 8; i++)
Right: for (int i = 0; i < 8; i++)
Why? A 3-bit variable can only hold 0 to 7. After 7 it wraps back to 0, so i < 8 is always true and the loop never ends.
Mistake #2: Using the loop variable after the loop
A variable declared in the header, as in for (int i = 0; ...), exists only inside the loop. Reading i after end is a compile error. Why? The header creates a new local scope. If you need the final value, declare the variable before the loop and write for (i = 0; ...).
Mistake #3: A non-constant bound in RTL
Wrong (RTL): for (int i = 0; i < num_req; i++), where num_req is a signal
Right (RTL): for (int i = 0; i < MAX_REQ; i++) if (i < num_req) ...
Why? Synthesis must know how many copies of the body to build. Loop to a constant maximum and use an if inside for the run-time limit.
Mistake #4: Forgetting begin and end
Without begin and end, only the first statement after the header belongs to the loop. Why? Indentation means nothing to the compiler. The remaining statements run once, after the loop finishes.
Practice Exercise
Challenge: Count the ones
Write a synthesizable module that takes an 8-bit input data and outputs ones, the number of bits in data that are 1. Use a for loop inside always_comb.
Hint
Start ones at zero before the loop, then add each bit of data to it. The largest possible count is 8, so how many bits does ones need?
Solution
module popcount (
input logic [7:0] data,
output logic [3:0] ones // 0 to 8 needs 4 bits
);
always_comb begin
ones = '0; // default before the loop
for (int i = 0; i < 8; i++)
ones += data[i]; // add 1 for every bit that is set
end
endmodule
The loop unrolls into eight adder stages, which synthesis typically optimizes into an adder tree. For data = 8'b1011_0010, ones = 4.
Summary
In this tutorial, you learned:
- A
forloop runs the initialization once, checks the condition before every pass, and runs the modifier after every pass - Variables declared in the header are local to the loop and cannot be used after it
- The header can initialize and update several variables, separated by commas
++and--come in pre and post forms; as a loop step they behave the same- With constant bounds and no timing control, a
forloop unrolls into parallel hardware, and iteration order sets priority - A loop variable that is too narrow wraps around and makes the loop infinite
SystemVerilog can read and write files on disk directly from a testbench — useful for logging results, loading a stimulus file, or reading back expected data to compare against.
10 min read | Intermediate Level
What You'll Learn
- How to open, check, and close a file with
$fopen/$fclose - The different file access modes, and why
$fopenreturns unusual-looking descriptor values - How to write and read lines with
$fdisplay/$fwriteand$fgets - Why a
while (!$feof(fd))loop can produce one extra, empty iteration — and how$fscanfavoids it - What a multichannel descriptor is, and how it differs from a single-file descriptor
How to Open and Close a File?
A file is opened for reading or writing with $fopen(), which returns a 32-bit integer handle called a file descriptor. This handle is used for every subsequent read or write, until it's closed with $fclose() — no further reads or writes are allowed on it after that.
module tb;
initial begin
// 1. Declare an integer variable to hold the file descriptor
int fd;
// 2. Open a file called "note.txt" in the current folder with a "read" permission
// If the file does not exist, then fd will be zero
fd = $fopen ("./note.txt", "r");
if (fd) $display("File was opened successfully : %0d", fd);
else $display("File was NOT opened successfully : %0d", fd);
// 2. Open a file called "note.txt" in the current folder with a "write" permission
// "fd" now points to the same file, but in write mode
fd = $fopen ("./note.txt", "w");
if (fd) $display("File was opened successfully : %0d", fd);
else $display("File was NOT opened successfully : %0d", fd);
// 3. Close the file descriptor
$fclose(fd);
end
endmodule
Output
ncsim> run Open failed on file "./note.txt". No such file or directory File was NOT opened successfully : 0 File was opened successfully : -2147483645 ncsim: *W,RNQUIE: Simulation is complete.
The first $fopen fails because note.txt doesn't exist yet and was opened for reading only — fd comes back as 0. The second call, opening the same file for writing, succeeds and creates it, returning -2147483645.
That large, negative-looking number isn't a bug — a file descriptor's most significant bit is always forced to 1 (so an implementation can tell it apart from a multichannel descriptor), while the remaining bits hold an ordinary small count of which file this is. Interpreted as a plain signed integer, that forced top bit alone is what makes the value read as large and negative — 0x80000003 simply displays as -2147483645, with 3 being the actual small count underneath. Checking if (fd) still works correctly either way — only a failed open returns exactly 0.
It's important to close every open file before the end of simulation, or its contents may not be fully written to disk.
Quick Check
Q: If fd = $fopen("missing.txt", "r") and the file doesn't exist, what value does fd hold, and what does if (fd) evaluate to?
Show Answer
fd is 0, and if (fd) evaluates to false — 0 is the one specific value that always means the open failed, regardless of what a successful descriptor's bit pattern looks like.
File Access Modes
By default a file opens in write mode ("w"). Several other modes are available:
| Argument | Description |
|---|---|
| "r" | Open for reading |
| "w" | Create for writing, overwrite if it exists |
| "a" | Create if the file does not exist, else append; open for writing at end of file |
| "r+" | Open for update (reading and writing) |
| "w+" | Truncate or create for update |
| "a+" | Append, open or create for update at EOF |
module tb;
initial begin
int fd_w, fd_r, fd_a, fd_wp, fd_rp, fd_ap;
fd_w = $fopen ("./todo.txt", "w"); // Open a new file in write mode and store file descriptor in fd_w
fd_r = $fopen ("./todo.txt", "r"); // Open in read mode
fd_a = $fopen ("./todo.txt", "a"); // Open in append mode
if (fd_w) $display("File was opened successfully : %0d", fd_w);
else $display("File was NOT opened successfully : %0d", fd_w);
if (fd_r) $display("File was opened successfully : %0d", fd_r);
else $display("File was NOT opened successfully : %0d", fd_r);
if (fd_a) $display("File was opened successfully : %0d", fd_a);
else $display("File was NOT opened successfully : %0d", fd_a);
// Close the file descriptor
$fclose(fd_w);
$fclose(fd_r);
$fclose(fd_a);
end
endmodule
Output
ncsim> run ncsim: *W,VFOPTW: File ./todo.txt being opened by Initial stmt (file: ./testbench.sv, line: 2 in worklib.tb [module]) has been opened earlier. File was opened successfully : -2147483645 File was opened successfully : -2147483644 File was opened successfully : -2147483643 ncsim: *W,RNQUIE: Simulation is complete.
All three variables get a different descriptor value, each pointing to the same underlying file but with different access permissions. The simulator warns that the file was already open, since fd_w hadn't been closed before fd_r and fd_a opened it again — a heads-up, not a fatal error.
How to Read and Write to a File?
A file opened in write ("w") or append ("a") mode can be written to with $fdisplay() or $fwrite(), both taking the file descriptor as their first argument. A file opened in read ("r") or read-write ("r+") mode can be read one line at a time with $fgets() — calling it 10 times reads 10 lines.
module tb;
int fd; // Variable for file descriptor handle
string line; // String value read from the file
initial begin
// 1. Lets first open a new file and write some contents into it
fd = $fopen ("trial", "w");
// Write each index in the for loop to the file using $fdisplay
// File handle should be the first argument
for (int i = 0; i < 5; i++) begin
$fdisplay (fd, "Iteration = %0d", i);
end
// Close this file handle
$fclose(fd);
// 2. Let us now read back the data we wrote in the previous step
fd = $fopen ("trial", "r");
// Use $fgets to read a single line into variable "line"
$fgets(line, fd);
$display ("Line read : %s", line);
// Get the next line and display
$fgets(line, fd);
$display ("Line read : %s", line);
// Close this file handle
$fclose(fd);
end
endmodule
Output
ncsim> run Line read : Iteration = 0 Line read : Iteration = 1 ncsim: *W,RNQUIE: Simulation is complete.
Each output line is followed by a blank line — that's not a mistake in the code. $fgets() keeps the line's trailing newline character as part of the string it returns, and $display() adds its own newline on top of that, so every line ends up printed with what looks like a double line break.
How to Read Until End of File?
$feof() returns true once the end of a file has been reached, and can drive a loop that reads an entire file:
module tb;
int fd; // Variable for file descriptor handle
string line; // String value read from the file
initial begin
// 1. Lets first open a new file and write some contents into it
fd = $fopen ("trial", "w");
for (int i = 0; i < 5; i++) begin
$fdisplay (fd, "Iteration = %0d", i);
end
$fclose(fd);
// 2. Let us now read back the data we wrote in the previous step
fd = $fopen ("trial", "r");
while (!$feof(fd)) begin
$fgets(line, fd);
$display ("Line: %s", line);
end
// Close this file handle
$fclose(fd);
end
endmodule
Output
ncsim> run Line: Iteration = 0 Line: Iteration = 1 Line: Iteration = 2 Line: Iteration = 3 Line: Iteration = 4 Line: ncsim: *W,RNQUIE: Simulation is complete.
Notice the trailing empty Line: at the end, even though the file only has 5 lines. This is a well-known gotcha, not a bug in this specific code: $feof() only becomes true after a read has already been attempted and found nothing left. Right after the 5th real line is read, $feof(fd) is still false — the read that would actually discover end-of-file hasn't happened yet — so the loop runs one more time, $fgets() comes back empty, and that empty result still gets displayed.
Quick Check
Q: Why doesn't the loop simply stop after printing "Iteration = 4"?
Show Answer
Because the loop condition, !$feof(fd), is checked before each read, using whatever $feof reported as of the previous read. Right after reading "Iteration = 4" successfully, the file hasn't been read again yet, so $feof is still false at that point — the loop only discovers it's actually at the end on the following iteration, once it tries to read again and gets nothing.
How to Parse a Line for Values?
$fscanf() scans a line and extracts specific values, and its return value is the number of items it successfully matched:
module tb;
int fd; // Variable for file descriptor handle
int idx;
string str;
initial begin
// 1. Lets first open a new file and write some contents into it
fd = $fopen ("trial", "w");
for (int i = 0; i < 5; i++)
$fdisplay (fd, "Iteration = %0d", i);
$fclose(fd);
// 2. Let us now read back the data we wrote in the previous step
fd = $fopen ("trial", "r");
// fscanf returns the number of matches
while ($fscanf (fd, "%s = %0d", str, idx) == 2) begin
$display ("Line: %s = %0d", str, idx);
end
// Close this file handle
$fclose(fd);
end
endmodule
Output
ncsim> run Line: Iteration = 0 Line: Iteration = 1 Line: Iteration = 2 Line: Iteration = 3 Line: Iteration = 4 ncsim: *W,RNQUIE: Simulation is complete.
No trailing empty line here, unlike the $feof example above. That's because the loop condition checks $fscanf's own return value directly — once there's nothing left to scan, it returns fewer than 2 matches immediately, and the loop stops right there, with no lagging extra iteration.
What Are Multichannel File Descriptors?
A multichannel descriptor (mcd) is a 32-bit packed value where a single bit is set to indicate which file is open. The least significant bit always refers to standard output, and the most significant bit is always 0.
$fopen returns an mcd only when it is called with just a file name and no mode argument; the file is then opened for writing. Writing to two or more files at once is done by bitwise OR-ing their mcds together and writing to the combined result:
module tb;
integer mcd1, mcd2, both;
initial begin
// No mode argument: each call returns a multichannel descriptor
mcd1 = $fopen ("file1.txt");
mcd2 = $fopen ("file2.txt");
// Combine both descriptors into one - a single $fdisplay call
// now writes the same line to both files at once
both = mcd1 | mcd2;
$fdisplay (both, "This goes to both files");
$fclose(mcd1);
$fclose(mcd2);
end
endmodule
A single $fdisplay(both, ...) call writes to both file1.txt and file2.txt at once, since both's bit pattern has both files' bits set. OR-ing in 1 as well, as in $fdisplay(both | 1, ...), also prints the line to standard output.
This only works with mcds. A descriptor returned by $fopen with a mode such as "w" is an ordinary file descriptor: its top bit is set and the low bits hold the file's number, so OR-ing two of them gives a value that names neither file. Open the files without a mode whenever one call should write to several of them.
Where Is File I/O Used?
Writing test results and debug logs to a file is standard practice for anything run as part of an automated regression, where a script needs to parse the output afterward rather than a person watching the simulator's console in real time. Reading from a file is just as common for loading stimulus — a set of expected values, or a memory image — without hardcoding it directly into the testbench.
Common Beginner Mistakes
Mistake #1: Forgetting to close a file before simulation ends
An open file descriptor's contents may not be completely written to disk until it's closed. Why? Always pair every $fopen() with a matching $fclose(), especially before $finish or the natural end of the test, or the file on disk may be incomplete.
Mistake #2: Using while (!$feof(fd)) without accounting for the extra iteration
As shown above, this pattern reliably produces one trailing empty read past the real end of the file. Why? $feof reports the result of the previous read, not a live look-ahead at whether the next read will succeed — check $fgets's own return value directly instead if you want to avoid this exact lag.
Mistake #3: Assuming $fopen returns small sequential integers
A successfully opened file descriptor can come back looking like a large negative number, such as -2147483645. Why? The count underneath genuinely is small and does increase sequentially, but its most significant bit is always forced to 1 on top of that — exactly what makes the signed value read as large and negative instead of a small positive number like 1, 2, 3. Always check for success with if (fd) rather than expecting any particular numeric range.
Practice Exercise
Challenge: Fix the Extra Empty Line
Rewrite the $feof-based read loop from earlier so it prints exactly 5 lines, with no trailing empty one — without switching to $fscanf.
Hint
$fgets itself returns a value: the number of characters read, which is 0 once there's nothing left. Check that return value directly instead of checking $feof beforehand.
Solution
fd = $fopen ("trial", "r");
while ($fgets(line, fd)) begin
$display ("Line: %s", line);
end
$fclose(fd);
$fgets returns 0 the moment there's nothing left to read, so checking its own return value directly reflects the real outcome of that specific call — unlike $feof, there's no lag between what the loop condition reports and what actually just happened.
Summary
In this tutorial, you learned:
$fopen()returns a file descriptor (0on failure), and$fclose()must be called before the file's contents are guaranteed to be fully written- File access modes control read, write, append, and update behavior, each represented by a different string like
"r","w", or"a" $fdisplay()/$fwrite()write formatted data;$fgets()reads one line at a time, keeping its trailing newlinewhile (!$feof(fd))reliably produces one extra, empty iteration past the real end of the file; checking$fgets's or$fscanf's own return value avoids that lag- A multichannel descriptor, returned by
$fopencalled without a mode, is a bit-flag value that can be OR'd together with another to write the same data to multiple files in a single call; ordinary file descriptors cannot be combined this way
Continuing the Testbench Components Chapter
Continue with SystemVerilog Testbench Example 1.
Every now and then you need to avoid recompiling a testbench just to change one setting — accepting values from the command line the way a scripting language like bash or Perl would. SystemVerilog does this through plusargs: optional arguments always starting with a + character, passed to the simulation at run time and read back inside the testbench through two system functions.
9 min read | Intermediate Level
What You'll Learn
- The difference between
$test$plusargs(presence check) and$value$plusargs(value extraction) - Exactly how
$test$plusargs's prefix matching works, and why it's case-sensitive - How
$value$plusargs's format specifier controls how the plusarg's text is reinterpreted, not just how it's displayed - Common command-line syntax pitfalls: a missing
=, an empty value, and a doubled+ - What causes a run-time error when using
$value$plusargs
Syntax
$test$plusargs (user_string)
$value$plusargs (user_string, variable)
$test$plusargs: Checking Whether an Argument Was Passed
$test$plusargs is used when you just need to know whether an argument was passed, without needing a value. It searches every plusarg given on the command line, and returns a non-zero integer if any one of them starts with the string you provided — otherwise it returns zero. A variable can supply the string instead of a literal, and any null characters in it are ignored. The match is case-sensitive.
module tb;
initial begin
if ($test$plusargs ("STANDBY"))
$display ("STANDBY argument is found ...");
if ($test$plusargs ("Standby"))
$display ("Standby argument is also found ...");
if ($test$plusargs ("STAND"))
$display ("STAND substring is found ...");
if ($test$plusargs ("S"))
$display ("Some string starting with S found ...");
if ($test$plusargs ("T"))
$display ("Some string containing T found ...");
if ($test$plusargs ("STAND_AT_EASE"))
$display ("Can't stand any longer ...");
if ($test$plusargs ("SUNSHADE"))
$display ("It's too hot today ...");
if ($test$plusargs ("WINTER"))
$display ("No match.. ");
end
endmodule
Run with the run-time argument +STANDBY:
ncsim> run STANDBY argument is found ... STAND substring is found ... Some string starting with S found ... ncsim: *W,RNQUIE: Simulation is complete.
Only three of the eight checks match. "STANDBY" matches exactly. "STAND" and "S" both match too, because STANDBY (the actual plusarg on the command line) starts with each of them — the matching direction is "does a supplied plusarg begin with my string," not the other way around. "Standby" fails despite being spelled almost identically, purely because of the case difference. "T" fails because STANDBY doesn't start with T at all, even though it contains one.
Quick Check
Q: Still running with +STANDBY, would $test$plusargs("BY") return true?
Show Answer
No. STANDBY doesn't start with "BY" — it ends with it. $test$plusargs only matches from the beginning of the plusarg, not anywhere within it.
$value$plusargs: Extracting a Value
$value$plusargs searches the same way, but also extracts a value into a variable. If a plusarg matches, it returns a non-zero value and stores the result in the variable provided; if nothing matches, it returns 0 and leaves the variable untouched. The user_string takes the form "plusarg_string format_string", where the format specifier works like $display's — and critically, it controls how the plusarg's raw text gets reinterpreted, not just how it's printed afterward.
| Format Specifier | Description |
|---|---|
| %d | Decimal conversion |
| %o | Octal conversion |
| %h, %x | Hexadecimal conversion |
| %b | Binary conversion |
| %e | Real exponential conversion |
| %f | Real decimal conversion |
| %g | Real decimal or exponential conversion |
| %s | String (no conversion) |
// Note FS : Format Specifier
module tb;
initial begin
string var1, var2;
bit [31:0] data;
if ($value$plusargs ("STRING=%s", var1))
$display ("STRING with FS has a value %s", var1);
if ($value$plusargs ("NUMBER=%0d", data))
$display ("NUMBER with %%0d has a value %0d", data);
if ($value$plusargs ("NUMBER=%0h", data))
$display ("NUMBER with %%0h has a value %0d", data);
if ($value$plusargs ("NUMBER=%s", data))
$display ("NUMBER with %%s has a value %0d", data);
if ($value$plusargs ("STRING=", var1))
$display ("STRING without FS has a value %s", var1);
if ($value$plusargs ("+STRING=%s", var1))
$display ("STRING with + char has a value %s", var1);
`ifdef RUNTIME_ERR
if ($value$plusargs ("STRING=%0d", var2))
$display ("STRING with %%0d has a value %s", var2);
`endif
end
endmodule
There should never be a space between the user string, =, and the value in the command-line expression itself. Here's what different run-time arguments produce:
+STRING=Joey
"Joey" can be passed with or without quotes:
ncsim> run STRING with FS has a value Joey STRING without FS has a value Joey ncsim: *W,RNQUIE: Simulation is complete.
+NUMBER=100
The same text, "100", gets reinterpreted completely differently depending on the format specifier used to extract it:
ncsim> run NUMBER with %0d has a value 100 NUMBER with %0h has a value 256 NUMBER with %s has a value 3223600 ncsim: *W,RNQUIE: Simulation is complete.
With %0h, the characters "100" are read as hex digits, not decimal — hex 100 is 1×16² + 0×16¹ + 0×16⁰ = 256 in decimal, exactly what's printed. With %s, there's no numeric parsing at all — the raw ASCII bytes of the string "100" (0x31, 0x30, 0x30) are packed directly into the 32-bit data variable as-is, giving the bit pattern 0x313030, which read back out as a plain decimal number is 3,223,600. The format specifier isn't just choosing how to print the value — it's choosing how the plusarg's text gets turned into bits in the first place.
Quick Check
Q: If the argument were +NUMBER=20 instead, what would $value$plusargs("NUMBER=%0h", data) report as a decimal value?
Show Answer
32. Hex 20 is 2×16¹ + 0×16⁰ = 32 in decimal — the same hex-reinterpretation happening with 256 above, just with different digits.
+STRING (no = or value)
Without the =, nothing is recognized at all:
ncsim> run ncsim: *W,RNQUIE: Simulation is complete.
+STRING= (empty value)
The argument's value is an empty string:
ncsim> run STRING with FS has a value STRING without FS has a value ncsim: *W,RNQUIE: Simulation is complete.
++STRING=Joey (doubled +)
The simulator only treats the first + character as the marker that begins a plusarg — everything after it, up to the =, becomes the literal user string. So ++STRING=Joey is actually the plusarg +STRING=Joey, which is exactly what the $value$plusargs("+STRING=%s", var1) call above was searching for:
ncsim> run STRING with + char has a value Joey ncsim: *W,RNQUIE: Simulation is complete.
+STRING=1234
Even a number is parsed as a plain string by default, with no numeric conversion:
ncsim> run STRING with FS has a value 1234 STRING without FS has a value 1234 ncsim: *W,RNQUIE: Simulation is complete.
What Happens With a Mismatched Format?
If the user string matches, but the format specifier doesn't fit the data actually being passed in, you get a run-time error — not a compile-time one. Compiling with +define+RUNTIME_ERR and running with +STRING=Joey:
ncsim> run
STRING with FS has a value Joey
STRING without FS has a value Joey
if ($value$plusargs ("STRING=%0d", var2))
|
ncsim: *E,SYSFMT (./testbench.sv,27|22): $value$plusargs -- value found 'Joey' for plusarg 'STRING=' does not match specified format.
STRING with %0d has a value
ncsim: *W,RNQUIE: Simulation is complete.
"Joey" can't be interpreted as a decimal number, so the %0d-formatted call fails at run time, well after compilation succeeded — this class of mistake is only caught once the simulation actually runs with that specific argument.
Where Are Plusargs Used?
Plusargs are the standard way a regression script controls a testbench without recompiling it for every run — passing a random seed, selecting which named test scenario to run, or turning on extra debug output, all decided at the command line rather than baked into the compiled testbench.
Common Beginner Mistakes
Mistake #1: Assuming $test$plusargs needs an exact match
As the example shows, $test$plusargs("S") matches +STANDBY, not just an argument that's literally +S. Why? It's a prefix check on whatever plusargs were actually passed, which can produce unexpected matches if your check string happens to be a prefix of something else on the command line too.
Mistake #2: Forgetting plusargs are case-sensitive
$test$plusargs("Standby") fails against +STANDBY purely due to case. Why? There's no case-insensitive matching built in — the string you check against has to match the actual casing used on the command line.
Mistake #3: Mismatching the format specifier to the actual data
As the RUNTIME_ERR example shows, passing a non-numeric value where a numeric format specifier is expected compiles fine and only fails when that specific line actually executes. Why? Always make sure the format specifier matches what the command-line value will actually contain, since this class of bug won't show up until run time, and only with the exact argument that triggers it.
Mistake #4: Adding spaces around the = in a plusarg
A command-line argument like +NUMBER = 100 (with spaces) won't be recognized the way +NUMBER=100 is. Why? The plusarg syntax requires the string, =, and value to be written with no spaces between them — any space breaks the parsing.
Practice Exercise
Challenge: Predict the Matches
Given the run-time argument +VERBOSE, which of these $test$plusargs calls would return true: $test$plusargs("VERBOSE"), $test$plusargs("VERB"), $test$plusargs("verbose"), $test$plusargs("OSE")?
Hint
Check each string against two things: does it match the start of VERBOSE exactly, and does the case match too?
Solution
"VERBOSE" and "VERB" both return true — VERBOSE starts with both of them, and the case matches. "verbose" fails on case (lowercase versus the actual uppercase VERBOSE). "OSE" fails because VERBOSE doesn't start with "OSE", even though it appears at the end of the word.
Summary
In this tutorial, you learned:
$test$plusargschecks whether any command-line plusarg starts with a given string, with no value extraction — it's case-sensitive and matches by prefix$value$plusargsextracts a value into a variable, using a format specifier that controls how the plusarg's raw text is reinterpreted into bits- The exact same text can produce very different numeric results depending on the format specifier —
%hreads digits as hex, while%spacks raw ASCII bytes with no numeric parsing at all - A missing
=, an empty value, or spaces around the=all change how (or whether) a plusarg is recognized - A format specifier that doesn't match the actual data produces a run-time error, not a compile-time one
Continuing the Testbench Components Chapter
Continue with SystemVerilog file operations.
A mailbox lets different processes exchange data with each other — similar to a real postbox, where letters are put into the box and retrieved later by someone else. A mailbox can be created with either a bounded or unbounded queue size: a bounded mailbox only holds a limited number of messages, and a process that tries to store more into a full mailbox is suspended until there's room; an unbounded mailbox has no such limit at all.
There are two types of mailboxes: a generic mailbox that accepts items of any data type, and a parameterized mailbox constrained to accept only one specific type.
10 min read | Intermediate Level
What You'll Learn
- The difference between a mailbox and a plain queue
- How a bounded mailbox blocks a producer once it's full, and how to read
num()safely - The full set of mailbox methods — blocking, non-blocking, and look-without-removing variants
- How to parameterize a mailbox to a specific data type, and why that's good practice
- The difference between a run-time type mismatch in a generic mailbox and a compile-time one in a parameterized mailbox
SystemVerilog Mailbox vs Queue
Although a mailbox essentially behaves like a queue, it's quite different from the queue data type. A plain queue can push and pop items from either the front or the back, and you can index into it directly. A mailbox, on the other hand, is a built-in class that uses semaphores internally to give atomic control over pushing and popping — you can't access a specific index within it, only retrieve items in FIFO order.
A Generic Mailbox Example (Bounded)
Two processes run concurrently below: one puts data into the mailbox, and the other gets data from it. The mailbox here is bounded to hold at most 2 items at once:
module tb;
// Create a new mailbox that can hold utmost 2 items
mailbox mbx = new(2);
// Block1: This block keeps putting items into the mailbox
// The rate of items being put into the mailbox is 1 every ns
initial begin
for (int i=0; i < 5; i++) begin
#1 mbx.put (i);
$display ("[%0t] Thread0: Put item #%0d, size=%0d", $time, i, mbx.num());
end
end
// Block2: This block keeps getting items from the mailbox
// The rate of items received from the mailbox is 1 item every 2ns
initial begin
forever begin
int idx;
#2 mbx.get (idx);
$display ("[%0t] Thread1: Got item #%0d, size=%0d", $time, idx, mbx.num());
end
end
endmodule
Output
ncsim> run [1] Thread0: Put item #0, size=1 [2] Thread1: Got item #0, size=0 [2] Thread0: Put item #1, size=1 [3] Thread0: Put item #2, size=2 [4] Thread1: Got item #1, size=1 [4] Thread0: Put item #3, size=2 [6] Thread1: Got item #2, size=1 [6] Thread0: Put item #4, size=2 [8] Thread1: Got item #3, size=1 [10] Thread1: Got item #4, size=0 ncsim: *W,RNQUIE: Simulation is complete.
Following the producer's own timing on its own, items would be put at 1, 2, 3, 4, and 5ns. But watch what happens to the last one: by 4ns, the mailbox is already full (size 2, its bound), and the producer's fifth put() — due at 5ns — has nothing to do but block. It only completes at 6ns, the moment the consumer's next get() frees up a slot. That's a bounded mailbox's flow control in action: the producer is throttled to however fast the consumer can actually keep up, not however fast it wants to produce.
There's a race between the two threads where the producer can push and the consumer can pop in the exact same delta cycle (as happens at 2, 4, and 6ns above). Because of that, the value num() reports is only valid at the instant it's printed — it can change again on the very next get() or put(), and its exact value at a shared timestamp can depend on which operation's statements happen to execute first.
Quick Check
Q: If the mailbox above were created with new(3) instead of new(2), would the producer's fifth put() still have to block?
Show Answer
No. With room for 3 items, the mailbox would never fill up fast enough to block the producer at this rate — every put() would succeed exactly on schedule, at 1, 2, 3, 4, and 5ns, with no delay.
try_put(): Checking for Room Without Blocking
The example above shows put() blocking once the mailbox is full. Sometimes blocking isn't what you want — you'd rather check whether there's room right now, and do something else immediately if there isn't. That's what try_put() is for:
module tb;
mailbox mbx = new (1); // bound = 1, room for only one item
initial begin
mbx.put (10);
$display ("[%0t] Put item 10, size=%0d", $time, mbx.num());
// The mailbox is already full - try_put() fails instead of blocking
if (mbx.try_put (20))
$display ("[%0t] try_put(20) succeeded", $time);
else
$display ("[%0t] try_put(20) failed - mailbox is full, moving on instead of blocking", $time);
#5 begin
int x;
mbx.get (x);
$display ("[%0t] Got item %0d, size=%0d", $time, x, mbx.num());
end
// Now that item 10 has been removed, there's room again
if (mbx.try_put (20))
$display ("[%0t] try_put(20) succeeded now that there's room", $time);
end
endmodule
At 0ns, the mailbox is already full after the first put(), so try_put(20) fails immediately and returns 0 — unlike put(), it never waits around to see if room eventually opens up. At 5ns, once get() removes item 10 and frees the only slot, the exact same try_put(20) call now succeeds right away.
Quick Check
Q: If mbx.put(20) (the blocking version) had been used instead of try_put(20) at 0ns in the example above, what would happen?
Show Answer
It would block at 0ns and only complete at 5ns, once get() frees a slot — the same outcome try_put() eventually reaches, just without ever reporting failure or letting the rest of the code run in the meantime.
Mailbox Methods
| Method | Description |
|---|---|
function new (int bound = 0); | Returns a mailbox handle; bound > 0 sets the maximum queue size (0 means unbounded) |
function int num (); | Returns the number of messages currently in the mailbox |
task put (singular message); | Blocking method that stores a message in FIFO order |
function int try_put (singular message); | Non-blocking version of put(); returns a positive integer on success, 0 if the mailbox is full |
task get (ref singular message); | Blocking method that retrieves one message, blocking the process if the mailbox is empty |
function int try_get (ref singular message); | Non-blocking version of get(); returns 0 if the mailbox is empty |
task peek (ref singular message); | Copies one message without removing it from the queue |
function int try_peek (ref singular message); | Non-blocking version of peek() |
peek() and try_peek(): Looking Without Removing
peek() copies whatever's at the front of the mailbox into a variable, but leaves it in the queue — unlike get(), which removes it:
module tb;
mailbox mbx = new ();
initial begin
int peeked, gotten;
mbx.put (42);
$display ("[%0t] Put item 42, size=%0d", $time, mbx.num());
// Look at the item without removing it
mbx.peek (peeked);
$display ("[%0t] Peeked item %0d, size=%0d", $time, peeked, mbx.num());
// Now actually remove it
mbx.get (gotten);
$display ("[%0t] Got item %0d, size=%0d", $time, gotten, mbx.num());
// Mailbox is empty now - try_peek() fails instead of blocking
if (mbx.try_peek (peeked))
$display ("[%0t] try_peek succeeded", $time);
else
$display ("[%0t] try_peek found the mailbox empty", $time);
end
endmodule
After peek(peeked), peeked holds 42, but num() still reports 1 — the item is still sitting in the mailbox. Only the subsequent get(gotten) actually removes it, dropping the size to 0. Once empty, try_peek() behaves like try_get(): it fails and returns immediately instead of blocking.
Like peek() and get(), try_peek() and try_get() form the same pair — one leaves the item in place, one removes it — just without ever blocking if the mailbox is empty.
Parameterized Mailboxes
By default, a mailbox is typeless, and can send and receive objects of mixed data types. That flexibility can also cause type mismatches that only surface at simulation time. Here's exactly what that looks like — a generic mailbox accepts a string being put in, with nothing stopping a completely unrelated type from trying to read it back out:
module tb;
mailbox mbx = new (); // generic - accepts any type
initial begin
string s = "hello";
int received;
mbx.put (s); // put a string in
mbx.get (received); // try to get it out as an int
$display ("[%0t] Received = %0d", $time, received);
end
endmodule
This compiles without complaint, since a generic mailbox doesn't check that what goes in matches what comes out. At run time, though, get(received) is trying to unpack a string into an int — a mismatch most simulators catch as a run-time error, well after the code has already been compiled, built, and started running.
This is the run-time counterpart to the compile-time TYCMPAT error shown later in this article for a mismatched parameterized mailbox. The failure mode is the same idea — sending one type where another is expected — but a generic mailbox only catches it once the simulation is already running, while a parameterized mailbox catches it before simulation even starts.
Parameterizing a mailbox to a specific data type avoids that risk entirely, catching mismatches at compile time instead.
Below, an alias for a string-typed mailbox is created with typedef (optional, but good practice), and two components — comp1 and comp2 — connect through it, with comp1 sending a few strings that comp2 receives:
// Create alias for parameterized "string" type mailbox
typedef mailbox #(string) s_mbox;
// Define a component to send messages
class comp1;
// Create a mailbox handle to put items
s_mbox names;
// Define a task to put items into the mailbox
task send ();
for (int i = 0; i < 3; i++) begin
string s = $sformatf ("name_%0d", i);
#1 $display ("[%0t] Comp1: Put %s", $time, s);
names.put(s);
end
endtask
endclass
// Define a second component to receive messages
class comp2;
// Create a mailbox handle to receive items
s_mbox list;
// Create a loop that continuously gets an item from
// the mailbox
task receive ();
forever begin
string s;
list.get(s);
$display ("[%0t] Comp2: Got %s", $time, s);
end
endtask
endclass
// Connect both mailbox handles at a higher level
module tb;
// Declare a global mailbox and create both components
s_mbox m_mbx = new();
comp1 m_comp1 = new();
comp2 m_comp2 = new();
initial begin
// Assign both mailbox handles in components with the
// global mailbox
m_comp1.names = m_mbx;
m_comp2.list = m_mbx;
// Start both components, where comp1 keeps sending
// and comp2 keeps receiving
fork
m_comp1.send();
m_comp2.receive();
join
end
endmodule
Output
ncsim> run [1] Comp1: Put name_0 [1] Comp2: Got name_0 [2] Comp1: Put name_1 [2] Comp2: Got name_1 [3] Comp1: Put name_2 [3] Comp2: Got name_2 ncsim: *W,RNQUIE: Simulation is complete.
m_mbx is created with new() and no bound, so it's unbounded — every put() succeeds immediately, and since comp2's get() is already waiting the moment each string arrives, both the put and the get for a given string happen in the same time step.
Quick Check
Q: Both m_comp1.names and m_comp2.list are assigned m_mbx in the testbench. Does each component get its own independent copy of the mailbox?
Show Answer
No. A mailbox handle behaves like any other class handle — assigning it doesn't copy anything, it just makes both variables reference the exact same underlying mailbox object. That's precisely what lets comp1's put() and comp2's get() operate on the same queue.
Matching Different Type Mailboxes
Consider what happens if comp1 used a string-typed mailbox but comp2 used a byte-typed one instead:
class comp2;
mailbox #(byte) list;
...
endclass
module tb;
s_mbox m_mbx;
...
initial begin
m_comp1.names = m_mbx;
m_comp2.list = m_mbx;
end
endmodule
Output
m_comp2.list = m_mbx;
|
ncvlog: *E,TYCMPAT (testbench.sv,34|25): assignment operator type check failed (expecting datatype compatible with 'mailbox' but found '$unit::s_mbox (mailbox)' instead).
This is a compile-time error, not a run-time one — exactly the benefit of parameterizing a mailbox instead of leaving it typeless. A typeless mailbox connecting a string producer to a byte consumer would compile fine and only fail (or silently misbehave) once the mismatched data actually flowed through it.
Where Is a Mailbox Used?
A mailbox is the classic way to connect a generator to a driver — the generator creates transaction objects and puts them in, the driver gets them out and drives the corresponding signals onto the bus. A bounded mailbox specifically models a slower consumer applying back-pressure on a faster producer, which is exactly the flow-control behavior shown in the first example above.
Common Beginner Mistakes
Mistake #1: Assuming an unbounded mailbox provides flow control
A mailbox created with plain new() (no bound) never blocks a producer, no matter how far ahead of the consumer it gets. Why? If backpressure is actually what you want — keeping a fast producer from running arbitrarily far ahead of a slow consumer — the mailbox needs an explicit bound; an unbounded one just keeps growing.
Mistake #2: Trusting num() as a stable snapshot
As the note in the first example explains, num() can change on the very next get() or put(), including ones happening in the same delta cycle. Why? Using it to make a decision (like "should I put more items?") without accounting for that race can lead to logic that behaves differently across simulator runs or seeds.
Mistake #3: Leaving a mailbox typeless when a fixed type is known
A generic mailbox accepts any data type, which means a type mismatch between a producer and consumer only shows up when the wrong data actually gets used, if it's ever caught at all. Why? Parameterizing the mailbox to the type you actually intend to send catches that mismatch at compile time instead, exactly as the TYCMPAT error above demonstrates.
Practice Exercise
Challenge: Predict the Blocking Point
Using the first bounded mailbox example, suppose the bound were changed from new(2) to new(1), with the same producer (1 item/ns) and consumer (1 item/2ns) rates. At what time would the producer's second put() (item 1) actually complete?
Hint
Work out the mailbox's size at each timestamp with a bound of 1, the same way the article traces it for a bound of 2, and find the first point where a put() would have to wait for the consumer.
Solution
2ns. Item 0 is put at 1ns (size 0→1, now full since the bound is 1). The producer's second put() is due at 2ns, but the mailbox is still full at that instant — until the consumer's own get(), also scheduled for 2ns, retrieves item 0 first (size 1→0). Since both events land at exactly 2ns, the get frees the single slot just in time for the put to complete in that same time step, landing right at 2ns rather than being pushed further out.
Summary
In this tutorial, you learned:
- A mailbox exchanges data between processes in FIFO order, using semaphores internally for atomic push/pop control — unlike a plain queue, you can't index into it directly
- A bounded mailbox blocks
put()once full, providing flow control between a producer and a slower consumer; an unbounded one never blocks a producer at all num()is only a snapshot valid at the instant it's read, and can change on the very next operationput()/get()block;try_put()/try_get()don't;peek()/try_peek()copy a message without removing it- A generic mailbox can accept a type mismatch that only fails at run time; parameterizing a mailbox to a specific type catches that same class of mistake at compile time instead
Quiz
No quiz questions available for this article.