我的生产者-消费者应用程序需要一个循环队列。在我的例子中,我有一个预先分配的对象数组(A 类):
A mylist[10];
查看 Boost 示例,似乎需要将项目“插入”和“弹出”队列。
但是,在我的例子中,我试图避免每次都创建一个新对象并将其插入队列,因为我可以简单地重用现有对象。
我的偏好是简单地更新当前生产者索引处的对象内容(并将索引更新到下一个位置)。同样,消费者使用当前消费者索引处的对象内容(并将索引更新到下一个位置)。本质上,本身没有推送或弹出。
虽然我可以组合自己的实现,但我想知道 STL 或 Boost 中是否已经有我可以使用的东西。
编辑:每次将 Boost 插入队列时,Boost 都要求我创建一个新值。就我而言,我需要每秒添加 100 多个项目。内存分配会终止我的应用程序。下面是 boost 伪代码来说明我的问题:
class A {
public:
int x;
};
boost::circular_buffer<A*> list(10);
for(int i=0;i<10;i++) {
A* p = new A();
p->x = i;
list.push_back(p);
}
int val = 100;
while(true) {
// Set new values at the head of the queue
A* p = new A();
p->x = val; val++;
list.push_back(p);
}
如您所见,我只想重用队列中的对象,而不是创建新对象。
最佳答案
您可能正在寻找 Boost.CircularBuffer .
这实际上是一个预先分配的元素 block ,所有循环逻辑都为您处理。
文档中的示例:
// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(3);
// Insert threee elements into the buffer.
cb.push_back(1);
cb.push_back(2);
cb.push_back(3);
int a = cb[0]; // a == 1
int b = cb[1]; // b == 2
int c = cb[2]; // c == 3
// The buffer is full now, so pushing subsequent
// elements will overwrite the front-most elements.
cb.push_back(4); // Overwrite 1 with 4.
cb.push_back(5); // Overwrite 2 with 5.
// The buffer now contains 3, 4 and 5.
a = cb[0]; // a == 3
b = cb[1]; // b == 4
c = cb[2]; // c == 5
// Elements can be popped from either the front or the back.
cb.pop_back(); // 5 is removed.
cb.pop_front(); // 3 is removed.
// Leaving only one element with value = 4.
int d = cb[0]; // d == 4
对于类似 FIFO 队列的应用程序,请参阅 Bounded Circular Buffer Example .
对于您的示例,您可以依赖 C++11 中可用的移动语义来避免动态内存分配:
class A {
public:
int x;
A (int a) : x(a) {}
};
boost::circular_buffer<A> list(10);
for(int i=0;i<10;i++) {
list.push_back(A (i));
}
int val = 100;
while(true) {
// Set new values at the head of the queue
list.push_back(A (val++));
}
关于c++ - 简单更新索引的循环队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31531725/