# Simultaneous buffer access in the bounded buffer problem

Galvin and various other resources only allow either the producer or the consumer to access the buffer at a time, the common code is as follows:

//Producer code

While(true)
{ down(empty);
down(mutex);
buffer[in] = item;
in = (in+1) % buffer_size;
up(mutex);
up(full);
}

//Consumer code

While(true)
{ down(full);
down(mutex);
item = buffer[out];
out = (out+1) % buffer_size;
up(mutex);
up(empty);
}


Here empty and full are semaphores which count the number of empty and full buffers. Mutex is initialised to 1, empty to buffer_size, full to 0.

I understand that multiple producers or consumers accessing the buffer at a time results in a race condition, but in my opinion a producer and a consumer can simultaneously access the buffer at a time without any problem. The solution given below seems to be fitting the constraints more precisely, so my question is, is there any problem(bounded wait not being satisfied, race condition, etc) in letting the producer and consumer access the buffer simultaneously like so?

While(true)
{ down(empty);
down(producer_mutex);
buffer[in] = item;
in = (in+1) % buffer_size;
up(producer_mutex);
up(full);
}

While(true)
{ down(full);
down(consumer_mutex);
item = buffer[out];
out = (out+1) % buffer_size;
up(consumer_mutex);
up(empty);
}

• Let say, the producer added an element into the buffer, and just after that i.e just before this statement  in = (in + 1)%buffer_size it got preempted. Now according to your code, you are going to allow consumers but it might create inconsistency. – Sai Sreenivas Dec 4 '20 at 16:26
• I think you're talking about the specific case where in and out point at the same slot? Because that's the only case which would result in inconsistency. In this case, semaphore full would be zero, so consumer can't access the buffer alongside the producer, it can if in and out point to different slots. – Yueor Dec 5 '20 at 17:13
• Also even if the producer and consumer could access the same slot at the same time, I don't see how it would cause inconsistency. According to your example, producer produces an item, preempts, consumer consumes that item, then either producer or consumer could continue, in the end, out and in will be incremented by one, without any inconsistency. – Yueor Dec 5 '20 at 17:23