Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ssl/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 使用std::async执行的任务就像使用future一样被阻塞_C++_C++11 - Fatal编程技术网

C++ 使用std::async执行的任务就像使用future一样被阻塞

C++ 使用std::async执行的任务就像使用future一样被阻塞,c++,c++11,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 namespa

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

  {
    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具有等待任务在析构函数中完成的特殊属性

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

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

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

是,STD::ASYN返回的未来具有在析构函数中等待任务完成的特殊属性。 这是因为松散线程是个坏消息,您必须等待该线程的唯一标记是在未来的析构函数中

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


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

你是正确的,STD的析构函数:如果它是最后一个等待共享状态的最后的未来,它等待着它完成,它是由STD::AYNC创建的。请参阅@Corristo:请在“答案”部分写下您的答案。@BoundaryPosition因为我没有包括解决问题的方法,所以我认为它不值得回答。出于某种原因,我认为编译器可以优化掉这些未使用的返回值。@Corristo:注释用于请求澄清。如果不值得回答,就不要写出来但不要在评论中这样做,因为我们无法对其进行同行评审。谢谢。您是对的,如果std::future是最后一个等待共享状态的future,并且它是由std::async创建的,那么std::future的析构函数将一直等到它完成。请参阅@Corristo:请在“答案”部分写下您的答案。@BoundaryPosition因为我没有包括解决问题的方法,所以我认为它不值得回答。出于某种原因,我认为编译器可以优化掉这些未使用的返回值。@Corristo:注释用于请求澄清。如果不值得回答,就不要写出来但不要在评论中这样做,因为我们无法对其进行同行评审。谢谢