我很难理解为什么会出现以下代码块:
{
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/