1. 阻塞队列的使用
- 将工程中的concurrentqueue.h和blockingconcurrentqueue.h放在include文件夹里就可以调用了
#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.
- 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.pngimage.png
image.png
3. 小结
When producing or consuming many elements, the most efficient way is to:
- Use the bulk methods of the queue with tokens
- Failing that, use the bulk methods without tokens
- Failing that, use the single-item methods with tokens
- Failing that, use the single-item methods without tokens
- bulk的操作是一批一批的,可以批量入队,批量出队,消耗较少
- try_enqueue()当队列满时,并不会执行入队操作,返回false,而enqueue()入队,会分配空间扩容。
- 队列有个最小长度,是concurrentqueue.h的BLOCK_SIZE 默认为32
网友评论