c++11多线程中的std::async异步函数

本文介绍了C++11中的std::async异步函数,用于创建可返回结果的异步任务。std::async返回std::future对象,持有线程的返回数据。通过std::future的成员函数如wait_for、wait_until和get,可以控制和获取异步任务的结果。此外,文章还讨论了std::launch类型的使用,包括延迟执行和立即创建新线程的选项。
摘要由CSDN通过智能技术生成

目录

写在前面

解析

future类成员函数

wait_for以及wait_until返回值类型

get函数

valid函数

wait_for函数

std::launch类型

参考博客


写在前面

如果有一个需要长时间运算的线程,需要计算出最终的有效值,但是现在不迫切需要这个数值,如果我们使用std::thread的话,着一定是不可行的,因为std::thread不可以接收返回值,这里需要使用std:async函数模板

我们可以使用std::async创建一个异步任务,返回std:future对象,这个std:future对象持有线程返回的数据

解析

std::saync是一个类模板,他的构造函数包含两种形式:

template <class Fn, class... Args>
  future<typename result_of<Fn(Args...)>::type>
    async (Fn&& fn, Args&&... args);
template <class Fn, class... Args>
  future<typename result_of<Fn(Args...)>::type>
    async (launch policy, Fn&& fn, Args&&... args);

可以知道,std::async的使用方法和std::thread类似,但是在第二个构造函数中,存在一个std::launch类型的参数,后面详细说明此参数,并且std::async都会返回一个std::future对象,用来存放返回的数据。

#include <iostream>
#include <future>
#include <string>
#include <vector>

int mythread()
{
	std::cout << "mythread() start thread id =" << std::this_thread::get_id() << std::endl;
	std::this_thread::sleep_for(std::chrono::seconds(5));
	std::cout << "mythread() start thread id =" << std::this_thread::get_id() << std::endl;
	return 5;
}
int main()
{
	std::cout << "main function id:" << std::this_thread::get_id() << std::endl;
	std::future<int> result = std::async(mythread);
	//或者使用auto自动判断返回值类型:auto result = std::async(mythread);

	std::cout << "continue......!" << std::endl;
	std::cout << result.get() << std::endl;
	
	std::cout << "main function finish!" << std::endl;
	return 0;
}</
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值