简体   繁体   English

std :: async中的奇怪行为

[英]Strange behaviour in std::async

I want have one task that can be killable if it's running of time. 我希望有一项任务,如果时间紧迫,可以终止。

So i am tryng this: 所以我正在尝试这个:

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

The ouput: 输出:

Starting... 开始...

Finished correctly 正确完成

Why don't print "Initializing thread..."? 为什么不打印“正在初始化线程...”? I tried swap both chronos and doesn't works anyway 我尝试交换两个chronos,但还是无法正常工作

You never demand the result of the task, so it isn't scheduled. 您永远不需要任务的结果,因此它没有计划。

Replace deferred with async and you'll get what you expect. async代替deferred ,您将得到期望的结果。

deferred only evaluates on a non -timed wait function. deferred仅对定时wait函数求值。 If you change to: 如果更改为:

handle.wait();

You'll see the thread start at that point. 您会看到线程从那时开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM