C中的循环缓冲区实现

标签 c data-structures circular-buffer

我找到了关于如何实现循环缓冲区的伪代码。

// Producer.
while (true) {
  /* produce item v */
  while ((in+1)%n == out)
    /* Wait. */;
  b[in] = v;
  in = (in + 1) % n
}

// Consumer.
while (true) {
  while (in == out)
    /* Wait. */;
  w = b[out];
  out = (out + 1) % n;
  /* Consume item w. */
}

我不明白的是“Consume item w”。评论,因为我认为 w = b[out]; 我们正在消耗 w,不是吗?

最佳答案

w = b[out];

您只需获取要消耗的元素的副本。与

out = (out + 1) % n;

您推进要消费的项目的索引,从而防止再次引用它。

在某种程度上,多次调用 w = b[out]; 实际上并不消耗缓冲区的槽,它只是访问它;而 out = (out + 1) % n; 阻止进一步访问该项目。防止进一步访问缓冲项是我能想到的对术语“消耗项”的最强定义。

关于C中的循环缓冲区实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7477810/

相关文章:

inheritance - golang 继承来实现像集合/模型这样的主干

c - 瓦尔格林德 : Invalid free() on String Array in C

c - 下载头文件

algorithm - 总和大于给定值的子数组个数

c - C 中自动 stdout 缓冲区刷新的规则是什么?

java - 为什么迭代映射比迭代列表慢?

java - 哪个更好?使用相应类数组的原始类型数组

java - 向后滚动圆形数组

c - 单链表c

c - 杂项驱动程序和字符驱动程序有什么区别?