栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++11 多线程-std::condition

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++11 多线程-std::condition

#include 
#include 
#include 
#include 
std::mutex mtx;
std::condition_variable cv;
int signal_sym = 0;

struct MySturuct
{
	int a;
};
std::queue;

void PrintString_1()
{
	std::unique_lock lk(mtx);
	int cnt = 0;
	while (cnt < 10)
	{
		while (signal_sym != 0)
			cv.wait(lk);
		std::cout << std::this_thread::get_id() << " : " << "A" << std::endl;
		signal_sym = 1;
		cnt++;
		cv.notify_one();
	}
}

void PrintString_2()
{
	std::unique_lock lk(mtx);
	int cnt = 0;
	while (cnt < 10)
	{
		while (signal_sym != 1)
			cv.wait(lk);
		std::cout << std::this_thread::get_id() << " : " << "B" << std::endl;
		signal_sym = 2;
		cnt++;
		cv.notify_one();
	}
}

void PrintString_3()
{
	std::unique_lock lk(mtx);
	int cnt = 0;
	while (cnt < 10)
	{
		while (signal_sym != 2)
			cv.wait(lk);
		std::cout << std::this_thread::get_id() << " : " << "C" << std::endl;
		signal_sym = 0;
		cnt++;
		cv.notify_one();
	}
}


int main()
{
	std::thread  t1(PrintString_1);
	std::thread  t2(PrintString_2);
	std::thread  t3(PrintString_3);
	t1.join();
	t2.join();
	t3.join();
	return 0;
}

可以参考std::condition_variable notify_one()与notify_all()的区别_xupeng1644的博客-CSDN博客,学习一下notify_one和notify_all;

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/316418.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号