#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();
}
}
}
c++11 条件变量
最新推荐文章于 2024-07-15 07:48:33 发布