What you practice
semaphore (3.4). Use semaphores so parallel threads acquire shared resources without collision. It is in Timing & Synchronization — Part 3 · Advanced SV & Mini-UVM of the SystemVerilog Masterclass. Timing, concurrency, constrained-random verification, assertions, and a pure-SV Mini-UVM environment.
The same IDE is the SystemVerilog simulator. Slang lints the file, Verilator runs it, and the waveform viewer sits next to the source.
What you will learn
You will learn how to use a SystemVerilog semaphore to enforce mutual exclusion when multiple threads access a shared resource.
Learning objectives
- Declare and initialize a semaphore.
- Use
get()to acquire exclusive access to a shared resource. - Use
put()to release the semaphore after completing the critical section. - Observe correct ordering of thread execution via simulation logs.
Theory
A semaphore is a synchronization primitive used to control access to a shared resource in concurrent programming. In SystemVerilog, semaphore is a built-in class with two primary methods:
| Method | Purpose |
|---|---|
sem.get(n) | Acquires n keys; blocks if fewer than n keys are available |
sem.put(n) | Releases n keys back to the semaphore |
A binary semaphore (initialized with new(1)) acts like a mutex: only one thread can hold the key at a time.
Practice
- Open this chapter in RtlStudio; the files appear in the Explore panel.
- Edit
student/tb/tb.svto replace eachsem.__TODO__(1)with the correct method call (getorput). - Run Simulation and check the Log panel for the expected
INFO:output. - Verify that shared_counter increments correctly (no skipped or duplicated values) due to mutual exclusion.
Summary
Students implemented mutual exclusion using a SystemVerilog semaphore in a multi-threaded testbench. They correctly paired get(1) before accessing the shared shared_counter and put(1) afterward. This pattern prevents race conditions and ensures deterministic behavior when multiple threads share resources—essential for verifying complex concurrent RTL designs.
Run it in the Verilog IDE
- Open the lesson in the IDE. The SystemVerilog for this topic is already in the editor.
- Lint with Slang before you simulate. It covers both Verilog and SystemVerilog in this IDE.
- Run Verilator and inspect the VCD. Interfaces, classes, and assertions count only if the simulator agrees.
- Run Yosys when the lesson is synthesizable RTL, and keep testbench-only constructs out of that module.
The lesson is done when the simulation matches semaphore. Change the source, run the Verilog simulator again, and read the waveform without leaving the IDE. Simulation guide · Yosys guide.