目录
写在前面
如果有一个需要长时间运算的线程,需要计算出最终的有效值,但是现在不迫切需要这个数值,如果我们使用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;
}
</