Header Ads Widget

Producer / Consumer Problem or bounded – buffer problem

A cooperating process is one that can affect or be affected by other processes executing in the system. In the bounded–buffer problem, at most n -1 items in the buffer at the same time. Suppose that we wanted to modify the algorithm to remedy this deficiency. One possibility is to add an integer variable counter, initialized to 0. Counter is incremented every time we adda new item to the buffer, and is decremented every time we remove one item from the buffer.

The code for the producer process can be modified as follows:

Repeat

….

Produce an item in next p

….

While counter = n do no-op;

Buffer[in] = next p;

In = in + 1 mod n

Counter := counter + 1;

Until false;

The code for the consumer process can be modified as follows:

Repeat

While counter = 0 do no-op;

Next c = buffer[out];

Out:= out + 1 mod n;

Counter := counter – 1;

Consume the item in next c

Until false;


Both routines are correct separately. But they may not function correctly when executed concurrently. Suppose that the value of the variable counter is currently 5, and the producer and consumer processes execute the statements ‘counter :=counter + 1’ and counter :=counter – 1 concurrently and the value of the variable counter may be 4, 5, or 6! The correct result is 5. Because of concurrent manipulation, the incorrect state arrived.

A situation like this, where several processes access and manipulate the same data concurrently, and the outcome of the execution depends on the particular order in which the access takes place, is called a race condition.

To guard against the race condition above, we need to ensure that only one process at a time can be manipulating the variable counter.

To make such a guarantee, we require some form of synchronization of the process.

Post a Comment

0 Comments