首页 » C语言 » c++11 实现两个线程交替同步

c++11 实现两个线程交替同步

原文 http://blog.csdn.net/hutianyou123/article/details/79174201

2018-01-27 02:00:48阅读(127)

#include <thread>
#include <iostream>
#include <mutex>
#include <condition_variable>
std::mutex data_mutex;
std::condition_variable data_var;
bool label = false;
void printodd()
{
	std::unique_lock<std::mutex> ulock(data_mutex);
	for (int odd = 1; odd <= 100; odd += 2)
	{
		data_var.wait(ulock, [] {return label; });
		std::cout << std::this_thread::get_id() << ": " << odd << " labelA= "<<label<<std::endl;
		label = false;
		data_var.notify_one();
	}
}
void printeven()
{
	std::unique_lock<std::mutex> ulock(data_mutex);
	for (int even = 0; even < 100; even += 2)
	{
		std::cout << std::this_thread::get_id() << ": " << even << " labelB= " << label<< std::endl;
		data_var.notify_one();
		label = true;
		data_var.wait(ulock, [] {return !label; });
	}
}
int main()
{
	std::thread t1(printeven);
	std::thread t2(printodd);
	t1.join();
	t2.join();
	std::cout << "end!" << std::endl;
	getchar();
	return 0;
}

最新发布

CentOS专题

关于本站

5ibc.net旗下博客站精品博文小部分原创、大部分从互联网收集整理。尊重作者版权、传播精品博文,让更多编程爱好者知晓!

小提示

按 Ctrl+D 键,
把本文加入收藏夹