Boost, C++11,生产者消费者以及Qt生产者消费者例子

本文介绍了使用C++, Qt, Boost及C++11实现生产者消费者模式的四种方法。通过示例代码展示了如何利用线程同步机制如互斥锁、条件变量等来确保线程间的正确交互。

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

  • 先看个Qt的生产者消费者
#include <QtCore>
#include <iostream>

const int DataSize = 100000;
const int BufferSize = 4096;
char buffer[BufferSize];

QWaitCondition bufferIsNotFull;
QWaitCondition bufferIsNotEmpty;
QMutex mutex;
int usedSpace = 0;

class Producer : public QThread
{
public:
    void run();
};

void Producer::run()
{
    for (int i = 0; i < DataSize; ++i) {
        mutex.lock();
        while (usedSpace == BufferSize)
            bufferIsNotFull.wait(&mutex);
        buffer[i % BufferSize] = "ACGT"[uint(std::rand()) % 4];
        ++usedSpace;
        bufferIsNotEmpty.wakeAll();
        mutex.unlock();
    }
}

class Consumer : public QThread
{
public:
    void run();
};

void Consumer::run()
{
    for (int i = 0; i < DataSize; ++i) {
        mutex.lock();
        while (usedSpace == 0)
            bufferIsNotEmpty.wait(&mutex);
        std::cerr << buffer[i % BufferSize];
        --usedSpace;
        bufferIsNotFull.wakeAll();
        mutex.unlock();
    }
    std::cerr << std::endl;
}

int main()
{
    Producer producer;
    Consumer consumer;
    producer.start();
    consumer.start();
    producer.wait();
    consumer.wait();
    return 0;
}
  • 在看一个Boost版本的生产者消费者

template<typename Data>  
class concurrent_queue  
{  
private:  
    std::queue<Data> the_queue;  
    mutable boost::mutex the_mutex;  
    boost::condition_variable the_condition_variable;  
public:  
    void push(Data const& data)  
    {  
        boost::mutex::scoped_lock lock(the_mutex);  
        the_queue.push(data);  
        lock.unlock();  
        the_condition_variable.notify_one();  
    }  
    bool empty() const 
    {  
        boost::mutex::scoped_lock lock(the_mutex);  
        return the_queue.empty();  
    }  
    bool try_pop(Data& popped_value)  
    {  
        boost::mutex::scoped_lock lock(the_mutex);  
        if(the_queue.empty())  
        {  
            return false;  
        }  

        popped_value=the_queue.front();  
        the_queue.pop();  
        return true;  
    }  
    void wait_and_pop(Data& popped_value)  
    {  
        boost::mutex::scoped_lock lock(the_mutex);  
        while(the_queue.empty())  
        {  
            the_condition_variable.wait(lock);  
        }  

        popped_value=the_queue.front();  
        the_queue.pop();  
    }  
};
  • 下面是c++11写的
#include <mutex>
#include <condition_variable>
#include <deque>
#include <iostream>
using namespace std;
std::condition_variable QueueNotFull;
std::condition_variable QueueNotEmpty;
std::mutex  QueueMutex;
std::deque<int> Que;
const int MaxSize = 16
// 判断队列是否为空
bool Empty(){
    return Que.empty();
}
// 判断队列是否已满
bool Full(){
    return Que.size() == MaxSize;
}
// 往队列中添加数据
void Put(int element){
    std::unique_lock<std::mutex> locker(QueueMutex);
    while (Full()){
        cout << "Full !! Wait !!" << endl;
        QueueNotFull.wait(locker);
    }
    Que.push_back(element);
    // 通知其他线程,队列不空
    QueueNotEmpty.notify_all();
}

// 从队列中取出数据
int Get(){
    std::unique_lock<std::mutex> locker(QueueMutex);
    while (Empty()){
        cout << "Empty!! Wait!!" << endl;
        QueueNotEmpty.wait(locker);
    }
    int t = Que.front();
    Que.pop_front();
    // 通知其他等待的对象,队列不满
    QueueNotFull.notify_all();
    return t;
}

// 消费者线程
void GetFunc(){
    while (1){
        int var;
        var = Get();
        cout << "Get : " << var << endl;
    }
}

// 生产者线程
void PutFunc(){
    srand((unsigned int)time(0));
    while (1){
        int var = rand()%100;
        Put(var);
    }
}

int main(int arc,char** argv)
{
    // 启动两个线程
    std::thread td1(GetFunc);
    std::thread td2(PutFunc);
    td1.join();
    td2.join();
    return 0;
}
  • 下面是自己写的一个c++11版本的
#include <iostream>
#include <mutex>
#include <condition_variable>
#include <deque>
#include <thread>
std::condition_variable notFull;
std::condition_variable notEmpty;
std::mutex mtx;
std::deque<int> deq;
const int MAX_SIZE = 16;
bool empty(){
    return deq.empty();
}

bool full(){
    return deq.size() == MAX_SIZE;
}

void put(int num){
    std::unique_lock<std::mutex> lock(mtx);
    while (full()){
        notFull.wait(lock);
    }
    deq.push_back(num);
    notEmpty.notify_all();
}

int get(){
    std::unique_lock<std::mutex> lock(mtx);
    while (empty()){
        notEmpty.wait(lock);
    }
    int num = deq.front();
    deq.pop_front();
    notFull.notify_all();
    return num;
}


void putFunc(){
    int i = 0;
    while (i < 100000){
        put(i++);
    }
}

void getFunc(){
    int i = 0;
    while (i++ < 100){
        cout << get() << endl;
    }
}

int main()
{
    std::thread t1(putFunc);
    std::thread t2(getFunc);
    t1.join();
    t2.join();
    system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值