如何获取boost SPSC队列的大小?

3
2个回答

3
您无法可靠地获取大小,因为它会邀请竞态条件。出于同样的原因,您将找不到empty()方法:当该方法返回值时,它将变得无关紧要,因为它可能已经改变。
有时,无锁容器提供“unreliable_size()”方法(用于统计/日志记录)。
这里的特殊情况是SPSC假设单个生产者和消费者:
  • size_type read_available() const;

    可以从spsc_queue中弹出的可用元素数量

  • size_type write_available() const;

    获取写入元素的写入空间

请注意,这些仅在分别使用消费者/生产者线程时才有效。

0

看起来我们的操作仅限于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 producer\n";
      // 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 编码模式。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接