c++11 条件变量

#include <iostream>
#include <thread>
#include <future>
#include <condition_variable>
#include <random>
#include <queue>

std::random_device rd;
std::mt19937 mt(rd());

class A
{
    public:
    A(){};
    void produce()
    {
        std::unique_lock<std::mutex> lock_guard(_mutex);
        int m = mt();
        _que.push(m);
        std::cout<<"in thread "<<std::this_thread::get_id()<<" generated "<<m<<std::endl;
        _cond.notify_one();//这里已经产生了数字供消费者消费,只需要将一个做了_cond.wait(lock_guard)操作的,正在休眠的线程唤醒,不过只能唤醒一个
    }
    void consume()
    {
        std::unique_lock<std::mutex> lock_guard(_mutex);
        while(_que.empty())
        {
            _cond.wait(lock_guard);//假如说某一时刻,此线程获得了锁,它先检查是否满足条件,如果条件不满足,
            // _cond就通过_cond.wait(lock_guard)操作将线程休眠,等待被条件变量的操作_cond.notify_one()或者_cond.notify_all()唤醒,然后再去竞争
            //_cond.wait(lock_guard)的真实含义
        }
        int ff = _que.front();
        _que.pop();
        std::cout<<"in thread "<<std::this_thread::get_id()<<" poped "<<ff<<std::endl;
    }
    private:
    std::mutex _mutex;
    std::condition_variable _cond;
    std::queue<int> _que;
};

int main()
{
    A a;
    for(int i =0; i<1000;i++)
    {
        std::thread t1(&A::produce,&a);//如果要在多线程中调用成员函数,其实很简单,因为本质上,所有成员函数的一个参数隐藏默认的this指针,也就是说,即使一个看起来
        //空的成员函数,他都包含一个隐藏的参数,参数为this指针,不然怎么化成c???也就是说A的produce函数本质是void A::product(A* this),所以只需要将a的指针或者
        //引用传进去即可,而且这个参数位置肯定是第一个,不解析
        std::thread t2(&A::consume,&a);
        if(t1.joinable())
        {
            t1.join();
        }
        if(t2.joinable())
        {
            t2.join();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值