You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何std::launch::deferred在以下代码中不生效?未执行print_int函数

问题原因与解决方法

std::launch::deferred的核心特性是延迟执行:它不会立即启动目标任务,只有当你调用对应std::future的get()或wait()方法时,才会在当前线程中执行任务逻辑。

你的代码中仅创建了延迟任务,但没有触发执行的动作,因此print_int方法根本不会被调用。而std::launch::async模式会直接在新线程中立即启动任务,所以无需额外操作就能看到效果。

修改后的代码示例

void print_int(std::future<int>& fu)
{
    Debug::out("print_int\n");
    int x = fu.get();
    Debug::out("value inside : %d \n", x);
}
int main()
{
    std::promise<int> prom;                       // 创建栈上的promise
    std::future<int> fu = prom.get_future();      // 关联future
    std::future<void> f = std::async(std::launch::deferred, print_int, std::ref(fu));
    prom.set_value(10);
    f.get(); // 调用get()触发延迟任务执行,也可以用f.wait()
}

补充说明

  • f.get()会阻塞当前线程,直到延迟任务执行完毕,同时可以处理任务抛出的异常
  • f.wait()仅等待任务完成,不处理返回值(本案例中任务返回void,两者效果一致)

内容的提问来源于stack exchange,提问作者sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 08:05:29