moodycamel::ConcurrentQueue 清空队列的方法论

方法1:循环弹出元素

cpp 复制代码
#include <concurrentqueue.h>

// 如果存储的是指针类型
moodycamel::ConcurrentQueue<int*> queue;
int* item = nullptr;
while (queue.try_dequeue(item)) {
    if (item) {
        delete item;  // 如果需要释放内存
        item = nullptr;
    }
}

// 如果存储的是普通类型
moodycamel::ConcurrentQueue<int> queue;
int item;
while (queue.try_dequeue(item)) {
    // 元素自动销毁
}

方法2:批量弹出

cpp 复制代码
#include <concurrentqueue.h>
#include <vector>

moodycamel::ConcurrentQueue<int> queue;

// 批量弹出,效率更高
std::vector<int> temp;
queue.try_dequeue_bulk(std::back_inserter(temp), 
                      queue.size_approx());

// temp现在包含所有弹出的元素,随后会被自动销毁
temp.clear();  // 立即释放内存

方法3:使用交换技巧、或 std::move(...)

cpp 复制代码
// 最简单的方法:创建新队列替换旧队列
moodycamel::ConcurrentQueue<int> newQueue;
std::swap(queue, newQueue);
// 原队列的所有权转移到了newQueue,出作用域时自动销毁

方法4:自定义清空函数(模板)

cpp 复制代码
template<typename T>
void ClearConcurrentQueue(moodycamel::ConcurrentQueue<T>& queue) {
    T item;
    while (queue.try_dequeue(item)) {
        // 元素自动处理
    }
}

// 对于指针类型的特化版本
template<typename T>
void ClearConcurrentQueue(moodycamel::ConcurrentQueue<T*>& queue) {
    T* item = nullptr;
    while (queue.try_dequeue(item)) {
        delete item;
        item = nullptr;
    }
}

线程安全

并发队列,在清空过程中可能有其他线程继续插入元素。如果需要完全清空:

  1. 暂停生产者:确保没有线程在插入
  2. 使用原子标志:协调清空操作
  3. 多次清空:循环清空直到确认队列为空
cpp 复制代码
// 确保队列完全清空的稳健方法
void EnsureQueueEmpty(moodycamel::ConcurrentQueue<int>& queue) {
    int item;
    int emptyCount = 0;
    const int MAX_EMPTY_CHECKS = 3;
    
    while (emptyCount < MAX_EMPTY_CHECKS) {
        if (queue.try_dequeue(item)) {
            emptyCount = 0;  // 重置计数器
        } else {
            emptyCount++;
            std::this_thread::yield();  // 让出CPU
        }
    }
}
相关推荐
端平入洛1 天前
auto有时不auto
c++
郑州光合科技余经理2 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1232 天前
matlab画图工具
开发语言·matlab
dustcell.2 天前
haproxy七层代理
java·开发语言·前端
norlan_jame2 天前
C-PHY与D-PHY差异
c语言·开发语言
哇哈哈20212 天前
信号量和信号
linux·c++
多恩Stone2 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054962 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月2 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
蜡笔小马2 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost