I am solving a specific kind of producer-consumer which goes as follows -
There is a buffer of size n
. Consumers take items from buffer, one item at a time (By this I mean, whenever a consumer thread has access to buffer, it won't take more than one item). Whenever the buffer is empty, a call to producer must be raised. The producer completely fills in this buffer and then blocks itself until a call is made again. I have modelled each producer and consumer as a thread and implemented it this way -
bool buffer[n];
//Producer
while(true){
lock(bufferLock);
wait(producerSemaphore,bufferLock);
completelyFillbuffer();
signalAll(consumerSemaphore);
unlock(bufferLock);
}
//Consumer
while(true){
lock(bufferLock);
if(buffer.isEmpty()){
signal(producerSemaphore);
wait(consumerSemaphore,bufferLock);
}
takeSliceFrombuffer();
unlock(bufferLock);
}
takeItemFrombuffer(){
take any true item and make it false;
}
completelyFillbuffer(){
make all items true;
}
The problem is that, I am using a single lock for complete buffer. So at any point, only a single consumer can take an item. But when the buffer is of large size, it makes sense to allow more consumers to take items simultaneously. How do I implement this?