std::async中的奇怪行为

Strange behaviour in std::async

本文关键字:async std      更新时间:2023-10-16

我想有一个任务,如果它运行时间不够,可以被杀死。

所以我在尝试这个:

#include <iostream>
#include <future>
using namespace std;
int main()
{
    auto handle = std::async(std::launch::deferred,[]
                        {
                            cout<<"Initializing thread..."<<endl; 
                            this_thread::sleep_for(std::chrono::seconds(5));
                        }
                );
    cout<<"Starting..."<<endl;
    handle.wait_for(std::chrono::seconds(2));
    cout<<"Finished correctly"<<endl;
    return 0;
}

输出:

开始……

正确完成

为什么不打印"初始化线程"?我尝试交换两个chronos和不工作无论如何

您从不要求任务的结果,因此它不被调度。

deferred替换为async,您将得到您所期望的

deferred仅对定时wait函数求值。如果更改为:

handle.wait();