4

以下是硬拷贝本身的“操作系统概念”第 7 版 Galvin,Gagne 第 3 章的摘录:


以下变量驻留在生产者和消费者进程共享的内存区域中:

#define BUFFER_SIZE 10

typedef struct {
 . . .
} item;

item buffer[ BUFFER_SIZE ];
int in = 0;
int out = 0;

共享缓冲区实现为具有两个逻辑指针的循环数组:inout。变量in指向缓冲区中的下一个空闲位置;out指向缓冲区中的第一个完整位置。当in==out;缓冲区已满时,缓冲区为空((in+1)%BUFFER_SIZE)==out

该方案最多允许同时BUFFER_SIZE-1在缓冲区中的最多项目。


我用粗体突出了我的困惑。这是该章在线幻灯片的链接(但它已经编辑了本书的几行)。转到“使用共享内存的生产者-消费者示例”部分

http://www.cs.uic.edu/~jbell/CourseNotes/OperatingSystems/3_Processes.html

BUFFER_SIZE-1为什么缓冲区中可以有项目?如果我们从buffer[0]to开始buffer[BUFFERSIZE-1],它不等于BUFFER_SIZE项目数吗?作者的意思是说缓冲区的索引不能超过BUFFER_SIZE-1吗?但是后来,他明明写了同时不能超过的BUFFER_SIZE-1数。请解释整个事情。

4

1 回答 1

16

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.

于 2013-04-21T07:19:54.787 回答