Imagine a parking lot with 3 spaces. The semaphore is the parking attendant who gives out 3 keys. When all keys are taken, new cars must wait until someone returns a key.
semaphore sem;
initial begin
sem = new(3); // Create semaphore with 3 keys
fork
use_resource("Process A");
use_resource("Process B");
use_resource("Process C");
use_resource("Process D"); // Must wait!
join
end
task use_resource(string name);
sem.get(1); // Get 1 key (blocks if none available)
$display("[%0t] %s got key, using resource", $time, name);
#10; // Use resource for 10 time units
$display("[%0t] %s returning key", $time, name);
sem.put(1); // Return 1 key
endtask