1、async
async是一个函数模板,用来启动一个异步任务,启动异步任务后,返回一个future对象。这个future对象里含有线程入口函数锁返回的结果(线程返回结果),可通过future对象的成员函数get()来获取。
2、future
(1)future:
将来的意思,提供了一种访问异步操作结果的机制,此结果可能没马上拿到,可在线程执行完毕后拿到结果,该结果可使用future类中get()函数来获取。
(2)launch::deferred和launch::async
launch::deferred:表示线程入口函数调用被延迟到future的wait()或者get()调用时才执行 若wait()或get()没调用,那么线程是不执行的,并且没创建新线程,是在主线程中调用线程入口函数。
launch::async:在调用async函数时立刻开始创建线程async()函数默认使用launch::async,所以一般省略此参数。
例
#include <iostream>
#include <string>
#include <thread>
#include <mutex>
#include <future>
using namespace std;
class A
{
public:
A() {}
~A() {}
int myThread(int tm)
{
cout << "tm = " << tm << endl;
cout << "myThread() start, threadID = " << this_thread::get_id() << endl;
chrono::microseconds dura(5000); // 定义时长,5秒
this_thread::sleep_for(dura); // 休眠一定时长
cout << "myThread() end, threadID = " << this_thread::get_id() << endl;
return 5;
}
};
int main()
{
A a;
int tm = 122;
cout << "main ,threadID = " << this_thread::get_id() << endl;
future<int> result = async(&a