(8)C++互斥量,條件變量---mutex,condition_variable

互斥量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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章