使用 std::async 准备好后立即显示结果
Displaying results as soon as they are ready with std::async
我正在尝试发现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;
}
}
现在,这个例子并不有趣,但它提出了一个对我来说很有趣的问题。假设我想在结果"到达"时显示结果(我不知道首先准备好什么,因为延迟是随机的),我应该怎么做?
我在这里所做的显然是错误的,因为我按照创建它们的顺序等待所有任务 - 所以我会等待第一个任务完成,即使它比其他任务长。
我想到了以下想法:对于每个future
,在短时间内使用wait_for
,如果准备就绪,则显示值。但我觉得这样做很奇怪:
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;
}
}
这带来了另一个问题:我们会在某些future
上多次调用get
,这是非法的:
在抛出 'std::future_error'
的实例后调用终止 what(): std::future_error:无关联状态
所以我真的不知道该怎么做,请建议!
使用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);
相关文章:
- 代码未在联机编译器上显示结果
- 我的循环超时并且不显示结果
- C 可执行文件从浏览器下载而不是显示结果
- 如果满足嵌套条件,则计算结果未显示结果C
- 使用 std::async 准备好后立即显示结果
- if, else if, else 函数未准确显示结果
- C++:如何在控制台窗口中显示结果
- VIM:执行复杂文件类型的脚本和显示结果
- 根据标准对结构向量进行排序,然后显示结果
- c++将var从一个函数传递到另一个函数,然后在主函数中显示结果
- 当结果超过 100 时,程序不显示结果
- 对输入'age'名称进行排序,然后显示结果
- 代码可以运行,但不在 Eclipse 中显示结果。
- 将代码C++到 MIPS 中,MIPS 中的代码运行时没有错误消息,但不显示结果
- 为什么使用 scanf() 时显示结果有延迟
- 如何使用信号和插槽从qt表单中获取id,然后在链表中搜索它并使用另一个表单显示结果
- C++不显示结果
- 最长公共子序列没有显示结果
- C++需要在Main()调试中显示结果的帮助
- C/C++读取UART端口并显示结果