Uncoordinated Producer/Consumer Problem:
Read the following program supporting multiple producers and consumers sharing a single item buffer.
Then answer the later questions.
Shared variables
semaphore mutex = 1;
int[SIZE] itemBuffer = createZeroFilledArray(SIZE);
int[SIZE] freeBufferIndices = createZeroFilledArray(SIZE);
Producer Logic: Consumer Logic:
while (true) { boolean indexDecided = false;
int putIndex = genRandomInt() % SIZE; int getIndex = 0;
wait(mutex); while (true) {
if (freeBufferIndices[putIndex] != 0) { if (indexDecided == false) {
signal(mutex); getIndex = genRandomInt() % SIZE;
continue; indexDecided = true;
} }
freeBufferIndices[putIndex] = 1; wait(mutex);
signal(mutex) if (freeBufferIndices[getIndex] == 0) {
item p = produceNextItem(); signal(mutex);
wait(mutex) indexDecided = false;
itemBuffer[putIndex] = p; continue;
freeBufferIndices[putIndex] = 2; } else if (freeBufferIndices[getIndex] == 1) {
signal(mutex)
signal(mutex);
}
continue;
}
freeBufferIndices[getIndex] = 0;
item p = itemBuffer[getIndex];
signal(mutex);
consumeItem(p);
}
1. Can multiple producers produce items in parallel?
2. Can multiple producers store the items they produced in the buffer in parallel?
3. If there any possibility of producer starvation in the above logic?
4. If a consumer decides to eat from a specific buffer index, does it must eat from that index? Or, is
it more flexible? Explain its behavior.
5. Explain in general English, when does a consumer wait for a specific producer?
6. There is a subtle error in the consumer code. Where is it? How will you fix the problem?