如何获得boost SPSC队列的大小

How to get size of boost SPSC Queue?

本文关键字:队列 SPSC 何获得 boost      更新时间:2023-10-16

我们想知道在给定时间点队列中元素的数量。我们正在推送和弹出对象,我们想知道队列缓冲区中对象的数量。有什么内置的功能吗?或者用其他方式得到它?

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一起使用的编码模式。