使用std :: async执行的任务会阻塞,就像使用了future一样 [英] Task executed with std::async is blocking like if future was used

查看:100
本文介绍了使用std :: async执行的任务会阻塞,就像使用了future一样的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难理解以下代码块的原因:

  {
std :: async(std :: launch :: async,[] {std :: this_thread :: sleep_for(5s);
//仅在上述任务完成后才能执行此行?
}

我怀疑 std :: async 返回 std:



完整代码如下:

  int main(){
使用命名空间std :: literals;

{
auto fut1 = std :: async(std :: launch :: async,[] {std :: this_thread :: sleep_for(5s); std :: cout<<< work done 1!\n;});
//它的析构函数中的fut1将在与上述任务相关联的线程上强制执行联接。
}
std :: cout<<<<完成-在与fut1相关联的线程上隐式联接刚刚结束\n\n;

std :: cout<<测试2开始<< std :: endl;
{
std ::异步的(std :: launch :: async,[] {std :: this_thread :: sleep_for(5s); std :: cout<< 完成工作2! << std :: endl; });
//没有未来,因此它不应该加入-但是-它确实以某种方式加入。
}
std :: cout<< 这个雪橇秀在工作完成前2 !! << std :: endl;

}


解决方案

是的, async 返回的 std :: future 具有等待在析构函数中完成任务的特殊属性。 / p>

这是因为宽松的线程是个坏消息,而您唯一需要等待的令牌就是将来的析构函数。



要解决此问题,请存储生成的期货,直到需要完成结果为止,或者在极端情况下,程序结束。



编写自己的线程池系统也是一个好主意。我发现C ++线程原语足以编写线程系统,但是我不鼓励在小型程序之外使用Raw。


I am having a hard time understanding why following code blocks:

  {
    std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); 
    // this line will not execute until above task finishes?
  }

I suspect that std::async returns std::future as temporary which in destructor joins on the task thread. Is it possible?

Full code is below:

int main() {
  using namespace std::literals;

  {
    auto fut1 = std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 1!\n"; });
    // here fut1 in its destructor will force a join on a thread associated with above task.
  }
  std::cout << "Work done - implicit join on fut1 associated thread just ended\n\n";

    std::cout << "Test 2 start" << std::endl;
  {
    std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); std::cout << "work done 2!" << std::endl; });
    // no future so it should not join - but - it does join somehow.
  }
  std::cout << "This shold show before work done 2!?" << std::endl;

}

解决方案

Yes, std::future returned by async has the special property of waiting for the task to be completed in the destructor.

This is because loose threads are bad news, and the only token you have to wait for that thread is in the destructor of the future.

To fix this, store the resulting futures until either you need the result to be done, or in extreme cases the end of the program.

Writing your own thread pool system is also a good idea; I find C++ threading primitives to be sufficient to write a threading system, but use in the raw is not something I'd encourage outside of tiny programs.

这篇关于使用std :: async执行的任务会阻塞,就像使用了future一样的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆