最近接触了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,还是要加锁才能保证,而且效率,跟正常有锁队列并不一定有提高
多线程读写的时候,还是用有锁队列比较好,这种无锁队列还是适合单线程读,单线程写的情况