Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Semaphore simple sample [closed]

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.

like image 444
user1074896 Avatar asked Mar 26 '12 07:03

user1074896


People also ask

What is an example of a semaphore?

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.

What happens when the semaphore value is 0?

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.

What does it mean when semaphore 0?

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.


1 Answers

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

like image 77
CloudyMarble Avatar answered Oct 11 '22 04:10

CloudyMarble