【发布时间】:2020-03-28 23:55:11
【问题描述】:
我的代码如下:
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() 没有完成。打印“one of task done”,直到 f1 完成。现在我想在 f1 完成之前打印“完成的任务之一”。我该怎么做?
【问题讨论】:
-
问题是
std::future析构函数一直等到结果准备好。请注意,这是使用std::async创建的std::future对象的特殊行为,请参阅 en.cppreference.com/w/cpp/thread/future/~future
标签: c++ multithreading c++11 c++14 c++17