一般条件变量都是结合互斥量运用。
这里不作过多的解释,学多C和C++都知道运用,程序中写有注解,直接看代码案例就好了。
如果有不懂的地方,去查一下吧 。(下面案例很简单)
案例如下:
#include<condition_variable>
#include<mutex>
#include<thread>
#include<iostream>
#include<chrono>
//C++条件变量
using namespace std;
using namespace this_thread;
/*
condition_variable 类
1,调用wait函数 阻塞线程
2,通过 unique_lock 加锁线程
3,notify_one notfy_all 唤醒单个线程 唤醒多个线程
*/
condition_variable cv; //条件变量
mutex cv_m;
int i = 0; //描述唤醒条件
bool done = false; //充当开关
void waits_thread(int id)
{
unique_lock<mutex> opne(cv_m); //加锁
cout <<id<< "等待中......" << endl;
cv.wait(opne, [] {return i == 1; });
//this_thread::sleep_for(chrono::seconds(id));
cout <<id<< "运行结束" << endl;
done = true;
}
void signal_noe()
{
this_thread::sleep_for(1s); //延时1s
cout <<"不做条件变量唤醒操作" << endl;
cv.notify_one();
unique_lock<mutex> OFF(cv_m);
i = 1;
while (!done)
{
cout << "条件变量满足唤醒操作"<<endl;
OFF.unlock();
cv.notify_one();
this_thread::sleep_for(1s);
OFF.lock();
}
}
void testNotifyOne()
{
thread t1(waits_thread,0);
thread t2(signal_noe);
t1.join();
t2.join();
}
//多个线程唤醒
void signals_all()
{
this_thread::sleep_for(1s); //延时1s
{
unique_lock<mutex> open(cv_m);
cout << "无条件变量改变的唤醒" << endl;
cv.notify_all();
}
this_thread::sleep_for(1s);
{
unique_lock<mutex> OFF(cv_m);
cout << "带条件变量改变的唤醒操作" << endl;
i = 1;
cv.notify_all();
}
}
void testNotify_all()
{
thread t1(waits_thread,1);
thread t2(waits_thread,2);
thread t3(waits_thread,3);
thread t4(signals_all);
t1.join();
t2.join();
t3.join();
t4.join();
}
int main()
{
//testNotifyOne();
testNotify_all();
return 0;
}