我的代码如下:
void f1() {
for (int i = 0; i < 1000; ++i) {
std::cout << "f1: " << i << std::endl;
}
}
void f2() {
for (int i = 0; i < 10; ++i) {
std::cout << "f2: " << i << std::endl;
}
}
auto fz = []() {
auto l_future = std::async(std::launch::async, f1);
auto r_future = std::async(std::launch::async, f2);
while (!is_ready(r_future)) {}
std::cout << "right done" << std::endl;
};
fz();
std::cout << "one of task done" << std::endl;
结果是打印了“正确完成”但 fz() 没有完成。“完成任务之一”被打印,直到 f1 完成。现在我想在 f1 完成之前打印“完成的任务之一”。我该怎么办?
最佳答案
来自 this std::async
reference :
If the
std::future
obtained fromstd::async
is not moved from or bound to a reference, the destructor of thestd::future
will block at the end of the full expression until the asynchronous operation completes
当 lambda 结束时,两个
std::future
对象被破坏,破坏l_future
将阻塞直到函数 f1
返回。
关于c++ - std::async int 函数可以在任务完成之前退出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59171628/