async 可以创建线程,然后通过使用result.get()等待子进程运行结束。
#include<iostream>
#include<thread>
#include<future>
using namespace std;
int my_print() {
cout << "子线程开始执行" << endl;
chrono::milliseconds wait_minute(2000);
this_thread::sleep_for(wait_minute);
cout << "子线程结束运行" << endl;
return 100;
}
int main() {
future<int>result = async(my_print);
cout << "continue..." << endl;
int a = 0;
cout << result.get() << endl;
cout << "主线程结束" << endl;
return 0;
}
1、std::lunch::deferred:
(defer推迟,延期)表示线程入口函数的调用会被延迟,一直到std::future的wait()或者get()函数被调用时(由主线程调用)才会执行;如果wait()或者get()没有被调用,则不会执行。
实际上根本就没有创建新线程。std::launch::deferred意思时延迟调用,并没有创建新线程,是在主线程中调用的线程入口函数。
2、std::launch::async,在调用async函数的时候就开始创建新线程。