Cover image: Semaphore in SystemVerilog | The Art of Verification

Semaphore in SystemVerilog: get(), put() and try_get(), Tested in One UVM Bench

In short: A semaphore in SystemVerilog is a built-in class, std::semaphore, that guards a shared resource with a bucket of keys. new(n) puts n keys in the bucket, get() takes keys and waits if there aren’t enough, put() returns them, and try_get() takes them only if they’re free right now. With one key it works as a mutex: one process at a time.

Two agents that drive the same bus, three jobs that share two channels: a testbench is full of processes that want the same thing at the same time. The semaphore is the simplest way to make them take turns. I put every rule in this post into one small UVM test and ran it on VCS; the output blocks are what it printed.

A simple way to picture it

Think of an office with two meeting rooms and a bowl with two keys at reception. You take a key, use a room, and drop the key back.

If the bowl is empty, you wait at reception. The bowl is the semaphore, the keys are its count, and taking and returning a key are get() and put().

SystemVerilog semaphore: get, put and try_get on a key bucket, a later get(1) served before a waiting get(2), and two traps, a killed holder and an extra put
How a semaphore hands out keys, with the VCS results

Where semaphore comes from: std::semaphore

semaphore is a class in the built-in std package, next to mailbox and process. Every SystemVerilog file can see it without an import, so semaphore s; and std::semaphore s; mean the same class.

You only need the std:: prefix if your own code declares something else called semaphore.

The methods

Method Waits? What it does
new(n = 0) No Creates the semaphore with n keys
get(n = 1) Yes Takes n keys; waits until n are free
put(n = 1) No Returns n keys to the bucket
try_get(n = 1) No Takes n keys and returns 1 if they’re free; otherwise takes none and returns 0

There’s no method that tells you how many keys are free. The bench has a small helper, tav_count(), that takes every free key with try_get and puts them straight back.

new(1): a mutex

With one key, only one process can be inside the guarded code at a time.

task tav_use_bus(semaphore bus_key, string who);
  `uvm_info("TAV_1", {who, ": waiting for the key"}, UVM_LOW)
  bus_key.get(1);
  `uvm_info("TAV_1", {who, ": got the key, driving the bus"}, UVM_LOW)
  #10;
  bus_key.put(1);
  `uvm_info("TAV_1", {who, ": returned the key"}, UVM_LOW)
endtask

bus_key = new(1);
fork
  tav_use_bus(bus_key, "AGENT_A");
  tav_use_bus(bus_key, "AGENT_B");
join
UVM_INFO testbench.sv(41) @ 0: uvm_test_top [TAV_1] AGENT_A: waiting for the key
UVM_INFO testbench.sv(43) @ 0: uvm_test_top [TAV_1] AGENT_A: got the key, driving the bus
UVM_INFO testbench.sv(41) @ 0: uvm_test_top [TAV_1] AGENT_B: waiting for the key
UVM_INFO testbench.sv(46) @ 10: uvm_test_top [TAV_1] AGENT_A: returned the key
UVM_INFO testbench.sv(43) @ 10: uvm_test_top [TAV_1] AGENT_B: got the key, driving the bus
UVM_INFO testbench.sv(46) @ 20: uvm_test_top [TAV_1] AGENT_B: returned the key

AGENT_B asked at 0 ns but only got the key at 10 ns, the moment AGENT_A put it back. The bus never had two drivers.

new(2): a pool

More than one key lets a fixed number of users in at once. Here three jobs share two channels.

UVM_INFO testbench.sv(52) @ 25: uvm_test_top [TAV_2] job 1 got a channel
UVM_INFO testbench.sv(52) @ 25: uvm_test_top [TAV_2] job 2 got a channel
UVM_INFO testbench.sv(55) @ 45: uvm_test_top [TAV_2] job 1 freed its channel
UVM_INFO testbench.sv(55) @ 45: uvm_test_top [TAV_2] job 2 freed its channel
UVM_INFO testbench.sv(52) @ 45: uvm_test_top [TAV_2] job 3 got a channel
UVM_INFO testbench.sv(55) @ 65: uvm_test_top [TAV_2] job 3 freed its channel

Jobs 1 and 2 started together at 25 ns. Job 3 waited 20 ns for a free channel.

try_get(): don’t wait

try_get() never blocks. It’s for code that has something better to do than wait, like a monitor that skips a sample.

UVM_INFO testbench.sv(83) @ 70: uvm_test_top [TAV_3] try_get: busy, doing something else
UVM_INFO testbench.sv(85) @ 70: uvm_test_top [TAV_3] try_get after put: got the lock

Both lines have the same time stamp: try_get() never waited.

Waiting order: a big get() and a small get()

The live version of this post said waiting processes are served first in, first out, so nobody starves. Part 4 checks that with requests of different sizes.

BIG asks for 2 keys on an empty semaphore. SMALL asks for 1 key, 1 ns later. Then one key comes back every 5 ns.

UVM_INFO testbench.sv(92) @ 75: uvm_test_top [TAV_4] BIG   asks for 2 keys
UVM_INFO testbench.sv(97) @ 76: uvm_test_top [TAV_4] SMALL asks for 1 key
UVM_INFO testbench.sv(102) @ 80: uvm_test_top [TAV_4] put(1)
UVM_INFO testbench.sv(99) @ 80: uvm_test_top [TAV_4] SMALL got 1 key
UVM_INFO testbench.sv(104) @ 85: uvm_test_top [TAV_4] put(1)
UVM_INFO testbench.sv(106) @ 90: uvm_test_top [TAV_4] put(1)
UVM_INFO testbench.sv(94) @ 90: uvm_test_top [TAV_4] BIG   got 2 keys
UVM_INFO testbench.sv(111) @ 100: uvm_test_top [TAV_4] keys left at the end: 0

SMALL asked later but got served first. At 80 ns there was one key: not enough for BIG, enough for SMALL, so VCS gave it to SMALL. BIG had to wait until two more keys came back, at 90 ns.

So “first in, first out” only holds when every request is the same size. With mixed sizes, a stream of small requests can keep a big one waiting for as long as it lasts.

put() without get(): the bucket grows

Nothing stops you from returning a key you never took.

UVM_INFO testbench.sv(117) @ 105: uvm_test_top [TAV_5] new(1): 1 key free
UVM_INFO testbench.sv(119) @ 105: uvm_test_top [TAV_5] after an extra put(1): 2 keys free

A semaphore made as a mutex now has 2 keys, so two processes can be “alone” on the bus at once. Nothing warned about it.

A key that never comes back

Part 6 is the trap that hangs real testbenches. A process takes the key and starts a long job, and a timeout kills it with disable fork before it reaches put().

UVM_INFO testbench.sv(127) @ 110: uvm_test_top [TAV_6] holder got the key, starts a long job
UVM_INFO testbench.sv(132) @ 120: uvm_test_top [TAV_6] timeout: killing the holder
UVM_INFO testbench.sv(135) @ 120: uvm_test_top [TAV_6] keys free after the kill: 0
UVM_INFO testbench.sv(141) @ 170: uvm_test_top [TAV_6] next user still waiting after 50 ns, giving up

Killing the holder didn’t return its key. The semaphore stayed at 0, and the next user would have waited forever without the 50 ns timeout. In a real bench that shows up as a hang, far from the code that caused it.

new() with no count

The default count is 0, so a semaphore made with new() starts with no keys.

UVM_INFO testbench.sv(153) @ 225: uvm_test_top [TAV_7] get(1) on new() still waiting after 50 ns, giving up

Semaphore vs mailbox

Semaphore Mailbox
Carries Nothing, only permission (keys) Data: items or handles
Blocks when Not enough keys on get() Empty on get(), full on put() (if bounded)
Typical use One driver on a shared bus Generator to driver hand-off
Package std::semaphore std::mailbox

What about UVM?

UVM has no semaphore class of its own. Inside a UVM bench you use the same std::semaphore, as this test does.

For sequences that compete for one sequencer, UVM has its own tools, lock() and grab(), so you don’t need a semaphore there. See UVM sequence arbitration for how those work.

The bench: one file, one run

Everything above comes from one file, tav_semaphore.sv (download it as a zip, 2 KB). Paste it into testbench.sv on EDA Playground, pick UVM 1.2, leave design.sv empty and set the top module to tav_top.

One run covers all seven parts, one after another. Parts 6 and 7 wait on a timeout, so the run always ends.

The full code: tav_semaphore.sv

// tav_semaphore.sv : the SystemVerilog semaphore, tested on one small UVM test.
// The Art of Verification (theartofverification.com)
//
// Run on: Synopsys VCS with UVM 1.2 (EDA Playground).
// Paste into testbench.sv, leave design.sv empty. Top module: tav_top.
// All messages go through `uvm_info; the @ time in each line is in ns.
//
// What the run shows, one part after another:
//   1. new(1) as a mutex: two agents share one bus
//   2. new(2) as a pool: three jobs, two channels
//   3. try_get(): don't wait, take another path
//   4. waiting order: a get(2) is waiting, then a get(1) arrives and one key comes back
//   5. put() without get(): the bucket grows past its starting count
//   6. a key lost when the process holding it is killed
//   7. new() with no count: the first get() never returns
// Parts 6 and 7 use a timeout, so the run always ends.

`timescale 1ns/1ns
`include "uvm_macros.svh"

package tav_sem_pkg;
  import uvm_pkg::*;

  class tav_sem_test extends uvm_test;
    `uvm_component_utils(tav_sem_test)

    function new(string name, uvm_component parent);
      super.new(name, parent);
    endfunction

    // how many keys are free right now (takes them all, then puts them back)
    function int tav_count(semaphore s);
      int n = 0;
      while (s.try_get(1)) n++;
      if (n > 0) s.put(n);
      return n;
    endfunction

    // ------------------------------------------------------------ 1. mutex
    task tav_use_bus(semaphore bus_key, string who);
      `uvm_info("TAV_1", {who, ": waiting for the key"}, UVM_LOW)
      bus_key.get(1);
      `uvm_info("TAV_1", {who, ": got the key, driving the bus"}, UVM_LOW)
      #10;
      bus_key.put(1);
      `uvm_info("TAV_1", {who, ": returned the key"}, UVM_LOW)
    endtask

    // ------------------------------------------------------------- 2. pool
    task tav_job(semaphore channels, int id);
      channels.get(1);
      `uvm_info("TAV_2", $sformatf("job %0d got a channel", id), UVM_LOW)
      #20;
      channels.put(1);
      `uvm_info("TAV_2", $sformatf("job %0d freed its channel", id), UVM_LOW)
    endtask

    virtual task run_phase(uvm_phase phase);
      semaphore bus_key, channels, lock, order, extra, leak, empty;
      phase.raise_objection(this);

      // 1. one key: only one agent drives at a time
      bus_key = new(1);
      fork
        tav_use_bus(bus_key, "AGENT_A");
        tav_use_bus(bus_key, "AGENT_B");
      join

      // 2. two keys, three jobs
      #5;
      channels = new(2);
      fork
        tav_job(channels, 1);
        tav_job(channels, 2);
        tav_job(channels, 3);
      join

      // 3. try_get on a busy lock
      #5;
      lock = new(1);
      lock.get(1);
      if (lock.try_get(1)) `uvm_info("TAV_3", "try_get: got the lock", UVM_LOW)
      else                 `uvm_info("TAV_3", "try_get: busy, doing something else", UVM_LOW)
      lock.put(1);
      if (lock.try_get(1)) `uvm_info("TAV_3", "try_get after put: got the lock", UVM_LOW)

      // 4. who goes first: a waiting get(2) or a later get(1)?
      #5;
      order = new(0);
      fork
        begin
          `uvm_info("TAV_4", "BIG   asks for 2 keys", UVM_LOW)
          order.get(2);
          `uvm_info("TAV_4", "BIG   got 2 keys", UVM_LOW)
        end
        begin
          #1 `uvm_info("TAV_4", "SMALL asks for 1 key", UVM_LOW)
          order.get(1);
          `uvm_info("TAV_4", "SMALL got 1 key", UVM_LOW)
        end
        begin
          #5  `uvm_info("TAV_4", "put(1)", UVM_LOW)
          order.put(1);
          #5  `uvm_info("TAV_4", "put(1)", UVM_LOW)
          order.put(1);
          #5  `uvm_info("TAV_4", "put(1)", UVM_LOW)
          order.put(1);
        end
      join_any
      #20;
      `uvm_info("TAV_4", $sformatf("keys left at the end: %0d", tav_count(order)), UVM_LOW)
      disable fork;

      // 5. put without get
      #5;
      extra = new(1);
      `uvm_info("TAV_5", $sformatf("new(1): %0d key free", tav_count(extra)), UVM_LOW)
      extra.put(1);                                   // nobody took one
      `uvm_info("TAV_5", $sformatf("after an extra put(1): %0d keys free", tav_count(extra)), UVM_LOW)

      // 6. the process holding the key is killed
      #5;
      leak = new(1);
      fork
        begin : holder
          leak.get(1);
          `uvm_info("TAV_6", "holder got the key, starts a long job", UVM_LOW)
          #100;
          leak.put(1);
          `uvm_info("TAV_6", "holder returned the key", UVM_LOW)
        end
        #10 `uvm_info("TAV_6", "timeout: killing the holder", UVM_LOW)
      join_any
      disable fork;
      `uvm_info("TAV_6", $sformatf("keys free after the kill: %0d", tav_count(leak)), UVM_LOW)
      fork
        begin
          leak.get(1);
          `uvm_info("TAV_6", "next user got the key", UVM_LOW)
        end
        #50 `uvm_info("TAV_6", "next user still waiting after 50 ns, giving up", UVM_LOW)
      join_any
      disable fork;

      // 7. no starting count
      #5;
      empty = new();
      fork
        begin
          empty.get(1);
          `uvm_info("TAV_7", "get(1) on new() returned", UVM_LOW)
        end
        #50 `uvm_info("TAV_7", "get(1) on new() still waiting after 50 ns, giving up", UVM_LOW)
      join_any
      disable fork;

      phase.drop_objection(this);
    endtask
  endclass
endpackage

module tav_top;
  import uvm_pkg::*;
  import tav_sem_pkg::*;

  initial run_test("tav_sem_test");
endmodule

What VCS printed

VCS X-2025.06-SP1 with UVM 1.2. Every TAV line is shown in its part above; the run ended at 225 ns with this summary:

UVM_INFO .../uvm-1.2/src/base/uvm_objection.svh(1276) @ 225: reporter [TEST_DONE] 'run' phase is ready to proceed to the 'extract' phase

** Report counts by severity
UVM_INFO :   32
UVM_WARNING :    0
UVM_ERROR :    0
UVM_FATAL :    0
** Report counts by id
[RNTST]     1
[TAV_1]     6
[TAV_2]     6
[TAV_3]     2
[TAV_4]     8
[TAV_5]     2
[TAV_6]     4
[TAV_7]     1
[TEST_DONE]     1
[UVM/RELNOTES]     1

Notice that the lost key in part 6 and the empty semaphore in part 7 left the summary at 0 errors. A semaphore never reports anything on its own; only your timeout does.

Common mistakes (and the fix for each)

1. A get() with no put() on some path. An early return, an error branch or a killed process skips the put(), and the next user waits forever. In part 6, killing the holder left the semaphore at 0 keys and the next user stuck. Fix: keep the code between get() and put() short, with one way out.

2. An extra put(). In part 5, one extra put(1) turned a mutex into a 2-key semaphore, with no warning. Fix: pair every put(n) with a get(n) of the same n.

3. Forgetting the count in new(). In part 7, get(1) on new() was still waiting when the 50 ns timeout fired. Fix: always write the count, even new(1).

4. Mixing key sizes on one semaphore. In part 4, a get(1) that arrived later was served before a waiting get(2). Fix: if every user takes one key, order is simple; mix sizes only when you’ve checked who waits behind whom.

5. Using a semaphore to pass data. It only carries permission. Fix: use a mailbox when a value has to move from one process to another.

Where AI helps, and where it doesn’t

An AI assistant is quick at the shape of the code: the fork, the get, the put, a timeout around it. It’s also good at spotting a path that leaves without returning the key.

What it can’t tell you is the order your simulator serves waiting processes in, or what a killed process does to the bucket. Part 4 and part 6 are there for that.

Practice challenge

Wrap get() and put() in a small class, tav_guard, whose run() task takes a key, calls a task you pass it, and always returns the key, even when a timeout fires. Then rerun part 6 with it.

FAQ

What is a semaphore in SystemVerilog? A built-in class, std::semaphore, that holds a bucket of keys. A process takes keys with get() before using a shared resource and returns them with put().

What is the difference between get() and try_get()? get() waits until enough keys are free. try_get() returns at once: 1 if it took the keys, 0 if it didn’t.

How do I make a mutex? Create the semaphore with one key, new(1), and put the shared code between get(1) and put(1).

What is the default key count? 0. A semaphore made with new() has no keys, and in the bench its first get(1) was still waiting after 50 ns.

Are waiting processes served in order? Only when every request is the same size. In the VCS run, a get(1) that arrived 1 ns later was served before a waiting get(2), because one key was enough for it and not for the get(2).

What is the difference between a semaphore and a mailbox? A semaphore carries only permission, a mailbox carries data. Both live in the std package.

References

  • IEEE 1800-2017, SystemVerilog standard: section 15.3 (semaphores), 15.4 (mailboxes), 9.6.3 (disable fork).
  • Chris Spear and Greg Tumbush, SystemVerilog for Verification, 3rd edition, chapter 7 (threads and interprocess communication).

Keep learning

A semaphore guards access; to move data between the same processes, use a mailbox in SystemVerilog. The processes themselves usually come from a fork, so the flavours of fork join is worth a read too, especially for join_any and disable fork.

There’s more in the SystemVerilog category and the interview questions.