【问题标题】:Circular queue that simply updates the indices简单更新索引的循环队列
【发布时间】:2015-10-10 11:23:25
【问题描述】:

我的生产者-消费者应用程序需要一个循环队列。就我而言,我有一个预先分配的对象数组(A 类):

A mylist[10]; 

查看 Boost 示例,似乎需要将项目“推入”和“弹出”到队列中/从队列中“弹出”。

但是,就我而言,我试图避免每次都创建一个新对象并将其推送到队列中,因为我可以简单地重用现有对象。

我的偏好是简单地更新当前生产者索引处的对象内容(并将索引更新到下一个位置)。同样,消费者使用当前消费者索引处的对象内容(并将索引更新到下一个位置)。本质上,它本身没有推送或弹出。

虽然我可以将自己的实现放在一起,但我想知道 STL 或 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 循环缓冲区示例。我不知道。它仍然需要你“push_back”一个值。
  • @Peter: true - 确实如此 - 但是(使用 C++11 和当前的 boost)如果你推回一个临时的或用 std::move() 包装的值,它会将它移动到缓冲区中,所以它不太可能特别昂贵。 (必须注意:通常最好让您的代码工作,然后查看它是否太慢;如果是这样,请使用分析器来确定要优化的内容。)
  • 我添加了一个伪示例来说明我的观点。内存分配会扼杀性能。非常感谢您的帮助。

标签: c++ boost


【解决方案1】:

您可能正在寻找Boost.CircularBuffer

这实际上是一个预先分配的元素块,为您处理所有循环逻辑。

一个示例,来自文档:

// 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++));
}

【讨论】:

  • 感谢您的帮助。我已经编辑了我的原始帖子,以包含我遇到的问题的示例。我在想 Boost.CircularBuffer 可能对我没有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 2023-02-17
  • 2013-04-29
  • 1970-01-01
  • 2018-05-19
相关资源
最近更新 更多