Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace synchronized, wait, notify by semaphores? (Producer-Consumer)

Good evening,

I am wondering how I can replace synchronized, wait and notify in the following code by semaphores? And where do I have to create the semaphore variable?

   import java.util.*;

   class Producer
   extends Thread
   {
     private Vector v;

     public Producer(Vector v)
     {
       this.v = v;
     }

     public void run()
     {
       String s;

       while (true) {
         synchronized (v) {
           s = "Value"+Math.random();
           v.addElement(s);
           System.out.println("Producer created "+s);
           v.notify();
         }
         try {
           Thread.sleep((int)(100*Math.random()));
         } catch (InterruptedException e) {
           //nothing
         }
       }
     }
   }

   class Consumer
   extends Thread
   {
      private Vector v;

      public Consumer(Vector v)
      {
         this.v = v;
      }

      public void run()
      {
         while (true) {
            synchronized (v) {
               if (v.size() < 1) {
                  try {
                     v.wait();
                  } catch (InterruptedException e) {
                     //nothing
                  }
               }
               System.out.print(
                 " Consumer found "+(String)v.elementAt(0)
               );
               v.removeElementAt(0);
               System.out.println(" (remaning: "+v.size()+")");
            }
            try {
               Thread.sleep((int)(100*Math.random()));
            } catch (InterruptedException e) {
               //nothing
            }
         }
      }
   }

I'd be glad if someone could help me out!

Thank you in advance..

like image 354
David Avatar asked Sep 29 '22 07:09

David


1 Answers

Think of a semaphore as a lock that can allow multiple threads to access a shared resource. Whatever number you initialize the semaphore to will allow that many threads to access the resource simultaneously. In Producer-Consumer, the resource is a shared buffer between the two threads. You want to make sure that the consumer cannot access the buffer unless it is full, and the producer cannot access the buffer unless it is empty. You should start with a count of 0 in the consumer's semaphore and 1 in the producer's semaphore.That way the Producer has to make the first move. When the Producer begins to write to the buffer, you want to down the Producer semaphore. When the Producer is done, you want to up the Consumer's semaphore which will allow the Consumer to access the resource. When the consumer has accessed the resource, it then ups the producer's semaphore notifying the producer that the buffer is now empty.

Use this as a starting point: http://cs.gmu.edu/cne/modules/ipc/aqua/producer.html

like image 167
nLee Avatar answered Oct 03 '22 02:10

nLee