环形缓冲区是一种固定大小的FIFO数据结构,使用数组和读写索引实现高效存取,通过取模运算形成环形循环,配合full标志区分空满状态,适用于生产者-消费者等场景。

环形缓冲区(Ring Buffer),也叫循环队列,是一种固定大小的先进先出(FIFO)数据结构,常用于生产者-消费者场景、网络数据缓存等。C++ 中实现环形缓冲区可以使用数组和两个指针(或索引)来管理读写位置。
环形缓冲区底层通常用一个固定大小的数组实现,配合两个索引:
当索引到达数组末尾时,通过取模运算回到开头,形成“环形”效果。
下面是一个线程不安全但高效的基础环形缓冲区模板实现:
立即学习“C++免费学习笔记(深入)”;
template <typename T, size_t Capacity>
class RingBuffer {
private:
T buffer[Capacity];
size_t read_index = 0;
size_t write_index = 0;
bool full = false;
<p>public:
bool push(const T& item) {
if (full) return false;
buffer[write_index] = item;
write_index = (write_index + 1) % Capacity;
// 写入后如果写索引追上读索引,表示满了
full = (write_index == read_index);
return true;
}</p><pre class='brush:php;toolbar:false;'>bool pop(T& item) {
if (empty()) return false;
item = buffer[read_index];
read_index = (read_index + 1) % Capacity;
full = false; // 只要读了,就一定不满
return true;
}
bool empty() const {
return (!full && (read_index == write_index));
}
bool is_full() const {
return full;
}
size_t size() const {
if (full) return Capacity;
if (write_index >= read_index)
return write_index - read_index;
else
return Capacity - (read_index - write_index);
}};
你可以这样使用上面的 RingBuffer:
#include <iostream>
<p>int main() {
RingBuffer<int, 4> rb;</p><pre class='brush:php;toolbar:false;'>rb.push(1);
rb.push(2);
rb.push(3);
int val;
while (rb.pop(val)) {
std::cout << val << " ";
}
// 输出: 1 2 3
return 0;}
几个需要注意的地方:
write_index = (write_index + 1) & (Capacity - 1);
基本上就这些。这个实现简洁高效,适合嵌入式、音视频处理等对性能敏感的场景。根据需求可扩展为动态容量、支持移动语义、添加 front()/back() 接口等。
以上就是C++如何实现一个环形缓冲区(ring buffer)_C++ 环形缓冲区实现方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号