美文网首页
BlockingQueue阻塞队列的使用

BlockingQueue阻塞队列的使用

作者: 暮阳晨鼓 | 来源:发表于2019-03-08 15:29 被阅读0次

1. 阻塞队列的使用

#include "blockingconcurrentqueue.h"
typedef moodycamel::BlockingConcurrentQueue<int> MyQueue;
MyQueue myQueue(2)

//Allocates more memory if necessary
myQueue.enqueue(item) : bool
myQueue.enqueue(prod_token, item) : bool
enqueue_bulk(prod_token, item_first, count) : bool
// Fails if not enough memory to enqueue
try_enqueue(item) : bool
try_enqueue(prod_token, item) : bool
try_enqueue(item_first, count) : bool
try_enqueue_bulk(prod_token, iterm_first, count) : bool
// Attempts to dequeue from the queue (never allocates)
try_dequeue(item&) : bool
try_dequeue(cons_token, item&) : bool
try_dequeue_bulk(item_first, max) : size_t
try_dequeue_bulk(cons_token, item_first, max) : size_t
//if you happen to know which producer you want to dequeue from
try_dequeue_from_producer(prod_token, item&) : bool
try_dequeue_bulk_from_producer(prod_token, item_first, max) : size_t
//A not-necessarily-accurate count of the total number of elements
size_approx() : size_t
// blockconcurrentqueue version
wait_dequeue(T&& item)
wait_dequeue_timed(T&& item, std::int64_t timeout_usecs)//这两个函数功能类似,都是进行出队操作,如果队列为空,则等待。唯一的区别是,前者永久等待,而后者可以指定等待的时间,而后者可以指定等待时间,如果超时,则会停止等待并返回false.
    1. bulk operations
moodycamel::ConcurrentQueue<int> q;
int items[] = {1,2,3,4,5};
q.enqueue_bulk(items, 5);
int results[5];
size_t count = q.try_dequeue_bulk(results, 5);
for (size_t i=0; i != count; i++){
assert(results[i] == items[i];
}

2. 使用效果

image.png
image.png
image.png

3. 小结

When producing or consuming many elements, the most efficient way is to:

  1. Use the bulk methods of the queue with tokens
  2. Failing that, use the bulk methods without tokens
  3. Failing that, use the single-item methods with tokens
  4. Failing that, use the single-item methods without tokens
  5. bulk的操作是一批一批的,可以批量入队,批量出队,消耗较少
  6. try_enqueue()当队列满时,并不会执行入队操作,返回false,而enqueue()入队,会分配空间扩容。
  7. 队列有个最小长度,是concurrentqueue.h的BLOCK_SIZE 默认为32

相关文章

网友评论

      本文标题:BlockingQueue阻塞队列的使用

      本文链接:https://www.haomeiwen.com/subject/ufrxpqtx.html