0
3.3kviews
Explain counting semaphore with examples.
1 Answer
1
136views

Counting Semaphore

The value of a counting semaphore can range over an unrestricted domain. Counting semaphores can be used to control access to a given resource consisting of a finite number of instances. The semaphore is initialized to the number of resources available. Each process that wishes to use a resource performs a wait() operation on the semaphore (thereby decrementing the count). When a process releases a resource, it performs a signal() operation (incrementing the count). When the count for the semaphore goes to 0, all resources are being used. After that, processes that wish to use a resource will block until the count becomes greater than 0.

Example

struct Semaphore {
  int value; // processes that can enter the critical section simultaneously.   
  queue type L; // L contains a set of processes that get blocked   

  down(Semaphore S) {
    SS.value = S.value - 1; //semaphore's value will get decreased when a new   
    //process enter in the critical section   
    if (S.value < 0) {
      put_process(PCB) in L; //if the value is negative then   
      //the process will get into the blocked state.  
      Sleep();
    } else
      return;
  }

  up(Semaphore s) {
    SS.value = S.value + 1; //semaphore value will get increased when   
    //it makes an exit from the critical section.   
    if (S.value <= 0) {
      select a process from L; //if the value of the semaphore is positive   
      //then wake one of the processes in the blocked queue.   
      wake - up();
    }
  }
}
Please log in to add an answer.