async 和 future提供了一种访问异步操作结果的机制。
async 是函数模板,启动异步任务,返回future对象。启动异步任务的含义是:自动创建一个线程,执行对应的入口函数。
future是类模板,future对象里面含有线程执行的结果,可以通过调用成员函数get()来获取结果。
代码示例
#include<iostream>
#include<thread>
#include<mutex>
#include<future>
using namespace std;
int myThread()
{
cout << "Thread start id = " << this_thread::get_id() << endl;
chrono::milliseconds time(5000); //休息5秒
this_thread::sleep_for(time);
cout << "Thread end id = " << this_thread::get_id() << endl;
return 5;
}
int main()
{
cout << "Main start id = " << this_thread::get_id() << endl;
future<int> result = async(myThread);
cout << "continue......" << endl;
cout << "result = " << result.get() << endl; //阻塞,等待线程myThread结束,获取返回。
return 0;
}
执行结果