gpt4 book ai didi

c++ - std::async int 函数可以在任务完成之前退出吗?

转载 作者:行者123 更新时间:2023-12-04 16:57:24 31 4
gpt4 key购买 nike

我的代码如下:

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 from std::async is not moved from or bound to a reference, the destructor of the std::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/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com