async
函数接受两种不同的启动策略,这些策略在std::launch
枚举中定义,如下:
std::launch::defered
:这种策略意味着任务将在调用future::get()
或future::wait
函数时延迟执行,也就是任务将在需要结果时同步执行std::launch::async
:任务在单独一个线程上异步执行默认情况下
async
使用std::launch::defered | std::launch::async
策略,这意味着任务可能异步执行,也可能延迟执行,具体取决于实现,示例:
#include <iostream>
#include <thread>
#include <future>
using namespace std;
thread::id test_async() {
this_thread::sleep_for(chrono::milliseconds(500));
return this_thread::get_id();
}
thread::id test_async_deferred() {
this_thread::sleep_for(chrono::milliseconds(500));
return this_thread::get_id();
}
int main() {
// 另起一个线程去运行test_async
future<thread::id> ans = std::async(launch::async, test_async);
// 还没有运行test_async_deferred
future<thread::id> ans_def = std::async(launch::deferred,test_async_deferred); //还没有运行test_async_deferred
cout << "main thread id = " << this_thread::get_id() << endl;
// 如果test_async这时还未运行完,程序会阻塞在这里,直到test_async运行结束返回
cout << "test_async thread id = " << ans.get() << endl;
// 这时候才去调用test_async_deferred,程序会阻塞在这里,直到test_async_deferred运行返回
cout << "test_async_deferred thread id = = " << ans_def.get() << endl;
return 0;
}
输出结果
main thread id = 1
test_async thread id = 2
test_async_deferred thread id = = 1
Process returned 0 (0x0) execution time : 1.387 s
Press any key to continue.
从输出结果可以看出采用
std::launch::defered
策略时任务是同步执行,采用launch::async
策略时任务是异步执行。