A SystemVerilog semaphore is a built-in class that works like a bucket with a fixed number of keys. A process has to get a key from the bucket before it can continue, and other processes have to wait until a key becomes available. Semaphores are used for mutual exclusion, controlling access to a shared resource, and basic synchronization between processes.
8 min read | Intermediate Level
What You'll Learn
- How a single-key semaphore enforces mutual exclusion (a mutex)
- The semaphore syntax and its four built-in methods
try_get(), the non-blocking way to check for a key without waiting- How a semaphore with more than one key lets several processes proceed at once
- When to use a semaphore instead of a mailbox or an event
Syntax
semaphore [identifier_name];
semaphore is a built-in class, so it's used just like any other class object: declared, then constructed with new().
Methods
| Method | Description |
|---|---|
function new (int keyCount = 0); | Specifies the number of keys initially allocated to the bucket |
function void put (int keyCount = 1); | Returns the given number of keys to the bucket |
task get (int keyCount = 1); | Blocks until the given number of keys can be obtained from the bucket |
function int try_get (int keyCount = 1); | Attempts to obtain keys immediately, without blocking; returns a positive value on success, 0 if not enough keys are available |
get() is a task because it can block. put() and try_get() are both functions because neither one ever waits: try_get() just reports failure immediately instead of blocking.
Two more rules from the standard are worth knowing. Processes blocked in get() wait in a first-in first-out queue, so they are served in the order they started waiting. And the bucket is not capped at its starting count: a put() always adds keys, so a semaphore can end up holding more keys than new() gave it.
A Basic Example: Mutual Exclusion With One Key
With a single key, a semaphore behaves as a mutex, so only one process can hold it at a time. Here, two people compete for the same library room, which only has one key available:
module tb_top;
semaphore key;
initial begin
key = new (1);
fork
personA ();
personB ();
#25 personA ();
join_none
end
task getRoom (bit [1:0] id);
$display ("[%0t] Trying to get a room for id[%0d] ...", $time, id);
key.get (1);
$display ("[%0t] Room Key retrieved for id[%0d]", $time, id);
endtask
task putRoom (bit [1:0] id);
$display ("[%0t] Leaving room id[%0d] ...", $time, id);
key.put (1);
$display ("[%0t] Room Key put back id[%0d]", $time, id);
endtask
task personA ();
getRoom (1);
#20 putRoom (1);
endtask
task personB ();
#5 getRoom (2);
#10 putRoom (2);
endtask
endmodule
Output
[0] Trying to get a room for id[1] ... [0] Room Key retrieved for id[1] [5] Trying to get a room for id[2] ... [20] Leaving room id[1] ... [20] Room Key put back id[1] [20] Room Key retrieved for id[2] [25] Trying to get a room for id[1] ... [30] Leaving room id[2] ... [30] Room Key put back id[2] [30] Room Key retrieved for id[1] [50] Leaving room id[1] ... [50] Room Key put back id[1]
personA grabs the only key immediately at 0ns. personB's attempt at 5ns blocks on key.get(1), since no key is available, and it doesn't succeed until personA returns the key at 20ns.
The same pattern repeats at 25ns, when personA's second call competes with personB, who still holds the key. Notice that "Room Key put back" prints before "Room Key retrieved": put() only wakes the waiting process, which runs after the current one moves on.
Quick Check
Q: With only one key in the bucket, could two processes ever both be inside their "room" (between get() and put()) at the same simulation time?
Show Answer
No. That's exactly what a one-key semaphore guarantees. get() only succeeds once a key is actually available, so a second process attempting get() while the first still holds the only key is forced to block until it's returned.
try_get(): Checking for a Key Without Waiting
Sometimes blocking indefinitely on get() isn't what you want. You'd rather check whether a key is available right now, and do something else immediately if it isn't. That's exactly what try_get() is for:
module tb;
semaphore key;
initial begin
key = new (1);
fork
// Process A takes the only key and holds it for 30ns
begin
key.get (1);
$display ("[%0t] Process A acquired the key", $time);
#30 key.put (1);
$display ("[%0t] Process A released the key", $time);
end
// Process B checks at 10ns, without blocking, whether a key is free
begin
#10;
if (key.try_get (1))
$display ("[%0t] Process B got the key immediately", $time);
else
$display ("[%0t] Process B could not get the key right now - moving on instead of waiting", $time);
end
join
end
endmodule
Output
[0] Process A acquired the key [10] Process B could not get the key right now - moving on instead of waiting [30] Process A released the key
Process A takes the only key at 0ns and doesn't release it until 30ns. When Process B calls try_get(1) at 10ns, the key isn't available. Instead of blocking like get() would, try_get() returns 0 immediately, and Process B moves straight into the else branch.
If Process B's check happened at a moment when the key was available, try_get(1) would succeed, actually take the key (just like get() would), and Process B would need to put() it back later. The only difference from get() is what happens when a key isn't available: try_get() fails and returns instantly instead of waiting.
Quick Check
Q: If Process B's try_get(1) check above happened at 35ns instead of 10ns, what would it return?
Show Answer
A positive value (success). Process A releases the key at 30ns, so by 35ns a key is available again, and try_get(1) would succeed immediately and take it.
Where Is try_get() Used?
try_get() is useful when a component should use a shared resource only if it's free right now, and fall back to some other action instead of stalling. In a testbench, a background process might try to grab a shared bus between transactions and simply skip that cycle when another process holds it.
A Semaphore With Multiple Keys
A semaphore isn't limited to acting as a mutex. Giving it more than one key lets that many processes proceed concurrently, and a process only blocks once every key is checked out:
module tb;
semaphore pool;
task automatic use_resource (int id);
pool.get (1);
$display ("[%0t] Worker %0d acquired a resource", $time, id);
#10 pool.put (1);
$display ("[%0t] Worker %0d released a resource", $time, id);
endtask
initial begin
pool = new (3); // 3 resources available at once
fork
use_resource (1);
use_resource (2);
use_resource (3);
use_resource (4); // no key left for this one - has to wait
join
end
endmodule
Output
[0] Worker 1 acquired a resource [0] Worker 2 acquired a resource [0] Worker 3 acquired a resource [10] Worker 1 released a resource [10] Worker 2 released a resource [10] Worker 3 released a resource [10] Worker 4 acquired a resource [20] Worker 4 released a resource
With 3 keys available, Worker 1, Worker 2, and Worker 3 all acquire a resource at 0ns without blocking each other. Worker 4 has nothing left to take, so it blocks until the first release at 10ns, then releases its own key 10ns later, at 20ns.
The order of lines within one time step comes from the order in which the simulator runs the forked processes, which the standard leaves open. Another simulator may print the three releases at 10ns in a different order.
Getting and Returning Several Keys at Once
Every method takes a key count, so a process can ask for more than one key in a single call. get(2) waits until two keys are in the bucket at the same time:
module tb;
semaphore key;
initial begin
key = new (1); // one key to start with
key.put (2); // the bucket now holds 3 keys
$display ("[%0t] try_get(3) returned %0d", $time, key.try_get (3));
$display ("[%0t] try_get(1) returned %0d", $time, key.try_get (1));
fork
begin key.get (2); $display ("[%0t] Got 2 keys", $time); end
begin #10 key.put (1); $display ("[%0t] Put 1 key back", $time);
#10 key.put (1); $display ("[%0t] Put 1 more key back", $time); end
join
end
endmodule
Output
[0] try_get(3) returned 1 [0] try_get(1) returned 0 [10] Put 1 key back [20] Put 1 more key back [20] Got 2 keys
The semaphore starts with one key, but put(2) raises the count to three, more than new() gave it. try_get(3) takes all three, so the next try_get(1) fails. get(2) then waits through the first put(1) at 10ns, because one key is not enough, and only returns at 20ns when the second key arrives.
Semaphore, Mailbox or Event?
SystemVerilog has three built-in ways for processes to coordinate, and each one answers a different need:
| Mechanism | What it does | Typical use |
|---|---|---|
semaphore | Counts keys; a process waits until it can take one | Sharing a bus, a memory model or a fixed number of resources |
| mailbox | Passes data objects from one process to another in order | Sending transactions from a generator to a driver |
| event | Signals that something happened, without carrying data | Telling one process that another has reached a point |
A semaphore carries no data at all. If one process needs to hand something to another, use a mailbox. If it only needs to say "now", use an event. The Interprocess Communication overview compares all three.
Common Beginner Mistakes
Mistake #1: Forgetting to put a key back
Every get() (or successful try_get()) needs a matching put(). Why? If a task takes a key and exits early, through an error path for instance, without returning it, every other process waiting for that key blocks forever: a classic deadlock.
Mistake #2: Using get() when try_get() was actually needed
get() blocks indefinitely if no key is available; try_get() never blocks at all. Why? If the intent was "use the resource only if it's free right now, otherwise do something else," get() is the wrong choice, because it commits the calling process to waiting, however long that takes.
Mistake #3: Assuming a semaphore is always a mutex
A semaphore only behaves as a mutex when it's created with exactly one key. Why? With new(3) or any count above 1, multiple processes can legitimately hold a key at the same time. It's a resource pool, not an exclusive lock. An extra put() can also turn a one-key mutex into a pool by accident.
Practice Exercise
Challenge: Add a Non-Blocking Check to the Resource Pool
Using the 3-key resource pool example above, add a fifth worker that checks with try_get() at time 0 (alongside the other four) instead of blocking with get(), and prints whether it succeeded.
Hint
At time 0, only 3 keys exist and workers 1 through 3 already claim them. Think about whether a try_get() call racing against those same three would have anything left to take.
Solution
task try_use_resource (int id);
if (pool.try_get (1))
$display ("[%0t] Worker %0d got a resource immediately", $time, id);
else
$display ("[%0t] Worker %0d found no resource available - skipping", $time, id);
endtask
// Add to the fork block, after use_resource (4):
// try_use_resource (5);
When the simulator runs the forked processes in the order they are written, workers 1 to 3 take all three keys first and Worker 5 prints the "skipping" message at 0ns. The standard does not fix that order, so on another simulator Worker 5 could run earlier and get a key. Either way, unlike get(), it never sits waiting for a key to free up.
Summary
In this tutorial, you learned:
- A semaphore is a bucket of keys; a process needs a key to proceed and returns it when done
get()blocks until a key is available;put()returns a key;try_get()attempts to get a key without ever blocking and returns 0 when it fails- Waiting processes are served in first-in first-out order, and
put()can raise the key count above its starting value - A semaphore created with exactly one key behaves as a mutex, allowing only one process at a time
- A semaphore created with more than one key lets that many processes proceed concurrently before any of them has to wait
- A semaphore carries no data; use a mailbox to pass data and an event to signal
Continuing the Interprocess Communication Chapter
Continue with SystemVerilog Mailbox for passing data between components.
SystemVerilog's randcase statement is a case-like construct that randomly picks exactly one of its branches to execute, weighted by positive integer values you assign to each branch. Unlike an ordinary case statement, where the branch that runs depends on comparing an expression against each item, no expression decides which randcase branch runs — the solver does, based purely on the weights you give it.
6 min read | Intermediate Level
What You'll Learn
- What
randcaseis and how it differs from an ordinarycasestatement - How branch weights convert into selection probabilities
- What happens with a zero-weight branch, and with every branch weighted zero
- How SystemVerilog picks a branch internally from a single random draw
Syntax: randcase
Each branch is a positive integer weight followed by a colon and a statement to execute if that branch is chosen:
randcase
item : statement;
...
endcase
Parameters:
item— a non-negative integer expression representing that branch's weight (zero is legal, and simply means the branch is never taken)statement— the statement executed if this branch is selected
The probability of any one branch being selected is that branch's weight divided by the sum of all the weights in the block.
Weighted Random Branch Selection
In the example below, the weights are 1, 5, and 3, which sum to 9. That makes the first branch's probability 1/9 (11.11%), the second branch's probability 5/9 (55.56%), and the third branch's probability 3/9 (33.33%):
module tb;
initial begin
for (int i = 0; i < 10; i++)
randcase
1 : $display ("Wt 1");
5 : $display ("Wt 5");
3 : $display ("Wt 3");
endcase
end
endmodule
Output
ncsim> run Wt 5 Wt 5 Wt 3 Wt 5 Wt 1 Wt 3 Wt 5 Wt 3 Wt 3 Wt 5 ncsim: *W,RNQUIE: Simulation is complete.
Note that Wt 5 appeared the most (the highest-probability branch), Wt 1 appeared the least (the lowest-probability branch), and Wt 3 landed somewhere in between — exactly what the weights predict over enough iterations.
Quick Check
Q: If the three weights above were changed to 2, 2, and 2 instead of 1, 5, and 3, what would the probability of each branch be?
Show Answer
An equal 1/3 (33.33%) each. Probability only depends on each weight relative to the sum — 2/6, 2/6, and 2/6 all reduce to the same 1/3, just like 3/9, 3/9, 3/9 would.
Zero-Weight Branches Are Skipped
If a branch specifies a weight of zero, that branch is simply never taken:
module tb;
initial begin
for (int i = 0; i < 10; i++)
randcase
0 : $display ("Wt 0");
5 : $display ("Wt 5");
3 : $display ("Wt 3");
endcase
end
endmodule
Output
ncsim> run Wt 5 Wt 5 Wt 3 Wt 5 Wt 5 Wt 3 Wt 5 Wt 3 Wt 3 Wt 5 ncsim: *W,RNQUIE: Simulation is complete.
Wt 0 never appears in the output — with a weight of 0, that branch contributes nothing to the probability calculation, so it can never be the one selected.
What Happens When All Weights Are Zero
Weighting every branch at zero doesn't make sense in practice, but SystemVerilog defines what happens if it occurs: no branch is taken, and the simulator issues a run-time warning instead of a compile-time error.
module tb;
initial begin
for (int i = 0; i < 10; i++)
randcase
0 : $display ("Wt 0.1");
0 : $display ("Wt 0.2");
0 : $display ("Wt 0.3");
endcase
end
endmodule
Output
ncsim> run
ncsim: *W,RANDNOB: The sum of the weight expressions in the randcase statement is 0.
No randcase branch was taken.
File: ./testbench.sv, line = 4, pos = 14
Scope: tb.unmblk1
Time: 0 FS + 0
ncsim: *W,RANDNOB: The sum of the weight expressions in the randcase statement is 0.
No randcase branch was taken.
File: ./testbench.sv, line = 4, pos = 14
Scope: tb.unmblk1
Time: 0 FS + 0
ncsim: *W,RANDNOB: The sum of the weight expressions in the randcase statement is 0.
No randcase branch was taken.
File: ./testbench.sv, line = 4, pos = 14
Scope: tb.unmblk1
Time: 0 FS + 0
...
This warning is easy to miss in a large regression log, especially if the weights come from variables rather than literal numbers — if a weight variable unexpectedly evaluates to 0 for every branch, the intended randomized behavior silently doesn't happen at all.
How the Solver Picks a Branch
Each call to randcase draws one random number in the range 0 up to the sum of the weights. The branches are then checked in declaration order — the first (top) branch's weight covers the smallest random numbers, the next branch covers the following range, and so on — so whichever branch's range contains the drawn number is the one that executes.
Where Is randcase Used?
randcase shows up whenever you want weighted, probabilistic branching without wrapping a variable in a class just to constrain its distribution — for example, mostly generating normal read/write transactions but occasionally injecting an error scenario, or picking between a handful of delay profiles with different likelihoods.
Common Beginner Mistakes
Mistake #1: Assuming weights must add up to 100
randcase weights are not percentages. Why? Probability is always that branch's weight divided by the sum of all weights, so 1, 5, 3 works exactly the same as 10, 50, 30 or 100, 500, 300 — only the ratios between weights matter, not their absolute values.
Mistake #2: Expecting a compile-time error when all weights are zero
An all-zero randcase is legal SystemVerilog — it just does nothing at run time and prints a warning. Why? Because it's a run-time condition (the weights could be variables that only evaluate to zero under certain circumstances), the tool can't catch it at compile time, so nothing stops your simulation from silently skipping that branch selection every single time.
Mistake #3: Confusing randcase with a dist constraint
randcase is a standalone procedural statement that doesn't need a rand variable or a call to randomize() at all — it just runs and picks a branch. Why? A weighted dist constraint, by contrast, only takes effect the next time randomize() is called on the class that contains it. If you need weighted branching outside of a class, randcase is usually the simpler tool; see SystemVerilog Constraints for dist.
Practice Exercise
Challenge: Weighted Transaction Type Selector
Write a randcase block that picks between three transaction types — "READ", "WRITE", and "ERROR" — so that READ and WRITE are equally likely and ERROR is much rarer, roughly a 1-in-20 chance.
Hint
Give READ and WRITE the same weight, and give ERROR a weight that's about 1/20th of that when all three weights are added together.
Solution
module tb;
initial begin
repeat (10) begin
randcase
10 : $display ("READ");
10 : $display ("WRITE");
1 : $display ("ERROR");
endcase
end
end
endmodule
The weights sum to 21, so READ and WRITE are each 10/21 (about 47.6%) — equally likely as each other — while ERROR is only 1/21 (about 4.8%), close to the roughly 1-in-20 target.
Summary
In this tutorial, you learned:
randcaserandomly executes exactly one of its branches, weighted by positive integer values- A branch's selection probability is its weight divided by the sum of all the weights
- A zero-weight branch is never selected; if every branch is weighted zero, none of them run and the simulator issues a run-time warning
- SystemVerilog draws one random number per call and matches it against the branches in declaration order to pick one
randcaseis a standalone statement — it doesn't need arandvariable or a call torandomize()
Continuing the Randomization Chapter
Continue with SystemVerilog Array Randomization in Class to see how rand and randc apply to arrays, queues, and dynamic arrays.
Verilog has significant limitations around global declarations, especially functions and user-defined types:
- Local Scope — every object declared inside a Verilog module is local to that module, so any function or task needed elsewhere has to be re-declared in every module that uses it, leading to redundant code and extra maintenance.
- Hierarchical References — Verilog allows reaching into another module's objects hierarchically, but these references are for verification purposes only and don't represent real hardware, so they aren't synthesizable.
- User-Defined Types — a type needed in multiple modules has to be redefined in each one, without a mechanism for declaring it once, globally.
A SystemVerilog package solves all three: a way to store and share data, methods, properties, and parameters reusable across multiple modules, interfaces, or programs. A package's scope sits at the same level as a top-level module, and keeping definitions between package and endpackage prevents clutter in the global namespace.
16 min read | Intermediate Level
What You'll Learn
- The specific Verilog limitations packages solve
- Basic package syntax, and what's allowed to go inside one
- How wildcard imports differ from importing specific items
- The exact order SystemVerilog uses to resolve an identifier, and why local declarations always win
- Whether importing a package that itself imports another package gives you transitive access to both
- What parts of a package are synthesizable, and which uses are simulation-only
SystemVerilog Package Syntax
package ;
// Typedef declarations
// Function/Task definitions
// ...
endpackage
A package is a separate namespace, not embedded inside any module.
A package cannot contain hierarchical references, except those created within the package itself or through an import.
A Basic Package Example
package my_pkg;
// Create typedef declarations that can be reused in multiple modules
typedef enum bit [1:0] { RED, YELLOW, GREEN, RSVD } e_signal;
typedef struct { bit [3:0] signal_id;
bit active;
bit [1:0] timeout;
} e_sig_param;
// Create function and task defintions that can be reused
// Note that it will be a 'static' method if the keyword 'automatic' is not used
function void calc_parity ();
$display ("Called from somewhere");
endfunction
endpackage
Importing a Package
A package is brought into the current scope with import and the scope resolution operator :::
import ::*; // Imports all items
import ::; // Imports specific item
Wildcard Import
A wildcard import makes a package's declarations visible — but only the ones actually referenced in the importing scope get pulled in; anything unused stays unimported:
// Import the package defined above to use e_signal
import my_pkg::*;
class myClass;
e_signal m_signal;
endclass
module tb;
myClass cls;
initial begin
cls = new();
cls.m_signal = GREEN;
$display ("m_signal = %s", cls.m_signal.name());
calc_parity();
end
endmodule
Output
ncsim> run m_signal = GREEN Called from somewhere ncsim: *W,RNQUIE: Simulation is complete.
Without the import statement, this same code fails to compile at all:
e_signal m_signal; | ncvlog: *E,NOIPRT (testbench.sv,15|8): Unrecognized declaration 'e_signal' could be an unsupported keyword, a spelling mistake or missing instance port list '()' [SystemVerilog]. cls.m_signal = GREEN; | ncvlog: *E,UNDIDN (testbench.sv,23|19): 'GREEN': undeclared identifier [12.5(IEEE)].
Importing Specific Items
Instead of a wildcard, individual items can be imported one at a time — more explicit, but more overhead as more items are needed:
import my_pkg::GREEN;
import my_pkg::e_signal;
import my_pkg::common;
Omitting any one of these causes a compile error, since the compiler has no other way to know where that identifier comes from. Note that this applies per-label, not per-enum — importing the type doesn't automatically import every value that belongs to it:
// Although e_signal is made visible, enumerated labels will not be made visible
import my_pkg::e_signal;
// Import each enumerated label instead, if you are not importing using wildcard ::*
import my_pkg::RED;
import my_pkg::GREEN;
import my_pkg::YELLOW;
// etc
Quick Check
Q: If only import my_pkg::e_signal; is written, and code later tries to use RED unqualified, will that compile?
Show Answer
No. Importing the type e_signal doesn't import its individual enum labels — RED, GREEN, and the rest each need their own explicit import statement (or a wildcard import instead).
Search Order: Why Local Always Wins
Local definitions inside a module or interface always take priority over a wildcard import. An import naming a specific item also takes precedence over a wildcard import. A wildcard import just extends the search: the tool looks for local declarations first, then wildcard-imported packages, and finally $unit's own declaration space — matching the same local-shadows-import rule covered in SystemVerilog Scope Resolution Operator.
package my_pkg;
typedef enum bit { READ, WRITE } e_rd_wr;
endpackage
import my_pkg::*;
module tb;
typedef enum bit { WRITE, READ } e_wr_rd;
initial begin
e_wr_rd opc1 = READ;
e_rd_wr opc2 = READ;
$display ("READ1 = %0d READ2 = %0d ", opc1, opc2);
end
endmodule
Output
ncsim> run READ1 = 1 READ2 = 1 ncsim: *W,RNQUIE: Simulation is complete.
Even though opc2 is declared with the package's type (e_rd_wr), the unqualified READ assigned to it still resolves to the module's own locally-declared READ (value 1, from e_wr_rd's reversed order), not the package's READ (value 0). The variable's declared type doesn't change which READ gets resolved — that's still governed by the search order above.
Forcing the package's own value requires an explicit :::
module tb;
initial begin
e_wr_rd opc1 = READ;
e_rd_wr opc2 = my_pkg::READ;
$display ("READ1 = %0d READ2 = %0d ", opc1, opc2);
end
endmodule
Output
ncsim> run READ1 = 1 READ2 = 0 ncsim: *W,RNQUIE: Simulation is complete.
Quick Check
Q: In the first version above, why does opc2 get 1 instead of the package's READ = 0, given that opc2's type comes from the package?
Show Answer
Because a variable's declared type and the resolution of an unqualified identifier used as its value are two separate things. e_rd_wr (the type) isn't shadowed locally, so it resolves from the package fine — but the literal READ on the right-hand side is a separate identifier lookup, and the module's own local READ shadows the package's, regardless of what type is being assigned to.
Nested Package References
Packages can import other packages. Here, package Y imports package X, and package Z imports package Y:
// Define a new package called X
package X;
byte lb = 8'h10;
int word = 32'hcafe_face;
string name = "X";
function void display();
$display("pkg=%s lb=0x%0h word=0x%0h", name, lb, word);
endfunction
endpackage
// Define a new package called Y, use variable value inside X within Y
package Y;
import X::*;
byte lb = 8'h10 + X::lb;
string name = "Y";
function void display();
$display("pkg=%s lb=0x%0h word=0x%0h", name, lb, word);
endfunction
endpackage
// Define a new package called Z, use variable value inside Y within Z
package Z;
import Y::*;
byte lb = 8'h10 + Y::lb;
string name = "Z";
function void display();
// Note that 'word' exists in package X and not in Y, but X
// is not directly imported here in Z, so the statement below
// will result in a compilation error
//$display("pkg=%s lb=0x%0h word=0x%0h", name, lb, word); // ERROR !
$display("pkg=%s lb=0x%0h", name, lb);
endfunction
endpackage
module tb;
// import only Z package
import Z::*;
initial begin
X::display(); // Direct reference X package
Y::display(); // Direct reference Y package
display(); // Taken from Z package because of import
end
endmodule
Output
Top level design units: X Y Z tb Loading snapshot worklib.tb:sv .................... Done ... xcelium> run pkg=X lb=0x10 word=0xcafeface pkg=Y lb=0x20 word=0xcafeface pkg=Z lb=0x30 xmsim: *W,RNQUIE: Simulation is complete.
Y::display() successfully prints word (0xcafeface) even though Y never declares its own word — it resolves through Y's own wildcard import of X. But Z::display() can't reach word at all, even though Z imports Y, which itself imports X. A wildcard import isn't transitive: importing Y::* gives Z access to what Y itself declares, not to whatever Y only sees because of its own separate import of X.
Quick Check
Q: Could Z::display() reach word if Z added its own import X::*; statement directly?
Show Answer
Yes. Since imports aren't transitive, Z needs to import X itself to see X's declarations directly — importing Y alone never gives Z anything beyond what Y declares on its own.
Where Are Packages Used?
Packages are the standard way a verification environment shares enums, structs, parameters, and utility functions across every component and test in a project — exactly the kind of global reuse Verilog couldn't offer. UVM itself is built and delivered as a package for this reason.
Design Notes: Packages and Synthesis
The synthesizable constructs a package can include are: parameters, local parameters, and constant variables; user-defined types via typedef; fully automatic task and function definitions; and import statements for other packages.
// Define the package for ALU instructions
package alu_pkg;
typedef enum logic [2:0] {
ADD = 3'b000,
SUB = 3'b001,
AND = 3'b010,
OR = 3'b011,
XOR = 3'b100
} alu_op_t;
endpackage
Using a wildcard import to bring everything in:
// Import everything inside the package containing ALU operations
import alu_pkg::*;
module alu (
input logic [2:0] opcode, // ALU operation code
input logic [31:0] a, // First operand
input logic [31:0] b, // Second operand
output logic [31:0] result // Result of the operation
);
always_comb begin
// Enumerations defined in 'alu_pkg' can be directly used here
// because they have been imported
case (opcode)
ADD: result = a + b; // Perform addition
SUB: result = a - b; // Perform subtraction
AND: result = a & b; // Perform bitwise AND
OR: result = a | b; // Perform bitwise OR
XOR: result = a ^ b; // Perform bitwise XOR
default: result = 32'b0; // Default case (optional)
endcase
end
endmodule
Or referencing the package directly, with no import at all:
// Note that package import is not done here
module alu (
input logic [2:0] opcode, // ALU operation code
input logic [31:0] a, // First operand
input logic [31:0] b, // Second operand
output logic [31:0] result // Result of the operation
);
always_comb begin
// Enumerations defined in 'alu_pkg' is directly referenced using ::
case (opcode)
alu_pkg::ADD : result = a + b; // Perform addition
alu_pkg::SUB : result = a - b; // Perform subtraction
alu_pkg::AND : result = a & b; // Perform bitwise AND
alu_pkg::OR : result = a | b; // Perform bitwise OR
alu_pkg::XOR : result = a ^ b; // Perform bitwise XOR
default : result = 32'b0; // Default case (optional)
endcase
end
When a module calls a task or function defined in a package, synthesis replicates that functionality as if it were defined directly inside the module. For a package's tasks and functions to be synthesizable, they must be declared automatic and cannot include static variables.
Synthesis does not support variable declarations inside a package. In simulation, though, a variable declared in a package is shared across every module that imports it — one module can write to it, and another can read the updated value. This is a form of inter-module communication that bypasses module ports entirely, and it's simulation-only, not synthesizable.
Common Beginner Mistakes
Mistake #1: Assuming a wildcard import always wins over a local declaration
As the search-order example shows, it's exactly the opposite — a local declaration always shadows a same-named wildcard-imported identifier. Why? This means a package's value can be silently overridden by an unrelated local declaration sharing the same name, with no warning at compile time.
Mistake #2: Assuming importing a package gives transitive access to what it imports
As the nested package example shows, import Z::*; doesn't give access to whatever Z only sees through Z's own import of Y. Why? Each package's imports are private to that package's own namespace — to reach something two levels deep, you need to import that specific package directly, not just the one that happens to import it.
Mistake #3: Importing a type without importing its individual enum labels
import my_pkg::e_signal; makes the type visible, but not any of its enum values. Why? When importing specific items instead of using a wildcard, every individual label needs its own import statement — the type and its values are treated as entirely separate importable items.
Mistake #4: Assuming any package content synthesizes
Plain variable declarations inside a package work fine in simulation but aren't synthesizable at all. Why? Only parameters, typedefs, fully automatic tasks/functions with no static variables, and import statements are synthesizable — a package used for simulation-only utility state (like the nested X/Y/Z example) won't carry over to a synthesizable design.
Practice Exercise
Challenge: Extend the Chain to Four Packages
Given the X → Y → Z chain from this article, suppose a fourth package, W, does import Z::*; and tries to reference lb (declared in Z) and word (declared only in X). Which reference compiles, and which doesn't?
Hint
Apply the same non-transitivity rule demonstrated by Z trying (and failing) to reach X's word through Y.
Solution
lb compiles fine — it's declared directly inside Z, which W imports directly. word fails to compile, for the exact same reason Z couldn't reach it through Y: W only imports Z, and Z never itself imports X — there's no chain of visibility reaching all the way back to where word is actually declared.
Summary
In this tutorial, you learned:
- Packages solve Verilog's local-scope, non-synthesizable-hierarchical-reference, and type-duplication limitations by providing a shared, reusable namespace
- A wildcard import (
::*) only pulls in items actually referenced; importing specific items requires naming each one, including every individual enum label - Local declarations always take priority over wildcard-imported ones, regardless of the declared type of the variable being assigned
- Package imports are not transitive — importing a package that itself imports another doesn't give you access to that second package's declarations
- Only parameters,
typedefs, fullyautomatictasks/functions, and import statements inside a package are synthesizable; plain variables are simulation-only
SystemVerilog lets you selectively turn randomization off for individual rand or randc class properties, or for an entire object, using the built-in rand_mode() method. A property with randomization disabled behaves exactly as if it had never been declared rand or randc in the first place — it simply keeps whatever value it already holds the next time randomize() is called.
6 min read | Intermediate Level
What You'll Learn
- How
rand_mode()enables or disables randomization for one variable, or for a whole object - How to check a variable's current
rand_mode()state - What happens to a disabled variable's value when
randomize()is called - How disabling a whole object differs from disabling one variable at a time
Syntax: rand_mode()
rand_mode() can be called either as a task, to set the state, or as a function, to read the current state back.
// Disables randomization of variable [variable_name] inside [class_object] class
[class_object].[variable_name].rand_mode (0);
// Enables randomization of variable [variable_name] inside [class_object] class
[class_object].[variable_name].rand_mode (1);
Parameters:
0— disables randomization for the target (task form)1— enables randomization for the target (task form)- no argument — returns the current state as
1(enabled) or0(disabled) (function form)
This is very similar to the constraint_mode() method used to disable constraint blocks — the difference is that rand_mode() targets a variable, while constraint_mode() targets a constraint block.
Randomization Enabled by Default
By default, every variable declared rand or randc has randomization enabled, as this first example confirms before disabling anything:
// Create a class that contains random variables
class Fruits;
rand bit [3:0] var1;
rand bit [1:0] var2;
endclass
module tb;
initial begin
// Instantiate an object of the class
Fruits f = new();
// Print values of those variables before randomization
$display ("Before randomization var1=%0d var2=%0d", f.var1, f.var2);
// rand_mode() is called as a function which returns the state of the given variable
// If it is enabled, then print a statement
if (f.var1.rand_mode())
if (f.var2.rand_mode())
$display ("Randomization of all variables enabled");
// Randomize the class object which in turn randomizes all internal variables
// declared using rand/randc keywords
f.randomize();
// Print the value of these variables after randomization
$display ("After randomization var1=%0d var2=%0d", f.var1, f.var2);
end
endmodule
Output
ncsim> run Before randomization var1=0 var2=0 Randomization of all variables enabled After randomization var1=15 var2=3 ncsim: *W,RNQUIE: Simulation is complete.
Disabling a Single Variable
Next, we'll disable var1 and see how that affects randomization of that one variable:
// Create a class that contains random variables
class Fruits;
rand bit [3:0] var1;
rand bit [1:0] var2;
endclass
module tb;
initial begin
Fruits f = new();
$display ("Before randomization var1=%0d var2=%0d", f.var1, f.var2);
// Turn off randomization for var1
f.var1.rand_mode (0);
// Print if var1 has randomization enabled/disabled
if (f.var1.rand_mode())
$display ("Randomization of var1 enabled");
else
$display ("Randomization of var1 disabled");
f.randomize();
$display ("After randomization var1=%0d var2=%0d", f.var1, f.var2);
end
endmodule
Output
ncsim> run Before randomization var1=0 var2=0 Randomization of var1 disabled After randomization var1=0 var2=3 ncsim: *W,RNQUIE: Simulation is complete.
var1 stays at its pre-randomization value of 0 even after f.randomize() runs, because rand_mode(0) made the solver treat it as if it were never rand in the first place. var2, left enabled, gets a fresh random value as usual.
Quick Check
Q: You call f.var1.rand_mode(0) and then f.randomize(). What value does var1 have afterward?
Show Answer
Whatever value var1 already had before the call — a disabled variable isn't reset to 0 or any other default, it's simply left untouched by the solver.
Disabling All Variables in an Object
Calling rand_mode() directly on the object, without naming a specific variable, applies to every rand/randc property inside it at once:
// Create a class that contains random variables
class Fruits;
rand bit [3:0] var1;
rand bit [1:0] var2;
endclass
module tb;
initial begin
Fruits f = new();
$display ("Before randomization var1=%0d var2=%0d", f.var1, f.var2);
// Turns off randomization for all variables
f.rand_mode (0);
if (! f.var1.rand_mode())
if (! f.var2.rand_mode())
$display ("Randomization of all variables disabled");
f.randomize();
$display ("After randomization var1=%0d var2=%0d", f.var1, f.var2);
end
endmodule
Output
ncsim> run Before randomization var1=0 var2=0 Randomization of all variables disabled After randomization var1=0 var2=0 ncsim: *W,RNQUIE: Simulation is complete.
With every property disabled, f.randomize() still returns successfully, but neither var1 nor var2 changes — there's nothing left for the solver to randomize.
Where Is rand_mode() Used?
rand_mode() is handy when you want to reuse the same object across multiple randomization calls but freeze part of it — for example, locking a packet's protocol version or destination ID after the first randomization so later calls only randomize the payload, or temporarily disabling a field while debugging a specific constraint failure.
Common Beginner Mistakes
Mistake #1: Expecting a disabled variable's value to reset
Calling rand_mode(0) doesn't clear or reset a variable — it just stops the solver from touching it going forward. Why? The variable keeps whatever value it held at the moment you disabled it, which might be its default, or a value left over from an earlier randomization.
Mistake #2: Assuming rand_mode() affects every instance of the class
rand_mode() is called on a specific object handle, like f.var1.rand_mode(0), and only affects that one object. Why? Each instance of a class tracks its own rand_mode state independently, so disabling randomization on one Fruits object has no effect on any other Fruits object you've created.
Mistake #3: Confusing rand_mode() with constraint_mode()
rand_mode() turns off randomization of a variable; constraint_mode() turns off enforcement of a constraint block. Why? Mixing the two up can leave you disabling the wrong thing — disabling a variable's rand_mode doesn't remove constraints that reference it, and disabling a constraint doesn't stop the variable from being randomized.
Practice Exercise
Challenge: Disable var2 Instead
Using the same Fruits class, write code that disables var2 only, then calls randomize() and prints both variables before and after. What do you expect var2 to be after randomization?
Hint
Follow the same pattern as the var1 example, just swap which variable you call rand_mode(0) on.
Solution
class Fruits;
rand bit [3:0] var1;
rand bit [1:0] var2;
endclass
module tb;
initial begin
Fruits f = new();
$display ("Before randomization var1=%0d var2=%0d", f.var1, f.var2);
// Turn off randomization for var2 this time
f.var2.rand_mode (0);
f.randomize();
$display ("After randomization var1=%0d var2=%0d", f.var1, f.var2);
end
endmodule
var2 stays at its pre-randomization value (0, unless something else set it earlier), while var1 is free to take any value from 0 to 15 — the mirror image of the earlier example.
Summary
In this tutorial, you learned:
rand_mode()enables or disables randomization for a single variable, or for everyrand/randcproperty in an object at once- Called with no argument,
rand_mode()returns the current state as1(enabled) or0(disabled) - A disabled variable is skipped by the solver and keeps whatever value it already had
rand_mode()state is tracked per object instance, not per classrand_mode()disables a variable;constraint_mode()disables a constraint block — they are not interchangeable
Continuing the Randomization Chapter
Continue with randcase to see the same enable/disable-style control applied to randomizing control flow itself, or see Disable Constraints for the constraint-block counterpart to rand_mode().
All constraints are enabled by default, and considered by the constraint solver during every call to randomize(). A disabled constraint simply isn't considered at all. Constraints are enabled or disabled at runtime using constraint_mode().
11 min read | Intermediate Level
What You'll Learn
- How
constraint_mode()works both as a task (to enable or disable) and as a function (to check current status) - What actually happens to a variable's legal range once its constraint is disabled
- Why calling
constraint_mode()on a name that isn't an actual constraint is caught at compile time, not run time
Syntax
constraint_mode() can be called both as a task and as a function. Called as a task, it returns nothing, and takes an argument to turn the constraint on or off. Called as a function, it returns the constraint's current state:
// Called as a task
class_obj.const_name.constraint_mode(0); // Turn off the constraint
class_obj.const_name.constraint_mode(1); // Turn on the constraint
// Called as a function
status = class_obj.const_name.constraint_mode(); // status is an int variable to hold return value
constraint_mode() is a built-in method, and cannot be overridden.
Method
When called as a task, the argument means:
| Value | Meaning | Description |
|---|---|---|
| 0 | OFF | Disables the constraint |
| 1 | ON | Enables the constraint |
Example
Here's the effect constraint_mode() has on a simple constraint:
class Fruits;
rand bit[3:0] num; // Declare a 4-bit variable that can be randomized
constraint c_num { num > 4; // Constraint is by default enabled, and applied
num < 9; }; // during randomization giving num a value between 4 and 9
endclass
module tb;
initial begin
Fruits f = new ();
// 1. Print value of num before randomization
$display ("Before randomization num = %0d", f.num);
// 2. Call "constraint_mode" as a function, the return type gives status of constraint
if (f.c_num.constraint_mode ())
$display ("Constraint c_num is enabled");
else
$display ("Constraint c_num is disabled");
// 3. Randomize the class object
f.randomize ();
// 4. Display value of num after randomization
$display ("After randomization num = %0d", f.num);
end
endmodule
Output
ncsim> run Before randomization num = 0 Constraint c_num is enabled After randomization num = 8 ncsim: *W,RNQUIE: Simulation is complete.
With c_num active, num lands within (4, 9) as expected — 8 in this case. Now let's disable the constraint before randomizing:
module tb;
initial begin
Fruits f = new ();
$display ("Before randomization num = %0d", f.num);
// Disable constraint
f.c_num.constraint_mode(0);
if (f.c_num.constraint_mode ())
$display ("Constraint c_num is enabled");
else
$display ("Constraint c_num is disabled");
// Randomize the variable and display
f.randomize ();
$display ("After randomization num = %0d", f.num);
end
endmodule
Output
ncsim> run Before randomization num = 0 Constraint c_num is disabled After randomization num = 15 ncsim: *W,RNQUIE: Simulation is complete.
Turning off the constraint let the solver choose any value the variable's own type supports — num came out as 15, well outside the original (4, 9) window, but still fully valid for a 4-bit variable. Disabling a constraint doesn't set the variable to some fallback value; it simply removes that restriction, reverting the variable to its full natural range.
Quick Check
Q: If f.c_num.constraint_mode(1) were called right after this, then randomize() called again, what range would num fall back into?
Show Answer
(4, 9) again — the same range as the very first example. Re-enabling a constraint restores its original rule exactly, as if it had never been disabled.
Calling constraint_mode() on a Nonexistent Constraint
If constraint_mode() is called on a name that isn't an actual constraint in the class, it's a compile-time error:
module tb;
initial begin
Fruits f = new();
f.c_does_not_exist.constraint_mode(1);
end
endmodule
Output
f.c_does_not_exist.constraint_mode (1);
|
ncvlog: *E,NOTCLM (testbench.sv,11|21): c_does_not_exist is not a class item.
Where Is This Used?
Toggling a constraint at runtime is commonly used to temporarily relax a class's normal legality rules for one specific directed test — deliberately generating an out-of-range or illegal value to check how the DUT handles it — without needing a dedicated subclass just for that one scenario.
Common Beginner Mistakes
Mistake #1: Forgetting constraint_mode() serves two different roles
The same method name works both as a task (with an argument, to set the state) and as a function (with no argument, to query it). Why? Mixing these up — like expecting a return value from the task form, or trying to pass an argument to the function form — won't behave as intended.
Mistake #2: Assuming a disabled constraint sets some fallback value
As the second example shows, disabling c_num didn't reset num to anything specific — it just let the full 4-bit range back in. Why? A disabled constraint is simply removed from consideration; the variable is still randomized, just without that particular restriction.
Mistake #3: Assuming a typo'd constraint name fails silently
As the last example shows, referencing a constraint that doesn't exist is caught at compile time, not left to fail quietly at runtime. Why? This is a genuine compile error (NOTCLM), so a misspelled constraint name will stop compilation rather than producing confusing runtime behavior.
Mistake #4: Assuming constraint_mode() can be overridden
It's explicitly a built-in method. Why? Unlike ordinary class methods, constraint_mode() can't be redefined in a subclass — its behavior is fixed by the language itself.
Practice Exercise
Challenge: Predict the Range Before and After
Given rand bit [5:0] val; and constraint c_val { val inside {[20:30]}; }, what range can val take before disabling c_val, and what range can it take after calling constraint_mode(0) on it?
Hint
Work out the full natural range a 6-bit variable can hold, and compare it against the range the constraint itself specifies.
Solution
Before disabling: 20 to 30, exactly the range c_val specifies. After disabling: 0 to 63, the full range a 6-bit variable can naturally hold — the same pattern as the article's own example, just with a 6-bit variable and a different starting range instead of a 4-bit one.
Summary
In this tutorial, you learned:
constraint_mode()enables or disables a constraint when called as a task with an argument, and reports its current state when called as a function with none- Disabling a constraint doesn't set the variable to a specific value — it simply reverts the variable to its full natural range for that type
- Re-enabling a constraint restores its original rule exactly, as though it had never been turned off
- Calling
constraint_mode()on a name that isn't an actual constraint is a compile-time error, not a silent runtime failure
Quiz
No quiz questions available for this article.