A ring buffer (circular queue) joins head and tail: read/write cursors advance around a fixed slice instead of shifting elements on every dequeue.
The payoff: after a dequeue you do not slide the rest of the queue forward; the next enqueue overwrites the freed slot.
Below is a common pattern—separate read/write counters—with a diagram-friendly walkthrough. Code is adapted from chanx ringbuffer.
Counter-based implementation
Skim the code first; a picture afterward makes the flow obvious.
ringbuffer,是环形缓存区, 或叫环形队列。
不同于一般常见的队列,环形队列收尾相连,通过移动指针来控制队列中内容的读写。
这样做有什么好处呢?
最大的好处是环形队列出队(读取)后,不需要对后续队列内容进行搬移,可以后续由入队(写入)覆盖。
下面来看下一种常见的实现方式, 通过读写指针计数来实现环形队列
计数法实现
先过一遍代码,后边会有图解版说明,方便理解
代码参考自鸟窝无限缓存 channel-chanx
