Here is an excerpt from the book "Operating System Concepts" 7th Edition Galvin,Gagne Chapter 3 from the hard-copy itself :
The following variables reside in a region of memory shared by the producer and consumer processes:
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
item buffer[ BUFFER_SIZE ];
int in = 0;
int out = 0;
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)%BUFFER_SIZE)==out
.
This scheme allows at most BUFFER_SIZE-1
items in the buffer at the same time.
I have highlighted my confusion in bold.Here's a link to an online slide of that chapter (but it has edited a few lines of the book).Go to the section "Producer-Consumer Example Using Shared Memory"
http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/3_Processes.html
Why can there be BUFFER_SIZE-1
items in the buffer? If we start from buffer[0]
to buffer[BUFFERSIZE-1]
, doesn't it equal BUFFER_SIZE
number of items? Does the author mean to say that the index of the buffer can't exceed BUFFER_SIZE-1
?But then, he has clearly written the number of items can't exceed BUFFER_SIZE-1
at the same time. Please explain the whole thing.
When you have ring buffer, you typically have 2 pointers or offsets, which signify start
and end
of the data in the buffer. Typical convention to tell if buffer is empty when start
== end
.
This convention leads to BUFFER_SIZE - 1
limitation on total numbers of items in ring buffer. If we were to allow to fill it to BUFFER_SIZE
, this would mean that start
== end
, and thus would be impossible to tell if buffer is completely empty or completely full.
If you create one more variable that keeps number of items in the buffer, this would be possible to tell apart and allow to fill buffer to the max. But it is easier to not do that and simply reduce max number of items by 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With