一、async、 future创建后台任务并返回值
希望返回一个结果
async是一个函数模板,用来启动一个异步任务,启动起来一个异步任务后,返回一个future对象
1、什么是异步任务: 就是自动创建一个线程并开始执行对应的线程的入口函数,它返回一个future对象
2、future对象里面就含有线程入口函数所返回的结果(线程返回结果,可以通过调用future对象的成员函数get()来获取)
#include <iostream>
#include <string>
#include <thread>
#include <vector>
#include <list>
#include <mutex>
#include <future>
using namespace std;
int mythread()
{
cout << "子线程id = " << this_thread::get_id() << endl;
chrono::milliseconds dura(5000);
this_thread::sleep_for(dura);
return 5;
}
int main()
{
cout << "main" << "threadid =" << this_thread::get_id() << endl;
future<int> result = async(mythread);
cout << "continue... !" << endl;
int def = 0;
cout << result.get() << endl;
cout << "I Love China!" << endl;
return 0;
}