Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Semaphore: try_get(): Checking for a Key Without Waiting

SystemVerilog Interprocess Communication

Runnable example from the SystemVerilog Semaphore tutorial (try_get(): Checking for a Key Without Waiting)

Open in IDE
testbench.sv
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
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.