Conceptually, a semaphore is a bucket. When a semaphore is allocated, a bucket that contains a fixed number of keys is created. Processes using semaphores must first procure a key from the bucket before they can continue to execute. If a specific process requires a key, only a fixed number of occurrences of that process can be in progress simultaneously. All others must wait until a sufficient number of keys is returned to the bucket. Semaphores are typically used for mutual exclusion, access control to shared resources, and basic synchronization.
Semaphore is a built-in class that provides the following methods:
-- Create a semaphore with a specified number of keys: new()
-- Obtain one or more keys from the bucket: get()
-- Return one or more keys into the bucket: put()
-- Try to obtain one or more keys without blocking: try_get()
EXAMPLE:semaphore program main ;
semaphore sema = new(1);
initialbegin repeat(3) begin fork ////////// PROCESS 1 ////////////////
begin $display("1: Waiting for key");
sema.get(1);
$display("1: Got the Key");
#(10);// Do some work
sema.put(1);
$display("1: Returning back key ");
#(10);
end ////////// PROCESS 2 ////////////////
begin $display("2: Waiting for Key");
sema.get(1);
$display("2: Got the Key");
#(10);//Do some work
sema.put(1);
$display("2: Returning back key ");
#(10);
end join end #1000;
end endprogram
RESULTS:
1: Waiting for key 1: Got the Key 2: Waiting for Key 1: Returning back key 2: Got the Key 2: Returning back key 1: Waiting for key 1: Got the Key 2: Waiting for Key 1: Returning back key 2: Got the Key 2: Returning back key 1: Waiting for key 1: Got the Key 2: Waiting for Key 1: Returning back key 2: Got the Key 2: Returning back key