FOR FREE YEAR SOLVED

What is the problem with a fatal Race Condition?

 

Problem with a fatal Race Condition

The problem of the above producer-consumer code is a race condition. It can occur because access to count is unconstrained. 

 

Let consider a certain moment 

 

When Buffer is empty i.e. count = 0 

 

Consumer: 1, 2, 3 preempted (before call sleep) | Producer: 1, 2, 3, 4, 5, 6, 7 | Consumer: 3 and sleep | Producer: 1, 2, 3, 4, 5, 6, 7….. 1, 2, 3, 4 and sleep

 

# The buffer is empty and the consumer has executes line 1, 2 and just see if the count is 0. At that instant, the scheduler preempted(stop) the process consumer before calling the sleep function. So, the consumer process is preempted (stop) before sleep it.

 

# Now process producer is in ready state and gets the CPU, execute all instructions 1,2,3,4,5,6 and 7. The producer inserts an item in the buffer; increments count and notice that it is now 1. In line 7 the as we know producer call wakeup() to wake consumer up because the producer assumed that the count was just 0, thus the customer must be sleeping. 

 

But unfortunately, the customer is not yet logically sleeping because the consumer was preempted by the scheduler before calling its sleep function. So, the wake-up signal is lost

 

# When the consumer next runs, it will test the value of the count it previously read, find it to be 0, and go to sleep

 

# Sooner or later the producer will fill up the buffer and also go to sleep.

 

Now both will sleep forever. This is called a race condition

 

The race condition of producer and consumer problem can be solved by semaphore variable.