#include<iostream>
#include<thread>
#include<string>
#include<mutex>
#include<fstream>
#include<deque>
#include<chrono>
#include<condition_variable>
std::deque<int> q;
std::mutex mu;
std::condition_variable cond;
void fun1() {
for (int i = 0; i < 10; i++)
{
std::unique_lock<std::mutex> loker(mu);
//loker.lock();
std::cout << "fun1" << i << std::endl;
q.push_back(i);
loker.unlock();
cond.notify_one();//一个等待线程
cond.notify_all();//多个等待线程
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
void fun2()
{
int data = 0;
while (data!=9)
{
std::unique_lock<std::mutex> loker(mu);
cond.wait(loker);//解锁互斥对象mu,并将其休眠,之后会重新加锁,所以此处用unique_lock
cond.wait(loker, []() {return !q.empty(); });//防止q不为空的时候激活,加入lamida函数
data = q.back();
std::cout << "fun2 : " << q.back() << std::endl;
q.pop_back();
loker.unlock();
}
}
void main() {
std::thread t2(fun2);
std::thread t1(fun1);
t1.join();
t2.join();
system("pause");
}
C++ : 多线程之条件变量
最新推荐文章于 2024-02-26 20:45:11 发布