concurrentqueue无锁队列多线程无序问题

本文探讨了MoodyCamel ConcurrentQueue在多线程环境下的使用,发现不加token时生产者加锁仍可能导致无序,而加入ProducerToken和ConsumerToken后能确保消费者顺序,但效率提升有限,适用于单线程读写场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近接触了concurrentqueue的多线程无锁队列,测试了一下,发现单线程生产者和单线程消费者可以正常使用,多线程生产者的时候,即使加锁了,单线程取出来的时候好像还是无序的

#include <iostream>
#include "concurrentqueue.h"
#include <functional>
#include <thread>
#include <mutex>

using moodycamel::ConcurrentQueue;

ConcurrentQueue<int> m_cqueue;
std::mutex m_mutex;

static int i = 0;
static void Produce(int arg)
{
        while(1)
        {
                m_mutex.lock();
                i++;
                m_cqueue.enqueue(i);
                m_mutex.unlock();
        }
}

static void Customer(int arg)
{
        while(1)
        {
                int value;
                static int lastvalue;
                m_cqueue.try_dequeue(value);
                if(value < lastvalue)
                        printf("getqueue notseq :%d ,last:%d \n", value, lastvalue);
                lastvalue = value;

        }
}

int main()
{
        std::thread thread1(Produce, 1);
        std::thread thread3(Produce, 1);
        std::thread thread2(Customer, 2);

        thread1.join();
        thread2.join();
        thread3.join();

        return 0;
}

不过concurrentqueue有个token功能,加了token后,可以保证消费者顺序

#include <thread>
#include <mutex>

using moodycamel::ConcurrentQueue;

ConcurrentQueue<int> m_cqueue;
std::mutex m_mutex;

moodycamel::ProducerToken prod_token(m_cqueue);
moodycamel::ConsumerToken cus_token(m_cqueue);

static int i = 0;
static void Produce(int arg)
{
        while(1)
        {
                m_mutex.lock();
                i++;
                m_cqueue.enqueue(prod_token, i);
                m_mutex.unlock();
        }
}

static void Customer(int arg)
{
        while(1)
        {
                int value;
                static int lastvalue;
                m_cqueue.try_dequeue(cus_token, value);
                if(value < lastvalue)
                        printf("getqueue notseq :%d ,last:%d \n", value, lastvalue);
                lastvalue = value;

        }
}

int main()
{
        std::thread thread1(Produce, 1);
        std::thread thread3(Produce, 1);
        std::thread thread2(Customer, 2);

        thread1.join();
        thread2.join();
        thread3.join();

        return 0;
}

感觉之前的测试理解有误,上面虽然加了token,还是要加锁才能保证,而且效率,跟正常有锁队列并不一定有提高

多线程读写的时候,还是用有锁队列比较好,这种无锁队列还是适合单线程读,单线程写的情况

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值