c++11 std::async与std::future

范例一:

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;

void aa()
{
	std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
	while (1) {

	}
}

void run()
{
	//启动一个异步的线程,返回结果是一个函数模板,
	auto it = std::async(aa);
}
int main()
{
	//run();
	//用{}限制下std::async函数模板的作用域,注意看打印结果,由于aa函数里面有一个while循环
	//所以,在std::async还没有析构之前,只会打印出一个主线程ID,后续的不会打印,
	{
		auto it = std::async(aa);
		std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	}
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	return 0;
}

在这里插入图片描述
范例二:

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
	std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
	return 3;
}
int main()
{
	//启动一个异步线程
	auto it = std::async(run);
	std::cout << it.get() << std::endl; //获取函数返回结果
	return 0;
}

在这里插入图片描述
范例三:

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;
int run()
{
	std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
	return 3;
}
int main()
{
	//启动一个异步线程
	auto it = std::async(run);
	it.wait(); //等待线程返回
	return 0;
}

范例四:

#include <iostream>
#include <string>
#include <thread>
#include <future>
using namespace std;

int run()
{
	std::cout << "子线程ID = " << std::this_thread::get_id() << std::endl;
	return 3;
}
int main()
{
	//启动一个异步线程
	auto it = std::async(std::launch::deferred,run);
	std::cout << "主线程ID = " << std::this_thread::get_id() << std::endl;
	//如果没有调用wait成员函数或者get成员函数,则不会调用run函数,
	//如果调用了这些成员函数,者会调用run函数,但是不会创建新的线程
	it.wait(); //等待线程返回
	return 0;
}

在这里插入图片描述
std::async的参数还有其它,大家可以自行尝试。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值