0

I want to add a synchronised section of code after first acquire the semaphore and I am not allowed to synchronised the function. So I wrote the following codes. Unfortunately, from the output, my program was blocked. Why is that? And how should I change the code if I could only change the context inside the P() and V().

package operating_system;

import java.util.ArrayList ;

public class Semaphore {

   private int value ;
   private ArrayList <SemProc> queue ;

   public Semaphore(int i) {
      value = i ;
      queue = new ArrayList <SemProc> () ;
   }

   public synchronized void V() {  //release
       value++;
       if ( value >0 )
           return;
       else {//someone else is waiting
           if ( !queue.isEmpty() ){
           SemProc Runner = queue.get(0);
           queue.remove(0);
           Runner.addToReadyQueue(true);
           }
       }
   }

   public void P(SemProc t) { //acquire
       synchronized (this){
       value--;
       if ( value >= 0 ) 
           return;
       else { // no available resources
           t.removeFromReadyQueue();
           queue.add(t);
           try {
            wait();
        } catch (InterruptedException e) {e.printStackTrace();}
   }}}}
NUO
  • 247
  • 2
  • 3
  • 14
  • What `SemProc` class is? You show `wait()` call, but who calls `.notify()`? – Tsyvarev Oct 27 '15 at 11:10
  • I am sorry, but I **strongly** advise you to use `java.util.concurrent` classes instead of writing your own. I am all for writing code to learn, but I honestly don't know where to begin. The code is intended to control threaded access, but it's strongly coupled with the object it's trying to control. Moreover, `SemProc` has its state set by `Semaphore` which also needs to be done in a thread-safe way. For instance, we have no way of knowing how `addToReadyQueue()` internally publishes the value of `true` so that other threads may act on it. Tip: "JCIP" is a great book that explains it all. – Daniel Oct 27 '15 at 11:43

0 Answers0