Digital blocks typically communicate using bus protocols — AMBA AXI, WishBone, OCP, and similar. A bus master sending data provides control signals telling the slave when a packet is valid, whether it's a read or write, and how many bytes are being sent, followed by an address and the data to be stored there. Here's a worked example where a testbench acts as the master, constraining a bus transaction class to valid data for a specific target.
12 min read | Intermediate Level
What You'll Learn
- How multiple constraints — class-level and inline — combine to model a real bus protocol's addressing and burst rules
- Why an address-range constraint alone isn't enough to guarantee a burst transaction stays within a slave's memory window
- How to verify by hand that a specific randomized result actually satisfies every constraint in play
Modeling a Bus Transaction
// Burst [ 0 -> 1 byte, 1 -> 2 bytes, 2 -> 3 bytes, 3 -> 4 bytes]
// Length -> max 8 transactions per burst
// Protocol expects to send only first addr, and slave should calculate all
// other addresses from burst and length properties
class BusTransaction;
rand int m_addr;
rand bit [31:0] m_data;
rand bit [1:0] m_burst; // Size of a single transaction in bytes (4 bytes max)
rand bit [2:0] m_length; // Total number of transactions
constraint c_addr { m_addr % 4 == 0; } // Always aligned to 4-byte boundary
function void display(int idx = 0);
$display ("------ Transaction %0d------", idx);
$display (" Addr = 0x%0h", m_addr);
$display (" Data = 0x%0h", m_data);
$display (" Burst = %0d bytes/xfr", m_burst + 1);
$display (" Length = %0d", m_length + 1);
endfunction
endclass
m_burst and m_length are both encoded as one less than their real meaning — a common convention that lets a 2-bit field represent 4 possible sizes (1 through 4 bytes) and a 3-bit field represent 8 possible counts (1 through 8 transfers), rather than wasting an encoding on "0 bytes" or "0 transfers." m_addr is constrained to always be 4-byte aligned, at the class level, so this rule applies to every transaction regardless of anything else layered on top later.
Constraining a Transaction to a Slave's Address Window
Now the class is randomized with inline constraints targeting a specific slave's address range:
module tb;
int slave_start;
int slave_end;
BusTransaction bt;
// Assume we are targeting a slave with addr range 0x200 to 0x800
initial begin
slave_start = 32'h200;
slave_end = 32'h800;
bt = new;
bt.randomize() with { m_addr >= slave_start;
m_addr < slave_end;
(m_burst + 1) * (m_length + 1) + m_addr < slave_end;
};
bt.display();
end
endmodule
Output
ncsim> run ------ Transaction 0------ Addr = 0x6e0 Data = 0xbbe5ea58 Burst = 4 bytes/xfr Length = 5 ncsim: *W,RNQUIE: Simulation is complete.
The first two inline constraints bound where the transaction starts: 0x6e0 (1760 in decimal) falls between slave_start (512) and slave_end (2048). But a burst transaction doesn't just touch its starting address — it spans (burst size) × (number of transfers) bytes total. With 4 bytes per transfer and 5 transfers, this transaction covers 20 bytes, ending at 1760 + 20 = 1780 — still comfortably under 2048, thanks to the third constraint. Without it, nothing would stop a burst from starting inside the valid window and then running past its end.
The class's own c_addr constraint is still in force too, even though it isn't repeated inline — 0x6e0 is divisible by 4, confirming the 4-byte alignment rule from the class definition combined seamlessly with the inline range constraints.
Quick Check
Q: If m_addr were 2040 — still comfortably under slave_end (2048) on its own — with a burst of 4 bytes/xfr and 5 transfers (20 bytes total), would this transaction pass the third constraint?
Show Answer
No. 2040 + 20 = 2060, which is not less than 2048 — this would violate the third constraint, even though the starting address alone (2040) satisfies both of the simpler range checks. This is exactly the scenario the third constraint exists to catch.
Where Is This Used?
This exact pattern — an address-range constraint combined with a burst-aware end-of-transfer check — is standard for testing any memory-mapped peripheral, regardless of the specific bus protocol (AXI, APB, WishBone, and others all share this same basic shape). It guarantees generated stimulus never targets memory outside a peripheral's decoded address range, even when a burst's last byte would otherwise spill past the boundary.
Common Beginner Mistakes
Mistake #1: Forgetting the class-level constraint still applies
As this example shows, c_addr's alignment rule stays in force even though the inline constraint never mentions it. Why? Inline constraints add to a class's existing constraints, they don't replace them — every rule declared in the class is still active during this randomization.
Mistake #2: Bounding only the starting address of a burst
As the Quick Check shows, checking just m_addr >= slave_start and m_addr < slave_end isn't enough on its own. Why? A burst spans multiple bytes starting from that address — without a constraint accounting for the full span, the transaction's later bytes could still land outside the target window.
Mistake #3: Miscounting the burst/length encoding
m_burst + 1 gives bytes per transfer, and m_length + 1 gives the number of transfers — not the raw field values themselves. Why? Forgetting the "off by one" encoding convention leads to computing a span that's smaller than the transaction actually uses, silently undermining the whole boundary check.
Mistake #4: Assuming a simple range constraint is sufficient stimulus coverage
Real protocol constraints usually need several rules working together — alignment, starting range, and burst span, in this case — not just one broad bound. Why? A single simplistic constraint can look correct while still allowing scenarios (like a burst overrunning its target) that a real protocol would never actually permit.
Practice Exercise
Challenge: Check Two Candidate Transactions
Using a slave range of slave_start = 0x100 (256) and slave_end = 0x400 (1024), evaluate whether each of these transactions would satisfy all three inline constraints from this article: Candidate A — addr 900, burst 2 bytes/xfr, length 4 transfers. Candidate B — addr 1010, burst 4 bytes/xfr, length 8 transfers.
Hint
For each candidate, compute the total span (bytes per transfer × number of transfers) and check whether addr + span stays under slave_end, in addition to the simple starting-address bounds.
Solution
Candidate A passes. 900 falls within [256, 1024). Its span is 2 × 4 = 8 bytes, ending at 908 — still under 1024.
Candidate B fails. 1010 is within [256, 1024) on its own, but its span is 4 × 8 = 32 bytes, ending at 1042 — past slave_end. This is exactly the same failure mode demonstrated in this article's own Quick Check: a starting address that looks fine in isolation, undone by the burst's own span.
Summary
In this tutorial, you learned:
- A realistic bus transaction constraint combines class-level rules (like address alignment) with inline constraints targeting a specific test scenario
- Bounding only a burst's starting address isn't enough — the transaction's full span has to be accounted for to guarantee it stays within a target window
- Encoded fields like burst size and transfer length often use an "off by one" convention, worth double-checking before computing a span
- Real protocol stimulus typically needs several constraints working together, not one broad range check alone
Here are several practical constraint examples, each building on the one before it, modeling increasingly realistic memory-partitioning scenarios you'll actually encounter on real projects.
22 min read | Advanced Level
What You'll Learn
- How to constrain a single memory block's start and end address within a larger address range
- How to partition memory into a random number of equal-sized regions using
foreach - How to extend that to variable-sized regions whose sizes must sum to an exact total
- How to model program/data/space regions using weighted distributions and multiple coordinated arrays
Memory Block Randomization
Assume a 2KB SRAM in the design, and the need to find a block of addresses within that space for some particular purpose:
class MemoryBlock;
bit [31:0] m_ram_start; // Start address of RAM
bit [31:0] m_ram_end; // End address of RAM
rand bit [31:0] m_start_addr; // Pointer to start address of block
rand bit [31:0] m_end_addr; // Pointer to last addr of block
rand int m_block_size; // Block size in KB
constraint c_addr { m_start_addr >= m_ram_start; // Block addr should be more than RAM start
m_end_addr <= m_ram_end; // Block addr should be less than RAM end
m_start_addr % 4 == 0; // Block addr should be aligned to 4-byte boundary
m_end_addr == m_start_addr + m_block_size - 1; };
constraint c_blk_size { m_block_size inside {64, 128, 512 }; }; // Block's size should be either 64/128/512 bytes
function void display();
$display ("------ Memory Block --------");
$display ("RAM StartAddr = 0x%0h", m_ram_start);
$display ("RAM EndAddr = 0x%0h", m_ram_end);
$display ("Block StartAddr = 0x%0h", m_start_addr);
$display ("Block EndAddr = 0x%0h", m_end_addr);
$display ("Block Size = %0d bytes", m_block_size);
endfunction
endclass
module tb;
initial begin
MemoryBlock mb = new;
mb.m_ram_start = 32'h0;
mb.m_ram_end = 32'h7FF; // 2KB RAM
mb.randomize();
mb.display();
end
endmodule
Output
ncsim> run ------ Memory Block -------- RAM StartAddr = 0x0 RAM EndAddr = 0x7ff Block StartAddr = 0x714 Block EndAddr = 0x753 Block Size = 64 bytes ncsim: *W,RNQUIE: Simulation is complete.
0x714 (1812) plus a 64-byte block gives an end address of 1812 + 64 - 1 = 1875, which is 0x753 — matching exactly.
Quick Check
Q: Would m_start_addr = 0x7FC ever be a legal result, given a 64-byte block size?
Show Answer
No. The constraint only bounds where the block starts, not where it ends — but a start address that close to m_ram_end combined with any nonzero block size would push m_end_addr well past the RAM's actual boundary, which this particular constraint doesn't explicitly guard against.
Equal Partitions of Memory
Now partition the same 2KB SRAM into N equally-sized partitions:
class MemoryBlock;
bit [31:0] m_ram_start; // Start address of RAM
bit [31:0] m_ram_end; // End address of RAM
rand int m_num_part; // Number of partitions
rand bit [31:0] m_part_start []; // Partition start array
rand int m_part_size; // Size of each partition
rand int m_tmp;
// Constrain number of partitions RAM has to be divided into
constraint c_parts { m_num_part > 4; m_num_part < 10; }
// Constraint size of each partition
constraint c_size { m_part_size == (m_ram_end - m_ram_start)/m_num_part; }
// Constrain start addr of each partition
constraint c_part { m_part_start.size() == m_num_part;
foreach (m_part_start[i]) {
if (i)
m_part_start[i] == m_part_start[i-1] + m_part_size;
else
m_part_start[i] == m_ram_start;
}
}
function void display();
$display ("------ Memory Block --------");
$display ("RAM StartAddr = 0x%0h", m_ram_start);
$display ("RAM EndAddr = 0x%0h", m_ram_end);
$display ("# Partitions = %0d", m_num_part);
$display ("Partition Size = %0d bytes", m_part_size);
$display ("------ Partitions --------");
foreach (m_part_start[i])
$display ("Partition %0d start = 0x%0h", i, m_part_start[i]);
endfunction
endclass
module tb;
initial begin
MemoryBlock mb = new;
mb.m_ram_start = 32'h0;
mb.m_ram_end = 32'h7FF; // 2KB RAM
mb.randomize();
mb.display();
end
endmodule
Output
ncsim> run ------ Memory Block -------- RAM StartAddr = 0x0 RAM EndAddr = 0x7ff # Partitions = 9 Partition Size = 227 bytes ------ Partitions -------- Partition 0 start = 0x0 Partition 1 start = 0xe3 Partition 2 start = 0x1c6 Partition 3 start = 0x2a9 Partition 4 start = 0x38c Partition 5 start = 0x46f Partition 6 start = 0x552 Partition 7 start = 0x635 Partition 8 start = 0x718 ncsim: *W,RNQUIE: Simulation is complete.
With 9 partitions, 2047 / 9 = 227 (integer division — the remainder is simply discarded, meaning the very last few bytes of RAM aren't covered by any partition). Each successive start address is confirmed to be exactly 227 more than the last, all the way through partition 8.
Variable Memory Partitions
Instead of equal sizes, let each partition's size vary, drawn from a fixed set of legal sizes, with the total required to sum to exactly the full RAM size:
class MemoryBlock;
bit [31:0] m_ram_start; // Start address of RAM
bit [31:0] m_ram_end; // End address of RAM
rand int m_num_part; // Number of partitions
rand bit [31:0] m_part_start []; // Partition start array
rand int m_part_size []; // Size of each partition
rand int m_tmp;
// Constrain number of partitions RAM has to be divided into
constraint c_parts { m_num_part > 4; m_num_part < 10; }
// Constraint size of each partition
constraint c_size { m_part_size.size() == m_num_part;
m_part_size.sum() == m_ram_end - m_ram_start + 1;
foreach (m_part_size[i])
m_part_size[i] inside {16, 32, 64, 128, 512, 1024};
}
// Constrain start addr of each partition
constraint c_part { m_part_start.size() == m_num_part;
foreach (m_part_start[i]) {
if (i)
m_part_start[i] == m_part_start[i-1] + m_part_size[i-1];
else
m_part_start[i] == m_ram_start;
}
}
function void display();
$display ("------ Memory Block --------");
$display ("RAM StartAddr = 0x%0h", m_ram_start);
$display ("RAM EndAddr = 0x%0h", m_ram_end);
$display ("# Partitions = %0d", m_num_part);
$display ("------ Partitions --------");
foreach (m_part_start[i])
$display ("Partition %0d start = 0x%0h, size = %0d bytes", i, m_part_start[i], m_part_size[i]);
endfunction
endclass
module tb;
initial begin
MemoryBlock mb = new;
mb.m_ram_start = 32'h0;
mb.m_ram_end = 32'h7FF; // 2KB RAM
mb.randomize();
mb.display();
end
endmodule
Output
ncsim> run ------ Memory Block -------- RAM StartAddr = 0x0 RAM EndAddr = 0x7ff # Partitions = 7 ------ Partitions -------- Partition 0 start = 0x0, size = 512 bytes Partition 1 start = 0x200, size = 128 bytes Partition 2 start = 0x280, size = 64 bytes Partition 3 start = 0x2c0, size = 1024 bytes Partition 4 start = 0x6c0, size = 128 bytes Partition 5 start = 0x740, size = 128 bytes Partition 6 start = 0x7c0, size = 64 bytes ncsim: *W,RNQUIE: Simulation is complete.
This time the 7 partition sizes (512, 128, 64, 1024, 128, 128, 64) sum to exactly 2048 — the full RAM size, unlike the equal-partition example's integer-division remainder. Each partition's start address correctly follows the previous partition's start plus its own size, with zero gaps and zero overlap.
Quick Check
Q: Why does this example's constraint use m_ram_end - m_ram_start + 1, while the equal-partitions example used (m_ram_end - m_ram_start) / m_num_part without the +1?
Show Answer
Because this constraint needs the partitions to add up to the RAM's total byte count (2048), which requires the +1 since m_ram_end is the address of the last valid byte, not one past it. The equal-partitions example instead divides that same span across a variable number of partitions, and simply accepts that integer division may leave a small remainder uncovered.
Variable Memory Partitions With Space in Between
Now add a gap — possibly zero bytes — between each partition:
class MemoryBlock;
bit [31:0] m_ram_start; // Start address of RAM
bit [31:0] m_ram_end; // End address of RAM
rand int m_num_part; // Number of partitions
rand bit [31:0] m_part_start []; // Partition start array
rand int m_part_size []; // Size of each partition
rand int m_space[]; // Space between each partition
rand int m_tmp;
// Constrain number of partitions RAM has to be divided into
constraint c_parts { m_num_part > 4; m_num_part < 10; }
// Constraint size of each partition
constraint c_size { m_part_size.size() == m_num_part;
m_space.size() == m_num_part - 1;
m_space.sum() + m_part_size.sum() == m_ram_end - m_ram_start + 1;
foreach (m_part_size[i]) {
m_part_size[i] inside {16, 32, 64, 128, 512, 1024};
if (i < m_space.size())
m_space[i] inside {0, 16, 32, 64, 128, 512, 1024};
}
}
// Constrain start addr of each partition
constraint c_part { m_part_start.size() == m_num_part;
foreach (m_part_start[i]) {
if (i)
m_part_start[i] == m_part_start[i-1] + m_part_size[i-1] + m_space[i-1];
else
m_part_start[i] == m_ram_start;
}
}
function void display();
$display ("------ Memory Block --------");
$display ("RAM StartAddr = 0x%0h", m_ram_start);
$display ("RAM EndAddr = 0x%0h", m_ram_end);
$display ("# Partitions = %0d", m_num_part);
$display ("------ Partitions --------");
foreach (m_part_start[i])
$display ("Partition %0d start = 0x%0h, size = %0d bytes, space = %0d bytes", i, m_part_start[i], m_part_size[i], m_space[i]);
endfunction
endclass
module tb;
initial begin
MemoryBlock mb = new;
mb.m_ram_start = 32'h0;
mb.m_ram_end = 32'h7FF; // 2KB RAM
mb.randomize();
mb.display();
end
endmodule
Output
ncsim> run ------ Memory Block -------- RAM StartAddr = 0x0 RAM EndAddr = 0x7ff # Partitions = 5 ------ Partitions -------- Partition 0 start = 0x0, size = 128 bytes, space = 64 bytes Partition 1 start = 0xc0, size = 32 bytes, space = 128 bytes Partition 2 start = 0x160, size = 32 bytes, space = 0 bytes Partition 3 start = 0x180, size = 1024 bytes, space = 512 bytes Partition 4 start = 0x780, size = 128 bytes, space = 0 bytes ncsim: *W,RNQUIE: Simulation is complete.
m_space is deliberately sized to m_num_part - 1 (4 elements for 5 partitions, since space only exists between partitions, not after the last one) — but display()'s foreach loop iterates over m_part_start's indices, all 5 of them, and prints m_space[i] for every single one, including index 4. That index is out of bounds for a 4-element array. The space = 0 bytes shown for the final partition isn't a genuine constrained value — it's an out-of-bounds read that happens to return 0, the default value for int. Adding up only the first 4 (legitimate) space values with all 5 partition sizes gives exactly 2048, confirming the last "space" figure isn't part of the actual solution at all.
Partition for Programs and Data
Finally, a more realistic scenario: memory partitioned into program, data, and empty-space regions, with the count and size of each driven by its own set of constraints, and a weighted distribution controlling how program sizes are chosen:
typedef struct {
int start_addr;
int end_addr;
} e_range;
class Space;
rand int num_pgm; // Total number of programs required
rand int num_data; // Total number of data blocks required
rand int num_space; // Total number of empty spaces required
rand int max_pgm_size; // Maximum program size
rand int max_data_size; // Maximum data size
rand int num_max_pgm; // Maximum number of programs
rand int pgm_size[]; // Size of each program region
rand int data_size[]; // Size of each data region
rand int space_size[]; // Size of each empty space region
int total_ram; // Total RAM space
// Constrain maximum individual program region size to be 512 bytes
// data region size to be 128 bytes and maximum number of programs in
// this memory region to be 100
constraint c_num_size { max_pgm_size == 512;
max_data_size == 128;
num_max_pgm == 100;
}
// Constrain total number of programs, data and space regions
constraint c_num { num_pgm inside {[1:num_max_pgm]};
num_data inside {[1:50]};
num_space inside {[1:50]};
}
// Constrain the array for program, data and space to equal the number
// decided by the above constraints.
constraint c_size { pgm_size.size() == num_pgm;
data_size.size() == num_data;
space_size.size() == num_space;
}
// Size of each program/data/space is stored into indices of the corresponding
// arrays. So, total size of RAM should be the sum of all programs + data + space
constraint c_ram { foreach (pgm_size[i]) {
// pgm_size[i] inside {4, 8, 32, 64, 128, 512};
pgm_size[i] dist {[128:512]:/75, [32:64]:/20, [4:8]:/10};
pgm_size[i] % 4 == 0;
}
foreach (data_size[i]) {
data_size[i] inside {64, 128, 512, 1024};
}
foreach (space_size[i]) {
space_size[i] inside {4, 8, 32, 64, 128, 512, 1024};
}
total_ram == pgm_size.sum() + data_size.sum() + space_size.sum();
}
// Function to display the partitioning
function void display();
$display("#pgms=%0d #data=%0d, #space=%0d", num_pgm, num_data, num_space);
$display("#pgms.size=%0d #data.size=%0d, #space.size=%0d total=%0d", pgm_size.sum(), data_size.sum(), space_size.sum(), total_ram);
foreach(pgm_size[i])
$display("pgm#%0d size=%0d bytes", i, pgm_size[i]);
foreach(data_size[i])
$display("data#%0d size=%0d bytes", i, data_size[i]);
foreach(space_size[i])
$display("space#%0d size=%0d bytes", i, space_size[i]);
endfunction
endclass
module tb;
initial begin
Space sp = new();
sp.total_ram = 6 * 1024; // Assuem total 6KB memory space
assert(sp.randomize());
sp.display();
end
endmodule
Output
ncsim> run #pgms=37 #data=18, #space=47 #pgms.size=3792 #data.size=1216, #space.size=1136 total=6144 pgm#0 size=4 bytes pgm#1 size=200 bytes pgm#2 size=384 bytes pgm#3 size=4 bytes pgm#4 size=60 bytes pgm#5 size=44 bytes pgm#6 size=4 bytes pgm#7 size=4 bytes pgm#8 size=396 bytes pgm#9 size=164 bytes pgm#10 size=40 bytes pgm#11 size=188 bytes pgm#12 size=148 bytes pgm#13 size=152 bytes pgm#14 size=4 bytes pgm#15 size=48 bytes pgm#16 size=4 bytes pgm#17 size=32 bytes pgm#18 size=36 bytes pgm#19 size=180 bytes pgm#20 size=8 bytes pgm#21 size=4 bytes pgm#22 size=144 bytes pgm#23 size=48 bytes pgm#24 size=448 bytes pgm#25 size=4 bytes pgm#26 size=148 bytes pgm#27 size=4 bytes pgm#28 size=4 bytes pgm#29 size=4 bytes pgm#30 size=4 bytes pgm#31 size=4 bytes pgm#32 size=32 bytes pgm#33 size=4 bytes pgm#34 size=356 bytes pgm#35 size=476 bytes pgm#36 size=4 bytes data#0 size=64 bytes data#1 size=64 bytes data#2 size=64 bytes data#3 size=64 bytes data#4 size=64 bytes data#5 size=64 bytes data#6 size=64 bytes data#7 size=64 bytes data#8 size=64 bytes data#9 size=128 bytes data#10 size=64 bytes data#11 size=64 bytes data#12 size=64 bytes data#13 size=64 bytes data#14 size=64 bytes data#15 size=64 bytes data#16 size=64 bytes data#17 size=64 bytes space#0 size=4 bytes space#1 size=4 bytes space#2 size=4 bytes space#3 size=4 bytes space#4 size=4 bytes space#5 size=4 bytes space#6 size=4 bytes space#7 size=4 bytes space#8 size=128 bytes space#9 size=8 bytes space#10 size=4 bytes space#11 size=4 bytes space#12 size=4 bytes space#13 size=4 bytes space#14 size=32 bytes space#15 size=64 bytes space#16 size=512 bytes space#17 size=4 bytes space#18 size=32 bytes space#19 size=4 bytes space#20 size=4 bytes space#21 size=128 bytes space#22 size=4 bytes space#23 size=4 bytes space#24 size=4 bytes space#25 size=4 bytes space#26 size=8 bytes space#27 size=4 bytes space#28 size=4 bytes space#29 size=4 bytes space#30 size=4 bytes space#31 size=8 bytes space#32 size=4 bytes space#33 size=4 bytes space#34 size=4 bytes space#35 size=4 bytes space#36 size=64 bytes space#37 size=4 bytes space#38 size=4 bytes space#39 size=4 bytes space#40 size=4 bytes space#41 size=8 bytes space#42 size=4 bytes space#43 size=4 bytes space#44 size=4 bytes space#45 size=4 bytes space#46 size=4 bytes ncsim: *W,RNQUIE: Simulation is complete.
The three region counts (37 programs, 18 data blocks, 47 spaces) and their total sizes (3792 + 1216 + 1136 = 6144) match the 6KB total_ram exactly. Every one of the 37 program sizes is both divisible by 4 and falls within one of the three dist ranges ([4:8], [32:64], or [128:512]) — and with that distribution weighted 75% toward the largest range, it's no coincidence that most program sizes shown are on the larger end, though the heavily-weighted small values (many programs sized at exactly 4 bytes) still show up as expected from the remaining 10% weight on [4:8].
Where Is This Used?
This exact family of techniques — sizing dynamic arrays via constraints, chaining each element's start address off the previous one's end, and mixing inside ranges with weighted dist distributions — is the standard toolkit for generating realistic memory maps in SoC and memory-controller verification, where the goal is to exercise many different, legal partitioning scenarios without ever hand-writing them individually.
Common Beginner Mistakes
Mistake #1: Bounding only a block's start address, not its full extent
As the first Quick Check shows, a block's start address staying within range doesn't guarantee its end address does too, once a variable size is involved. Why? Any constraint modeling a sized region needs to account for where that region actually ends, not just where it begins.
Mistake #2: Reusing a loop bound sized for one array to index into a differently-sized array
As the flagged example shows, iterating with an index meant for a 5-element array while reading from a 4-element one produces a silent out-of-bounds access. Why? The read doesn't crash or warn in this case — it just returns a default value that can look deceptively like a real result.
Mistake #3: Forgetting the +1 when a sum needs to cover an inclusive address range
As the second Quick Check explains, m_ram_end - m_ram_start and m_ram_end - m_ram_start + 1 mean different things — a byte count spanning an inclusive range always needs the +1. Why? Omitting it undercounts the true size of the range by exactly one byte, which matters when a sum constraint needs to match it exactly.
Mistake #4: Assuming dist weights alone guarantee every value in a range is equally likely
As the final example shows, a 75% weight on [128:512] doesn't mean every individual value in that range is equally probable relative to values in the other two ranges — it governs the combined probability of landing anywhere in that range at all. Why? This is the same range-vs-individual-value distinction covered for dist in earlier articles, just applied here at a larger scale.
Practice Exercise
Challenge: Fix the Out-of-Bounds Display
Rewrite the display() function from the "Variable Memory Partitions With Space in Between" example so it never reads past the end of m_space.
Hint
The constraint block itself already uses the right guard — if (i < m_space.size()) — before touching m_space[i]. Apply that same guard inside the display loop.
Solution
function void display();
$display ("------ Memory Block --------");
$display ("RAM StartAddr = 0x%0h", m_ram_start);
$display ("RAM EndAddr = 0x%0h", m_ram_end);
$display ("# Partitions = %0d", m_num_part);
$display ("------ Partitions --------");
foreach (m_part_start[i]) begin
if (i < m_space.size())
$display ("Partition %0d start = 0x%0h, size = %0d bytes, space = %0d bytes",
i, m_part_start[i], m_part_size[i], m_space[i]);
else
$display ("Partition %0d start = 0x%0h, size = %0d bytes",
i, m_part_start[i], m_part_size[i]);
end
endfunction
The last partition now simply omits the "space" field entirely, rather than printing a misleading value read from outside the array's actual bounds.
Summary
In this tutorial, you learned:
- A single memory block can be constrained to fall within a larger address range using bounds on its start address, alignment, and computed end address
- An array of partition start addresses can be built entirely from constraints, with each element defined relative to the one before it via
foreach - Array reduction methods like
sum()let a constraint require a set of variable-sized regions to add up to an exact total - Combining
insideranges with weighteddistdistributions across several coordinated dynamic arrays can model a realistic, multi-region memory map in a single randomize() call - A loop bound sized for one array can silently read out of bounds on a differently-sized array — always match the guard condition to the specific array actually being indexed
SystemVerilog randomization also works on array-like structures inside a class — static arrays, dynamic arrays, and queues. As with any other variable, the array itself has to be declared rand or randc to make it, and its elements, randomizable.
6 min read | Intermediate Level
What You'll Learn
- How randomizing a static array differs from randomizing a scalar
- Why a dynamic array or queue needs a size constraint before its elements can be randomized meaningfully
- How to constrain individual array elements with
foreach - What happens when you leave an array's size unconstrained
Randomizing Static Arrays
Randomizing a static array is straightforward and works just like any other rand variable — every element gets a fresh random value, each independently within its declared range:
class Packet;
rand bit [3:0] s_array [7]; // Declare a static array with "rand"
endclass
module tb;
Packet pkt;
// Create a new packet, randomize it and display contents
initial begin
pkt = new();
pkt.randomize();
$display("queue = %p", pkt.s_array);
end
endmodule
Output
ncsim> run
queue = '{'hf, 'hf, 'h2, 'h9, 'he, 'h4, 'ha}
ncsim: *W,RNQUIE: Simulation is complete.
s_array has a fixed size of 7 elements, each a 4-bit value (0 to 15, shown in hex above), and no extra syntax is needed beyond the rand qualifier — the size is already known at declaration time, so there's nothing else for the solver to figure out besides the element values.
Randomizing Dynamic Arrays
Dynamic arrays don't have a size fixed at declaration — that's what the empty square brackets [] mean below. Because of that, the array's length is itself treated as an implicit random variable, and you'll usually want to constrain it explicitly with .size(). In this example, one constraint keeps the size somewhere between 5 and 10 (exclusive on both ends, so anywhere from 6 to 9), and a second constraint, using foreach, sets each element equal to its own index:
class Packet;
rand bit [3:0] d_array []; // Declare a dynamic array with "rand"
// Constrain size of dynamic array between 5 and 10
constraint c_array { d_array.size() > 5; d_array.size() < 10; }
// Constrain value at each index to be equal to the index itself
constraint c_val { foreach (d_array[i])
d_array[i] == i;
}
// Utility function to display dynamic array contents
function void display();
foreach (d_array[i])
$display ("d_array[%0d] = 0x%0h", i, d_array[i]);
endfunction
endclass
module tb;
Packet pkt;
// Create a new packet, randomize it and display contents
initial begin
pkt = new();
pkt.randomize();
pkt.display();
end
endmodule
If you don't constrain a dynamic array's or queue's size at all, the solver is free to pick any legal size for it — including zero, leaving you with an unexpectedly empty array. Always constrain .size() explicitly if you need a predictable length.
Output
ncsim> run d_array[0] = 0x0 d_array[1] = 0x1 d_array[2] = 0x2 d_array[3] = 0x3 d_array[4] = 0x4 d_array[5] = 0x5 d_array[6] = 0x6 d_array[7] = 0x7 d_array[8] = 0x8 ncsim: *W,RNQUIE: Simulation is complete.
The array size was randomized to 9 (satisfying c_array, since 9 is greater than 5 and less than 10), and the element at each index equals the index itself (satisfying c_val).
Quick Check
Q: If you removed constraint c_array entirely from the class above, what could happen to d_array's size?
Show Answer
It would become unconstrained, so the solver could legally pick any size, including 0 — an empty array. c_val's foreach constraint would still hold for whatever size ends up chosen, since it applies per-index rather than fixing the count.
Randomizing Queues
Queues work the same way as dynamic arrays — declare them rand and constrain their .size() if you need a specific length:
class Packet;
rand bit [3:0] queue [$]; // Declare a queue with "rand"
// Constrain size of queue to exactly 4
constraint c_array { queue.size() == 4; }
endclass
module tb;
Packet pkt;
// Create a new packet, randomize it and display contents
initial begin
pkt = new();
pkt.randomize();
// Tip : Use %p to display arrays
$display("queue = %p", pkt.queue);
end
endmodule
Output
ncsim> run
queue = '{'hf, 'hf, 'h2, 'h9}
ncsim: *W,RNQUIE: Simulation is complete.
Here c_array pins the queue's size to exactly 4 elements, so unlike the dynamic array example, every call to randomize() produces the same length — only the element values change.
Where Is Array Randomization Used?
Randomized arrays and queues are a natural fit for variable-length packet payloads and burst transactions — constrain the size to a legal burst length, then let each element (or a foreach constraint tying elements together) generate the payload contents automatically.
Common Beginner Mistakes
Mistake #1: Leaving a dynamic array's or queue's size unconstrained
Without a .size() constraint, the array's length is randomized right along with its elements. Why? This can silently produce an empty array on some runs, which is easy to miss until something downstream (like a loop over the array) behaves unexpectedly with zero iterations.
Mistake #2: Writing a per-element constraint without foreach
A constraint like d_array[i] == i; only makes sense wrapped in a foreach (d_array[i]) loop inside the constraint block. Why? Without foreach, there's no i to loop over, and the constraint simply won't compile or apply to every index the way you intend.
Mistake #3: Assuming static arrays need special randomization syntax
A static array declared rand randomizes exactly like a scalar variable does — no extra constraint or syntax is required just to make it work. Why? Its size is already fixed at declaration time, so the solver only has element values left to figure out, unlike dynamic arrays and queues where size is also in play.
Practice Exercise
Challenge: Constrain a Queue to Even Values
Declare a rand bit [7:0] queue with exactly 3 elements, and add a foreach constraint so that each element equals its index multiplied by 2 (so the queue always ends up {0, 2, 4}).
Hint
Use the same foreach (queue_name[i]) queue_name[i] == i * 2; pattern shown in the dynamic array example, just applied to a queue with a fixed size constraint instead.
Solution
class Packet;
rand bit [7:0] data_q [$];
constraint c_size { data_q.size() == 3; }
constraint c_val {
foreach (data_q[i])
data_q[i] == i * 2;
}
endclass
module tb;
Packet pkt;
initial begin
pkt = new();
pkt.randomize();
$display("data_q = %p", pkt.data_q);
end
endmodule
c_size fixes the queue at exactly 3 elements, and c_val's foreach constraint ties each element to its index, so every call to randomize() produces the same values — {0, 2, 4} — even though the queue is technically still rand.
Summary
In this tutorial, you learned:
- Static arrays randomize like any other
randvariable — their size is already fixed, so only element values are randomized - Dynamic arrays and queues treat their own size as an implicit random variable unless you constrain it with
.size() - Leaving a dynamic array's or queue's size unconstrained can produce an empty array on some runs
foreachinside a constraint block lets you tie each array element to its index or to other elements- A queue with a size fixed by constraint keeps a consistent length across calls to
randomize(), while its element values still vary
Continuing to Constraints
With arrays and queues covered, the natural next step is SystemVerilog Constraints, which goes deeper into the constraint styles briefly introduced across this chapter — ranges, inside, and weighted dist distributions.
A class variable such as pkt is only a name by which an object is known — it can hold the handle to an object of a class, but until it's assigned something, it is always null. This article looks closely at the difference between a handle and the object it points to, what happens when two handles point to the same object, and how to build arrays of objects using fixed, dynamic, and associative arrays.
7 min read | Intermediate Level
What You'll Learn
- The difference between a class handle and a class object
- Why accessing a property through a
nullhandle causes a runtime error - What happens when two handles are assigned to the same object
- How to build fixed, dynamic, and associative arrays of class objects
What Is a Class Handle?
When you declare a variable of a class type, SystemVerilog does not create an object — it only creates a handle, a reference that can later point to an object. Until that handle is assigned the result of a new() call, it points to nothing, and its value is null.
// Create a new class with a single member called
// count that stores integer values
class Packet;
int count;
endclass
module tb;
// Create a "handle" for the class Packet that can point to an
// object of the class type Packet
// Note: This "handle" now points to NULL
Packet pkt;
initial begin
if (pkt == null)
$display ("Packet handle 'pkt' is null");
// Display the class member using the "handle"
// Expect a run-time error because pkt is not an object
// yet, and is still pointing to NULL. So pkt is not
// aware that it should hold a member
$display ("count = %0d", pkt.count);
end
endmodule
Output
ncsim> run
Packet handle 'pkt' is null
count = ncsim: *E,TRNULLID: NULL pointer dereference.
File: ./testbench.sv, line = 18, pos = 33
Scope: tb
Time: 0 FS + 0
./testbench.sv:18 $display ("count = %0d", pkt.count);
ncsim> exit
Accessing a property or method through a handle that is still null is one of the most common simulation errors in SystemVerilog — reported as a null pointer dereference (or "null object access"). The fix is always the same: make sure new() has been called before the handle is used.
null is a keyword, not a string. Comparing a handle to the literal text "null" is a type mismatch and will not compile — always compare with pkt == null.
What Is a Class Object?
An instance of a class is created only when its new() function is invoked. To reference that object again later, you assign its handle to a variable of the matching class type.
// Create a new class with a single member called
// count that stores integer values
class Packet;
int count;
endclass
module tb;
// Create a "handle" for the class Packet that can point to an
// object of the class type Packet
// Note: This "handle" now points to NULL
Packet pkt;
initial begin
if (pkt == null)
$display ("Packet handle 'pkt' is null");
// Call the new() function of this class
pkt = new();
if (pkt == null)
$display ("What's wrong, pkt is still null ?");
else
$display ("Packet handle 'pkt' is now pointing to an object, and not NULL");
// Display the class member using the "handle"
$display ("count = %0d", pkt.count);
end
endmodule
Output
ncsim> run Packet handle 'pkt' is null Packet handle 'pkt' is now pointing to an object, and not NULL count = 0 ncsim: *W,RNQUIE: Simulation is complete.
Notice that count prints as 0 even though it was never explicitly assigned. SystemVerilog initializes integer-type class properties to their default value (0 for int) at the moment the object is constructed, the same way module-level variables default to a known value.
Quick Check
Q: Why does the last $display (the one that reads pkt.count) succeed in this example, while the same line in the previous example caused a null pointer dereference?
Show Answer
The first $display in both examples only checks pkt == null, which is comparing the handle itself — that's always safe, even on a null handle. The error only happens when you try to access a member through the handle, like pkt.count, before new() has been called. In this second example, pkt = new() runs first, so by the time pkt.count is accessed, the object already exists.
What Happens When Two Handles Point to the Same Object?
If you assign one handle to another, the second handle does not get its own copy of the object — it simply starts pointing to the same memory as the first.
// Create a new class with a single member called
// count that stores integer values
class Packet;
int count;
endclass
module tb;
// Create two "handles" for the class Packet
// Note: These "handles" now point to NULL
Packet pkt, pkt2;
initial begin
// Call the new() function of this class and
// assign the member some value
pkt = new();
pkt.count = 16'habcd;
// Display the class member using the "pkt" handle
$display ("[pkt] count = 0x%0h", pkt.count);
// Make pkt2 handle to point to pkt and print member variable
pkt2 = pkt;
$display ("[pkt2] count = 0x%0h", pkt2.count);
end
endmodule
Output
ncsim> run [pkt] count = 0xabcd [pkt2] count = 0xabcd ncsim: *W,RNQUIE: Simulation is complete.
Now pkt and pkt2 both point to the same instance of Packet. This is because pkt2 = pkt did not create a new object — it only copied the handle, so both names now refer to the same memory. If you changed pkt2.count after this point, reading pkt.count would show the new value too, since there's only one object behind both names.
This handle-copy behavior is exactly why SystemVerilog provides a separate copy() convention (often hand-written, or via the built-in shallow-copy method) when you actually want a second, independent object with the same property values rather than two names for the same one.
Arrays of Class Objects
Just like a single class variable, each element of an array of class objects is its own handle, and starts out as null until it's individually constructed with new().
Fixed Array
A fixed-size array, also known as a static array, is declared with a specific size at compile time. In this example, fixed_array can hold exactly 5 Packet objects, and that size is locked in when the code compiles.
Packet fixed_array [5]; // Declares a fixed array of 5 Packet objects
// Define the Packet class
class Packet;
int count;
// Constructor to initialize count
function new(int c = 0);
count = c;
endfunction
endclass
module tb;
// Declare a fixed array of Packet objects
Packet fixed_array[5];
initial begin
$display("--- Fixed Array Example ---");
// Initialize each element of the fixed array
for (int i = 0; i < 5; i++) begin
fixed_array[i] = new(i * 10); // Create a new Packet object and assign it
end
// Access and display data from the fixed array
for (int i = 0; i < 5; i++) begin
$display("fixed_array[%0d].count = %0d", i, fixed_array[i].count);
end
// Example of accessing a null element if not initialized (would cause an error if dereferenced)
// assert(fixed_array[0] != null); // Check if initialized
end
endmodule
Output
xcelium> run --- Fixed Array Example --- fixed_array[0].count = 0 fixed_array[1].count = 10 fixed_array[2].count = 20 fixed_array[3].count = 30 fixed_array[4].count = 40 xmsim: *W,RNQUIE: Simulation is complete.
Dynamic Array
A dynamic array is declared without a specific size and can grow or shrink at runtime. You allocate it using the new[size] syntax.
Packet dynamic_array[]; // Declares a dynamic array of Packet objects
dynamic_array = new[10]; // Initializes the array with a size of 10
Here, dynamic_array starts out empty. The call to new[10] allocates space for 10 handles, each of which still needs its own new() call before it points to an actual Packet object.
module tb;
initial begin
// Declare a dynamic array of Packet objects
Packet dynamic_array[];
$display("--- Dynamic Array Example ---");
// Initialize the dynamic array with a specific size
dynamic_array = new[3]; // Creates space for 3 Packet references
// Initialize each element of the dynamic array
for (int i = 0; i < dynamic_array.size(); i++) begin
dynamic_array[i] = new(i + 1); // Create new Packet objects
end
// Access and display data
foreach (dynamic_array[i]) begin
$display("dynamic_array[%0d].count = %0d", i, dynamic_array[i].count);
end
end
endmodule
Output
xcelium> run --- Dynamic Array Example --- dynamic_array[0].count = 1 dynamic_array[1].count = 2 dynamic_array[2].count = 3 xmsim: *W,RNQUIE: Simulation is complete.
Associative Array
An associative array uses a key, rather than a numerical index, to access elements. The key can be an integer, a string, or another data type, and the array only stores elements that have been explicitly added.
Packet assoc_array[*]; // Declares an associative array of Packet objects
assoc_array[100] = new; // Adds a Packet object with key 100
assoc_array["header"] = new; // Adds a Packet object with key "header"
Here, assoc_array is declared with a wildcard index [*], so it can be indexed by any integral expression. The integer 100 is used directly, and the string literal "header" is automatically cast to a bit vector of equivalent size, so it is still an integral key. Non-integral index values are illegal for a wildcard array, and an associative array has only one index type, declared once; to use real string keys, declare it as Packet assoc_array[string], as in the example below. This is useful when the range of indices isn't known up front, or when you want to associate an object with a meaningful label instead of a plain number.
module tb;
// Declare an associative array where the key is a string and the value is a Packet object
Packet assoc_array[string];
initial begin
$display("--- Associative Array Example ---");
// Assign Packet objects to the associative array using string keys
assoc_array["packet_A"] = new(50);
assoc_array["packet_B"] = new(75);
assoc_array["packet_C"] = new(100);
// Access and display data using keys
$display("assoc_array[\"packet_A\"].count = %0d", assoc_array["packet_A"].count);
$display("assoc_array[\"packet_C\"].count = %0d", assoc_array["packet_C"].count);
// Iterate through the associative array (order is not guaranteed unless specified)
foreach (assoc_array[k]) begin
$display("Key: %s, Count: %0d", k, assoc_array[k].count);
end
// Check if a key exists
if (assoc_array.exists("packet_B")) begin
$display("Packet_B exists in the associative array.");
end
end
endmodule
Output
xcelium> run --- Associative Array Example --- assoc_array["packet_A"].count = 50 assoc_array["packet_C"].count = 100 Key: packet_A, Count: 50 Key: packet_B, Count: 75 Key: packet_C, Count: 100 Packet_B exists in the associative array. xmsim: *W,RNQUIE: Simulation is complete.
The foreach loop above happens to iterate in insertion order in this run, but the code's own comment is correct to caution that associative array iteration order isn't formally guaranteed — don't rely on it matching insertion order.
Where Is This Used?
Scoreboards and transaction trackers in verification environments frequently use associative arrays of class objects, keyed by a transaction ID or address, so a monitor can look up the matching expected transaction the moment a response arrives — without scanning through a fixed-size or dynamic array every time.
Common Beginner Mistakes
Mistake #1: Accessing a member through a handle before calling new()
Wrong: Packet pkt; $display("count = %0d", pkt.count);
Right: Packet pkt; pkt = new(); $display("count = %0d", pkt.count);
Why? A handle on its own is null. Reading a property through a null handle causes a null pointer dereference, since there's no object in memory for count to belong to.
Mistake #2: Assuming pkt2 = pkt creates a second, independent object
Wrong: Changing pkt2.count and expecting pkt.count to stay the same.
Right: Treat pkt and pkt2 as two names for the same object after a plain handle assignment — a change through either one is visible through both.
Why? pkt2 = pkt only copies the handle, not the object it points to. To get a second, independent object, you need a separate call to new().
Mistake #3: Declaring a fixed or dynamic array of objects and skipping the per-element new() call
Wrong: Packet fixed_array [5]; fixed_array[0].count = 10;
Right: Packet fixed_array [5]; fixed_array[0] = new(); fixed_array[0].count = 10;
Why? Declaring Packet fixed_array [5] only reserves five handles, all initialized to null. Each element still needs its own new() call before it becomes a usable object.
Practice Exercise
Challenge: Independent vs. Aliased Handles
Using the Packet class from this article, write a small testbench that creates one object pkt with count = 5. Then create a second handle pkt_alias that points to the same object as pkt, and a third handle pkt_copy that points to a brand new, independent object also constructed with count = 5. Change pkt.count to 99, then display count through all three handles to confirm which ones changed.
Hint
pkt_alias should be created with a plain handle assignment (pkt_alias = pkt;), while pkt_copy needs its own call to new() with the same starting value.
Solution
class Packet;
int count;
function new (int c = 0);
count = c;
endfunction
endclass
module tb;
Packet pkt, pkt_alias, pkt_copy;
initial begin
pkt = new (5);
pkt_alias = pkt; // Same object as pkt
pkt_copy = new (5); // A separate, independent object
pkt.count = 99;
$display ("pkt.count = %0d", pkt.count);
$display ("pkt_alias.count = %0d", pkt_alias.count);
$display ("pkt_copy.count = %0d", pkt_copy.count);
end
endmodule
pkt_alias.count also shows 99, since pkt_alias and pkt point to the same object. pkt_copy.count still shows 5, since it was built with its own new() call and is a completely separate object.
Summary
In this tutorial, you learned:
- A class handle is just a reference — it stays
nulluntilnew()is called to construct an actual object - Accessing a property or method through a
nullhandle causes a runtime null pointer dereference - Assigning one handle to another (
pkt2 = pkt) makes both handles point to the same object, not two separate objects - Fixed arrays, dynamic arrays, and associative arrays can all hold class objects, but every element still needs its own
new()call before use
wait fork lets the current process wait until every process it has forked is over — the opposite of disable fork, which terminates them instead. This is useful when a process needs to spawn multiple threads, do some other work in the meantime, and only later pause to make sure all of that spawned work has actually finished.
7 min read | Intermediate Level
What You'll Learn
- What
wait forkdoes, and how it differs fromdisable fork - How
wait forkbehaves after afork...join_anyleaves some threads still running - Why
wait forkwaits for every immediate child process of the current process, not just the most recent fork block - When to reach for
wait forkinstead ofdisable fork
A Basic wait fork Example
This reuses the same three-thread setup from the disable fork article — three threads are kicked off in parallel with fork...join_any, and the main process resumes as soon as any one of them finishes. This time, instead of disabling the remaining threads, the main process waits for all of them to finish with wait fork:
module tb_top;
initial begin
// Fork off 3 sub-threads in parallel and the currently executing main thread
// will finish when any of the 3 sub-threads have finished.
fork
// Thread1 : Will finish first at time 40ns
#40 $display ("[%0t ns] Show #40 $display statement", $time);
// Thread2 : Will finish at time 70ns
begin
#20 $display ("[%0t ns] Show #20 $display statement", $time);
#50 $display ("[%0t ns] Show #50 $display statement", $time);
end
// Thread3 : Will finish at time 60ns
#60 $display ("[%0t ns] TIMEOUT", $time);
join_any
// Display as soon as the fork is done
$display ("[%0t ns] Fork join is done, wait fork to end", $time);
// Wait until all forked processes are over and display
wait fork;
$display ("[%0t ns] Fork join is over", $time);
end
endmodule
Output
ncsim> run [20 ns] Show #20 $display statement [40 ns] Show #40 $display statement [40 ns] Fork join is done, wait fork to end [60 ns] TIMEOUT [70 ns] Show #50 $display statement [70 ns] Fork join is over ncsim: *W,RNQUIE: Simulation is complete.
The main process resumes at 40ns, same as before, right after Thread1 finishes. But this time, instead of moving straight on, wait fork blocks until the two remaining threads — Thread3 (60ns) and Thread2 (70ns) — both finish. "Fork join is over" only prints at 70ns, once the slowest of the two remaining threads completes.
Quick Check
Q: If Thread2's total delay above were shortened so it finished at 55ns instead of 70ns, at what time would "Fork join is over" print?
Show Answer
60ns. wait fork waits for every remaining thread, so it resolves once the last one finishes — with Thread2 now finishing at 55ns and Thread3 still at 60ns, Thread3 becomes the slower of the two.
Does wait fork Wait for Every Process?
To see the full scope of wait fork, this example forks two more processes after the first join_any, before calling wait fork:
module tb_top;
initial begin
// Fork off 3 sub-threads in parallel and the currently executing main thread
// will finish when any of the 3 sub-threads have finished.
fork
// Thread1 : Will finish first at time 40ns
#40 $display ("[%0t ns] Show #40 $display statement", $time);
// Thread2 : Will finish at time 70ns
begin
#20 $display ("[%0t ns] Show #20 $display statement", $time);
#50 $display ("[%0t ns] Show #50 $display statement", $time);
end
// Thread3 : Will finish at time 60ns
#60 $display ("[%0t ns] TIMEOUT", $time);
join_any
// Display as soon as the fork is done
$display ("[%0t ns] Fork join is done, wait fork to end", $time);
// Fork two more processes
fork
#10 $display ("[%0t ns] Wait for 10", $time);
#20 $display ("[%0t ns] Wait for 20", $time);
join_any
// Wait until ALL forked processes are over
wait fork;
$display ("[%0t ns] Fork join is over", $time);
end
endmodule
Output
ncsim> run [20 ns] Show #20 $display statement [40 ns] Show #40 $display statement [40 ns] Fork join is done, wait fork to end [50 ns] Wait for 10 [60 ns] TIMEOUT [60 ns] Wait for 20 [70 ns] Show #50 $display statement [70 ns] Fork join is over ncsim: *W,RNQUIE: Simulation is complete.
At 40ns, a second fork...join_any spawns two more threads (finishing 10ns and 20ns later, so at 50ns and 60ns respectively), and resumes as soon as the faster one finishes — "Wait for 10" at 50ns. At that point, wait fork is called. Notice it doesn't just wait for the second fork's leftover thread ("Wait for 20," at 60ns) — it also waits for Thread2 and Thread3, still pending from the first fork block, all the way back at the top of the process. "Fork join is over" only prints at 70ns, once every one of those remaining threads — from both fork blocks — has finished.
wait fork covers every immediate child process of the current process, regardless of which fork statement spawned them — not just the most recent one. That's narrower than disable fork, though: disable fork reaches an entire descendant tree (children, their children, and so on), while wait fork only waits on the current process's direct children, not on anything those children themselves go on to fork.
Where Is wait fork Used?
wait fork is the right tool when you need results from every spawned thread rather than discarding whatever hasn't finished — for example, running several independent checkers in parallel and needing every one of them to actually complete and report before deciding whether a test passed, instead of cutting any of them off early with disable fork.
Common Beginner Mistakes
Mistake #1: Confusing wait fork with disable fork
One waits for spawned processes to finish; the other terminates them. Why? Using disable fork when you actually needed the results of a still-running thread throws that work away, while using wait fork when you meant to abandon a stuck thread can stall the process indefinitely instead.
Mistake #2: Assuming wait fork only covers the most recent fork block
As the second example shows, wait fork waits for every immediate child process of the current process — including threads left over from an earlier, unrelated fork statement. Why? This can make wait fork take much longer than expected if older background threads from earlier in the same process are still running.
Mistake #3: Not accounting for how long wait fork might actually block
Code right after wait fork doesn't execute until every remaining immediate child process finishes, however long that takes. Why? If one of those background threads is a long-running or even indefinite task, wait fork will block for just as long — it's not a quick synchronization checkpoint unless you already know every spawned thread finishes promptly.
Practice Exercise
Challenge: Predict the Output
Using the basic wait fork example from earlier, suppose Thread3's delay were changed from #60 to #80. At what time would "Fork join is over" print, and which thread would be the last one wait fork is waiting on?
Hint
The main process still resumes at 40ns when Thread1 finishes first. From there, work out each remaining thread's own finish time and take the latest one.
Solution
80ns, waiting on Thread3. With Thread3 now finishing at 80ns instead of 60ns, it becomes the slowest of the two remaining threads (Thread2 still finishes at 70ns), so wait fork now resolves at 80ns instead of 70ns.
Summary
In this tutorial, you learned:
wait forkblocks the current process until every process it has forked has finished, instead of terminating them likedisable forkdoes- After a
fork...join_anyleaves threads running,wait forkresolves once the slowest of the remaining threads finishes wait fork's scope covers every immediate child process of the current process, not just the most recently forked block — though unlikedisable fork, it doesn't reach any further than that process's direct children- Use
wait forkwhen you need the results or side effects of every spawned thread; usedisable forkwhen you need to abandon whatever's still running wait forkcan block for as long as its slowest remaining thread takes, including an indefinitely long one
Continuing to Interprocess Communication
With threads and processes covered, continue with SystemVerilog Interprocess Communication to start the next chapter — covering events, semaphores, and mailboxes for coordinating concurrent processes safely.
Quiz
No quiz questions available for this article.