# Producer Consumer Problem:-

The paradigm for cooperating processes, producer process produces information that is consumed by a consumer process.

To allow producer and consumer processes to run concurrently, we must have available a buffer of items that can be filled by the producer and emptied by the consumer. A producer can produce one item while the consumer is consuming another item. The producer and consumer must be synchronized so that the consumer does not try to consume an item that has not yet been produced. In this situation, the consumer must wait until an item is produced.

✦ unbounded-buffer places no practical limit on the size of the buffer.

✦ bounded-buffer assumes that there is a fixed buffer size.

### Bounded-Buffer – Shared-Memory Solution

The consumer and producer processes share the following variables.

Shared data

#define BUFFER_SIZE 10

Typedef struct

{

. . .

} item;

item buffer[BUFFER_SIZE];

int in = 0;

int out = 0;

Solution is correct, but can only use BUFFER_SIZE-1 elements.

The shared buffer is implemented as a circular array with two logical pointers: in and out. The variable in points to the next free position in the buffer; out points to the first full position in the buffer. The buffer is empty when in == out ; the buffer is full when ((in + 1) % BUFFERSIZE) == out.

The code for the producer and consumer processes follows. The production process has a local variable next produced in which the new item to be produced is stored:

Bounded-Buffer – Producer Process

item nextProduced;

while (1)

{

while (((in + 1) % BUFFER_SIZE) == out)

; /* do nothing */

buffer[in] = nextProduced;

in = (in + 1) % BUFFER_SIZE;

}

Bounded-Buffer – Consumer Process

item nextConsumed;

while (1)

{

while (in == out)

; /* do nothing */

nextConsumed = buffer[out];

out = (out + 1) % BUFFER_SIZE;

}