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.