Write the code segments to create a monitor that has the sam

Write the code segments to create a monitor that has the same behavior as a semaphore.

Monitor semaphore {

//initialization

// synchronization condition variable

// methods

   wait ( )

   signal ( )

}

Solution

I assume the code is to be written in Java as no language is specified. The solution is below:

public class Monitor_Semaphore {
  
   private int count;
  
   //initialize
   public Semaphore (int init)
   {
       count = init;
   }
  
   //signal
   synchronized public void S() {
       count++;
       notify();
   }
  
   //wait
   synchronized public void W()
       throws InterruptedException {
           while (count == 0) wait();
               count--;
   }
  
   public void Method1(){
      
       W();
  
       //critical section
      
       S();
   }
}

Write the code segments to create a monitor that has the same behavior as a semaphore. Monitor semaphore { //initialization // synchronization condition variabl

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site