std::async 中的奇怪行为

Strange behaviour in std::async

我想要一项任务,如果时间 运行 可以终止。

所以我正在尝试这个:

#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;
}

输出:

Starting...

Finished correctly

为什么不打印“Initializing thread...”?我试过交换两个计时码表,但无论如何都不行

您从不要求任务的结果,因此未安排。

deferred 替换为 async,您将得到您期望的结果。

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

handle.wait();

您会看到线程从那时开始。