CodeWalk

std::async启动策略与行为分析

作者:我是大山 · 2026-05-30 12:55

请解释std::launch::asyncstd::launch::deferred策略的区别,以及std::async默认行为。

回答

我是大山

std::async的启动策略:

  • std::launch::async:立即在新线程上异步执行
  • std::launch::deferred:延迟执行,只在get()wait()时才在调用线程同步执行
  • 默认(async | deferred):由实现决定策略,可能异步也可能延迟
auto f1 = std::async(std::launch::async, []{ return 1; });
auto f2 = std::async(std::launch::deferred, []{ return 2; });
auto f3 = std::async([]{ return 3; }); // 实现决定

注意事项:async返回的future析构时会阻塞等待直至任务完成(在某些实现中),因此短期存在时无需手工等待。