Can anyone share simple sample of using Semaphore? If it's possible a sample of solving a task without semaphore and then with semaphore to understand main idea of it.
An oxygen thread will wait for two hydrogen to come ready and then signal the oxygen count twice to let them know oxygen is ready. This is an example of a "rendezvous"—we are signaling a general semaphore to record the action of one thread and another thread can wait on it to meet up with it.
If the semaphore's value is 0 prior to decrementing, then the sem_wait() operation will block the current thread. If a thread calls sem_post() and there is at least one thread waiting on the semaphore, then one of the threads becomes unblocked.
If the semaphore is initialized with 0, then the first completed operation must be V. Both P and V operations can be blocked, if they are attempted in a consecutive manner. If the initial value is 0, the first completed operation must be V; if the initial value is 1, the first completed operation must be P.
Here is a simple Semaphore implementation:
public class Semaphore {
private boolean signal = false;
public synchronized void take() {
this.signal = true;
this.notify();
}
public synchronized void release() throws InterruptedException{
while(!this.signal) wait();
this.signal = false;
}
}
The take()
method sends a signal which is stored internally in the Semaphore. The release()
method waits for a signal. When received the signal flag is cleared again, and the release()
method exited.
Read this article and take a look at this example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With