如何获得boost SPSC队列的大小
How to get size of boost SPSC Queue?
我们想知道在给定时间点队列中元素的数量。我们正在推送和弹出对象,我们想知道队列缓冲区中对象的数量。有什么内置的功能吗?或者用其他方式得到它?
http://www.boost.org/doc/libs/1_53_0/doc/html/boost/lockfree/spsc_queue.html您不能可靠地获得大小,因为它会引发竞争条件。出于同样的原因,您将找不到empty()
方法:当该方法返回值时,它将无关紧要,因为它可能已经更改。
有时无锁容器提供一个"unreliable_size()"方法(用于统计/日志记录)
这里的特殊情况是SPSC假设单一生产者和消费者:
-
size_type read_available() const;
可以从spsc_queue中弹出的可用元素数
-
size_type write_available() const;
获取写入空间
注意,只有在消费者/生产者线程中使用时,才有效。
看起来我们的操作仅限于pop()和push()函数。在您的软件设计中,您必须关注这些操作。例如,如果您是消费者,则限制您一次只能消费队列上的所有项目。你必须依靠另一种与生产者沟通的渠道(条件变量或原子变量)。
atomic<bool> producer_done(false); // producer set this variable to tell the consumer the status
spsc_queue<Obj> theQ; // assume producers have pushed
Obj tmpObj;
while (!producer.done) {
if (!theQ.pop(tmpObj)) {
cerr << "did not get any item from the producern";
// the producer may be too slow, your only choice is loop and wait, or other more complicated inter thread communication
// may be sleep a little
this_thread::sleep_for(1s);
}
else { // you got an item to work on
consume(tmpObj);
}
}
// now you know the single producer is no longer adding item to the queue
while (theQ.pop(tmpObj)) {
consume(tmpObj);
}
这实际上是可以在消费者部分与spsc_queue一起使用的编码模式。
相关文章:
- boost::进程间消息队列引发错误
- 如果我只是不访问queue_front节点的子节点,而是将它们推到队列中呢?还是BFS吗
- Android NDK传感器向事件队列报告奇怪的间隔
- C++优先级队列,按对象的唯一指针的特定方法升序排列
- 按对象的特定方法按升序排列的C++优先级队列
- 使用2个键的cpp-stl::优先级队列排序不正确
- 我是否需要在下一次转移时将所有权*转移回转移队列
- 在一个读写器队列中,我可以用volatile替换原子吗
- 为什么我的多线程作业队列崩溃
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 使用"Task"函数指针队列定义作业管理器
- 在c++队列中使用pop和visit实现线程安全
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 打印优先级队列
- ARM 上的无锁 SPSC 队列实现
- 哪个架构更好?多个 SPSC 队列或一个 MPSC 队列
- 在 Folly 的无锁 SPSC 队列中使用 std::memory_order_consume
- SPSC锁定免费队列,无原子
- Boost spsc队列段故障
- 如何获得boost SPSC队列的大小