A semaphore is used to control access to a shared resource when a process is being executed. This is done with the help of a counter. When this counter value is greater than 0, access to share resource is provided. On the other hand, if the value of counter is zero, then access to shared resources is denied. The counter basically keeps a count of the number of permissions it has given to the shared resource. This means, a semaphore provides access to a shared resource for a thread.
Following is an example −
public class Demo { private boolean my_signal = false; public synchronized void accept() { this.my_signal = true; this.notify(); } public synchronized void give_it() throws InterruptedException { while(!this.my_signal) wait(); this.my_signal = false; } }
The ‘accept’ method is used to send a signal that is stored inside a semaphore. The ‘give_it’ function waits for a signal. When this function receives a signal, its flag is cleared, and the control exits from this function. Using a semaphore in this manner, none of the signals would be missed.