簡體   English   中英

如何獲得boost SPSC Queue的大小?

[英]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 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的編碼模式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM