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

标签 c++ multithreading c++11 c++14 c++17

我的代码如下:

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/

相关文章:

c++ - 导致在 32 位代码中使用 64 位变量会导致性能下降

c++ - 为什么 threading.stack_size() 没有产生想要的效果?

c# - 合作/非抢占式线程避免死锁?

c++ - 更好的做法 : Ever looping thread or successive threads?

c++ - 为什么这个简单的代码会出现语法错误?

map 和 multimap 之间的 C++ 模板特化

c++ - GCC 程序不捕获异常

c++ - 转换为 Cinder gl::Texture

c++ - 如何将时间字符串(M:SS)转换为float

java - 用于从数据库读取和更新 REST 服务器的多线程 Java 控制台应用程序