c++ - 使用 std::async 执行的任务正在阻塞,就像使用了 future 一样

标签 c++ c++11

我很难理解为什么会出现以下代码块:

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

我怀疑 std::async 返回 std::future 作为临时的,它在析构函数中加入任务线程。是否可以?

完整代码如下:

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;

}

最佳答案

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

这是因为松散的线程是个坏消息,您必须等待该线程的唯一标志是在未来的析构函数中。

要解决此问题,请存储结果 future ,直到您需要完成结果,或者在极端情况下程序结束。

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

关于c++ - 使用 std::async 执行的任务正在阻塞,就像使用了 future 一样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43559825/

相关文章:

c++ - C++类外函数

c++ - 快速读取带有 float 的文本文件

c++ - 在 C++03 中是否可以使用非 const 右值引用?

c++ - 如何使用 C++ 中的默认构造函数定义和声明变量?

c++ - 如何让 "factory function"返回一个不可复制的对象?

c++ - 这种与浮点文字零的比较有效吗?

c++ - Clang 和 GCC 在使用大括号表示法和 initializer_list 时不同意构造函数的选择

c++ - GCC 不遵守 'pragma GCC diagnostic' 以消除警告

c++ - 在外部程序窗口中查找给定控件的最简单方法是什么?

c++ - Visual Studio 2015 默认附加库