互斥量std::metux:锁定资源不被同时访问
条件变量:(1)阻塞线程,等待某条件满足继续往下执行(2)通知其他线程继续执行,因为条件变量在阻塞过程中并不会轮询当前条件的值。也有说是唤醒其他线程的说法,因为等待中的线程是在睡眠状态的,你不去通知他他就一直睡着不起来干活。
#include <iostream>
#include <thread>
#include <windows.h>
#include <string>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <chrono>
int number = 0;
std::mutex mtx;//定义互斥量
std::condition_variable con_var;//定义条件变量
bool flag = true;
void fun1()
{
for (int i = 0; i < 1000; i++)
{
std::unique_lock<std::mutex> lck(mtx);
con_var.wait(lck, [] {return flag; });//条件变量阻塞等待flag为真
//以下注释的代码跟 con_var.wait(lck, [] {return flag; }); 这句等价的,下面的更好理解
//while (true)
//{
// if (flag)
// {
// con_var.notify_one();
// break;
// }
// con_var.wait(lck);
// std::this_thread::sleep_for(std::chrono::milliseconds(10));
//}
flag = false;
number++;
con_var.notify_one();//条件变量通知线程可以继续执行
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << number << std::endl;
}
}
void fun2()
{
for (int i = 0; i < 1000; i++)
{
std::unique_lock<std::mutex> lck(mtx);
//con_var.wait(lck, [] {return !flag; });
while (true)
{
if (!flag)
{
con_var.notify_one();
break;
}
con_var.wait(lck);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
flag = true;
number--;
//con_var.notify_one();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
std::cout << number << std::endl;
}
}
int main()
{
std::thread th1(fun1);
std::thread th2(fun2);
th1.join();//等待线程执行完成后再执行后续代码
th2.join();
//th1.detach();
//th2.detach(); //直接运行主线程
system("pause");
return 0;
}