async多线程的简单使用例子

using namespace std;
#include<iostream>
#include<mutex>
#include<future>
#include<thread>
#include<chrono>

int g_id = 0;
mutex mutex_g_id;

int consumer(void)
{
	lock_guard<mutex> lock(mutex_g_id);
	g_id = 0;
	for (size_t i = 1; i <= 100; i++)
	{
		g_id += i;
	
		std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(5));
	}
	
	
	return g_id;
}

int producer(void)
{
	
	lock_guard<mutex> lock(mutex_g_id);
	g_id = 0;
	for (size_t i = 1; i <= 100; i++)
	{
		g_id += i;
	
		std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(5));
	}

	return g_id;
}


int main()
{

	auto a = async(launch::async,consumer);
	auto b = async(launch::async, producer);
	
	cout << a.get() << endl;
	
	cout << b.get() << endl;


}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 1024 设计师:白松林 返回首页