Search code examples
javamultithreadingoperating-systemsemaphoreproducer-consumer

Producer Consumer bounded buffer using Semaphore


Below is my implementation for the PC problem

public class CircularQueue {
Queue <Integer>queue = new LinkedList<Integer>();
final int LIMIT = 10;
static Semaphore semProd = new Semaphore(1);
static Semaphore semConsu = new Semaphore(0);
public void enqueue(int productId) throws InterruptedException{

        semProd.acquire();
         queue.add(productId);
         System.out.println(Thread.currentThread().getName()+" Putting(In Q) Product ID:"+productId);
         semConsu.release();
}

public int deueue() throws InterruptedException{
        semConsu.acquire();
        int productID = (int) queue.remove();
        System.out.println(Thread.currentThread().getName()+" Getting (In Q) Product ID:"+productID);
        semProd.release();
    return productID;
}
}



//producer class
public class Producer implements Runnable{
CircularQueue cQueue ;
public Producer(CircularQueue queue){
    this.cQueue = queue;

}

public void run(){
    while(true){
    for(int i =0 ; i < 5 ;i++){

        try {
            cQueue.enqueue(i);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    }}}


//consumer class
public class Consumer implements Runnable{

CircularQueue cQueue ;
public Consumer(CircularQueue cQueue){
    this.cQueue = cQueue;

}
public void run(){

    try {
        while(true){
        int item = cQueue.deueue();
        Thread.sleep(2000);}
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}}


//Driver Class
public class DriverClass {

public static void main(String args[]){

    CircularQueue cQueue = new CircularQueue();
    new Thread(new Producer(cQueue)).start();
    new Thread(new Consumer(cQueue)).start();


}}

1) How do I check if my implementation is correct 2)if I want to edit solution for multiple consumer and multiple producer then how should I change implementation

is increasing number of semProduce and sem consume enough?

static Semaphore semProd = new Semaphore(4);//4 producer
static Semaphore semConsu = new Semaphore(3);//3 consumer

Solution

  • For a general-purpose, bounded, multi-producer/consumer blocking queue with semaphores, you need three of them. One to count the number of free spaces in the queue, (initialized to the LIMIT of the queue), one to count the number of items in the queue, (initialized to zero), and another to protect the queue from multiple access, (initialized to 1, to act as a mutex).

    Pseudocode:

    Producer: wait(free); wait(mutex); queue.push(newItem); send(mutex); send(items);

    Consumer: wait(items); wait(mutex); result=(queue.pop); send(mutex); send(free); return result;