使用std :: async准备好结果后立即显示

Tho*_*ski 5 c++ asynchronous

我正在尝试发现C ++中的异步编程。这是我一直在使用的玩具示例:

#include <iostream>
#include <future>
#include <vector>

#include <chrono>
#include <thread>

#include <random>

// For simplicity
using namespace std;

int called_from_async(int m, int n)
{
    this_thread::sleep_for(chrono::milliseconds(rand() % 1000));
    return m * n;
}

void test()
{
    int m = 12;
    int n = 42;

    vector<future<int>> results;

    for(int i = 0; i < 10; i++)
    {
        for(int j = 0; j < 10; j++)
        {
            results.push_back(async(launch::async, called_from_async, i, j));
        }
    }

    for(auto& f : results)
    {
        cout << f.get() << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

Now, the example is not really interesting, but it raises a question that is, to me, interesting. Let's say I want to display results as they "arrive" (I don't know what will be ready first, since the delay is random), how should I do it?

What I'm doing here is obviously wrong, since I wait for all the tasks in the order in which I created them - so I'll wait for the first to finish even if it's longer than the others.

I thought about the following idea: for each future, using wait_for on a small time and if it's ready, display the value. But I feel weird doing that:

while (any_of(results.begin(), results.end(), [](const future<int>& f){
    return f.wait_for(chrono::seconds(0)) != future_status::ready;
}))
{
    cout << "Loop" << endl;
    for(auto& f : results)
    {
        auto result = f.wait_for(std::chrono::milliseconds(20));
        if (result == future_status::ready)
            cout << f.get() << endl;
    }
}
Run Code Online (Sandbox Code Playgroud)

This brings another issue: we'd call get several times on some futures, which is illegal:

抛出'std :: future_error'what
()实例后终止调用:std :: future_error:无关联状态

所以我真的不知道该怎么办,请提出建议!

vll*_*vll 4

用于valid()跳过您已经调用的期货get()

bool all_ready;
do {
    all_ready = true;
    for(auto& f : results) {
        if (f.valid()) {
            auto result = f.wait_for(std::chrono::milliseconds(20));
            if (result == future_status::ready) {
                cout << f.get() << endl;
            }
            else {
                all_ready = false;
            }
        }
    }
}
while (!all_ready);
Run Code Online (Sandbox Code Playgroud)

  • 不是真正的解决方案。该代码仍然按照每个任务的创建顺序等待 20 毫秒。它可能会产生一种错觉,即结果“一旦”可用就被打印出来,并且对于简单的情况可能就足够了。但是尝试一下 100 个任务,首先创建慢速任务,最后创建快速任务。真正的解决方案涉及更多一些,需要一个“互斥体”、一个“条件变量”和某种结果队列。 (2认同)