Task executed with std::async is blocking like if future was used

后端 未结 1 2031
逝去的感伤
逝去的感伤 2021-01-24 06:50

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

  {
    std::async(std::launch::async, [] { std::this_thread::sleep_for(5s); 
    // this line w         


        
相关标签:
1条回答
  • 2021-01-24 07:06

    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.

    0 讨论(0)
提交回复
热议问题