FOR FREE YEAR SOLVED

Producer and Consumer problem or Bounded-Buffer problem with a fatal Race Condition

 

How to solve busy waiting problems by sleep and wakeup call, let us consider the producer and consumer problem. Here two processes share a common and fixed-size buffer.

 

One of them, the producer, puts information into the buffer, and the other one, the consumer, takes it out.

This algorithm can allow n producers and m consumers, but for simplicity, we will consider only one producer and one consumer.

 

 

In the above producer and consumer problem, busy waiting will remove because when the producer wants to put a new item in the buffer, but it is already full, it goes to sleep. And it awakened further when the consumer has removed one or more items. 

 

In the same way, if the consumer wants to remove an item from the buffer, but the buffer is empty, it goes to sleep until the producer puts something in the buffer and wakes it up.  This approach solves the busy waiting problem i.e. CPU time is never wastage here. 

 

Description of the above algorithms

Here count and N (buffer) is a global variable. 

 

Producer’s code:

Line 3: Produce a new item and store it in a variable name item.

 

Here the total number of the capacity of the producer is defined by N (= 100) and there is another variable count which is used to track that how many item producer inserted till now.

 

Line 4: Using count variable checks the capacity of the producer is full or not. This producer’s code will first test to see if the count is N. If it is, the producer will go to sleep.

 

At line 4 if counts == N is not satisfied then

 

Line 5: The producer will add an item and

 

Line 6: Increment buffer using count (count = count + 1).

 

Line 7: After increment buffer (count = count + 1), it checks if count is 1(count == 1) or not. If it is, then the producer wakes up the consumer because the producer thinks that previously it was count = 0 and the consumer was in a sleep state. 

For this reason, producer tries to wake up consumer every time when the count is immediately 1 (count == 1).

 

Consumer’s code:

Line 3: It checks the count variable to see there is anything to be consumed or not. So, the first test counts the variable to see if it is 0 or not. If it is then go to sleep.

 

At line 3 if counts ==0 is not satisfied then

 

Line 4: Remove an item from the buffer and 

 

Line 5: Increment buffer using count (count = count - 1).

 

Line 6: After decrement buffer (count=count-1), it checks if count is N - 1 (count == N - 1) or not. If it is, then the consumer wakes up the producer because the consumer thinks that previously it was count=N and the producer was full and went to sleep state. For this reason, consumer try to wake up producer the every time when the count is immediately N - 1 (count == N - 1).

 

Line 7: Print the item which was removed.