c++使用条件变量实现生产消费问题(跨平台)

1. 生产者线程


思路:队列满了的情况下, 触发条件变量wait, 等待消费线程消费后唤醒继续生产.

void ProducerThreadFunc()
{
    while(1) {            
        while(/* 容器已满 */) {      
            /* 线程等待, 直到消费者消费后唤醒继续执行 */      
        }

        /* 生产动作 */   
    }   
}

2. 消费者线程


思路: 队列中没有元素可以被消费的情况下, 触发条件变量wait, 等待生产线程生产元素之后唤醒继续消费.

// 伪代码
void ConsumerThreadFunc()
{
    while(1) {            
        while(/* 容器为空 */) {          
            /* 线程等待, 直到生产者生产后唤醒继续执行 */    
        }

        /* 消费动作 */        
    }        
}

3. 完整代码


#include <iostream>

#include <vector>
#include <condition_variable>
#include <mutex>
#include <thread>
#ifdef __linux__
#include <unistd.h>
#else
#include <windows.h>
#endif

using namespace std;

void Run_EveryWhere_Sleep(int time)
{
#ifdef __linux__
    sleep(time);
#else 
    Sleep(time * 1000);
#endif
}

class TestClass
{
public:
    int Exec()
    {
        std::thread thread_consumer(&TestClass::ConsumerThreadFunc, this);        
        std::thread thread_producer(&TestClass::ProducerThreadFunc, this);
        thread_consumer.join();
        thread_producer.join();
        return 0;
    }

    void ProducerThreadFunc()
    {
        while(1) {   
            // 使用while防止虚假唤醒         
            while(m_vecNums.size() >= 10) {      
                std::cout << "Producer Thread Wait, Current Size = " << m_vecNums.size() << endl;      
                unique_lock<std::mutex> locker(m_mutex);
                m_cv.wait(locker);    
            }

            int num = rand();
            std::cout << "Produce One Number " << num << std::endl;            
            m_vecNums.emplace_back(num);
            m_cv.notify_all();

            Run_EveryWhere_Sleep(1);
        }   
    }

    void ConsumerThreadFunc()
    {
        while(1) {    
            // 使用while防止虚假唤醒        
            while(m_vecNums.size() <= 0) {      
                std::cout << "Consumer Thread Wait, Current Size = " << m_vecNums.size() << endl;      
                unique_lock<std::mutex> locker(m_mutex);
                m_cv.wait(locker);    
            }

            std::cout << "Consume One Number " << m_vecNums[m_vecNums.size() - 1] << std::endl;
            m_vecNums.pop_back();
            m_cv.notify_all();

            Run_EveryWhere_Sleep(1);
        }        
    }

private:
    vector<int> m_vecNums;          /// > 生产消费对象存储容器

    condition_variable m_cv;        /// > 条件变量
    mutex m_mutex;                  /// > 配合条件变量使用
};

int main(int argc, char **argv)
{
    TestClass A;
    return A.Exec();
}

4. 执行效果


[root@localhost condition_var_test]# g++ main.cpp -lpthread
[root@localhost condition_var_test]# ./a.out 
Produce One Number Consumer Thread Wait, Current Size = 1804289383
Produce One Number 846930886
Consume One Number 846930886
Produce One Number 1681692777
Consume One Number 1681692777
Produce One Number 1714636915
Consume One Number 1714636915
Produce One Number 1957747793
Consume One Number 1957747793
Produce One Number 424238335
Consume One Number 424238335
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SuperYang_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值