#include <iostream>
#include <condition_variable>
#include <mutex>
#include <queue>
#include <deque>
#include <thread>
/*
1.condition_variable()默认构造函数
2.condition_variable(const condition_variable &)=delete 禁止拷贝
3.condition_variable& condition_variable::operator=(const condition_variable &)=delete 禁止赋值
4.notify_one() 通知一个等待的线程 如果生产的数据有一个 那么使用这个函数比较合适
5.notify_all() 通知全部等待的线程 如果生产的数据有多个 那么使用此函数
6.wait(unique_lock<mutex> lock) 阻塞当前线程 直到通知到达
7.wait(unique_lock<mutex> lock, Pred pred) 循环阻塞当前线程 直到通知到达且谓词满足
// ======条件变量解锁过程======
//
// t1 t2 t3
// 获取锁
// wait解锁 获取锁
// 阻塞 wait解锁 获取锁
// 阻塞 wait解锁
// | 阻塞
// |
// |-----------------notify.one()
// 加锁
// 处理
// 解锁
*/
using namespace std;
class Test
{
public:
int inCache(int count);
int outCache();
~Test(){
cout << "~Test"<< endl;
}
private:
mutex m_mutex;
condition_variable m_cond;
queue<string> m_queue;
};
int Test::inCache(int count)
{
unique_lock<mutex> lk(m_mutex);
thread::id tid = this_thread::get_id();
string s;
for(int i=1;i<count+1; i++)
{
s = to_string(i);
m_queue.push(s);
//cout << "write data = " << s << endl;
//m_cond.notify_one();
m_cond.notify_all();//通知所有线程 避免消费者>生产者 虚假唤醒
}
return count;
}
// ======条件变量解锁过程======
//
// t1 t2 t3
// 获取锁
// wait解锁 获取锁
// 阻塞 wait解锁 获取锁
// 阻塞 wait解锁
// | 阻塞
// |
// |-----------------notify.one()
// 加锁
// 处理
// 解锁
int Test::outCache()
{
while (true)
{
unique_lock<mutex> lk(m_mutex);
//cout << "线程" << std::this_thread::get_id() << " 拿到锁" << std::endl;
while(m_queue.empty())//避免虚假唤醒
m_cond.wait(lk);//1)把锁解开 2)阻塞,等待唤醒,其他线程可以拿到锁了 3)加锁
string s = m_queue.front();
cout << "线程" << std::this_thread::get_id() << " read queue = \"" << s << "\"" << std::endl;
m_queue.pop();
lk.unlock();
this_thread::sleep_for(chrono::microseconds(1));//模拟数据处理时间 在此时间内 其他线程可以继续读取队列中的数据
}
return 1;
}
int main()
{
Test test;
//消费者
thread r1(&Test::outCache, &test);
thread r2(&Test::outCache, &test);
thread r3(&Test::outCache, &test);
thread r4(&Test::outCache, &test);
//生产者
this_thread::sleep_for(chrono::seconds(1));
thread w1(&Test::inCache, &test, 1);
this_thread::sleep_for(chrono::seconds(2));
thread w2(&Test::inCache, &test, 6);
w1.join();
w2.join();
r1.join();
r2.join();
r3.join();
r4.join();
return 0;
}
c++ condition_varition解析
最新推荐文章于 2024-07-22 09:38:37 发布