【问题标题】:can std::async int a function quit out before task is finished?std::async int 可以在任务完成之前退出函数吗?
【发布时间】: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 完成之前打印“完成的任务之一”。我该怎么做?

【问题讨论】:

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


【解决方案1】:

来自this std::async reference

如果从std::async 获得的std::future 没有从引用中移动或绑定到引用,则std::future 的析构函数将在完整表达式的末尾阻塞,直到异步操作完成

当 lambda 结束并销毁两个 std::future 对象时,l_future 的销毁将阻塞,直到函数 f1 返回。

【讨论】:

    【解决方案2】:

    您的代码挂在 [1] 行

    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;
            // [1]
        };
    

    因为未来的 dtor 等待结果。

    您可以从您的 lambda 返回 future,然后在 cout 调用 get 以等待结果,即直到 f1 任务完成:

    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;
            return l_future; // move future outside lambda
        };
    
    auto fut = fz();
    std::cout << "one of task done" << std::endl;
    fut.get();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-16
      • 1970-01-01
      相关资源
      最近更新 更多