[英]Returning std:vector with std::async c++11
我在使用 std::future 和 std::async 返回 std::vector 时遇到问题。 为什么
#include <iostream>
#include <vector>
#include <functional>
#include <future>
using namespace std;
int main(int argc, char** argv) {
int A = 10;
vector<future<int>> sumarray(A);
for(int i = 0; i < A; i++)
sumarray[i] = async( launch::async, [i] { return i; } );
for(int i = 0; i < A; i++)
cout << sumarray[i].get() << " ";
cout << endl;
}
用 g++ -std=c++11 -pthread 编译,按预期打印
0 1 2 3 4 5 6 7 8 9
但
#include <iostream>
#include <vector>
#include <functional>
#include <future>
using namespace std;
int main(int argc, char** argv) {
int A = 10;
int B = 2;
vector<future<vector<int>>> sumarray(A);
for(int i = 0; i < A; i++){
sumarray[i] = async( launch::async, [i,B] {
vector<int> v(B);
for(int j = 0; j < B; j++) v[j] = (j+1)*i;
return v;
});
}
for(int j = 0; j < B; j++)
for(int i = 0; i < A; i++)
cout << sumarray[i].get()[j] << " ";
cout << endl;
}
以同样的方式编译 throw
terminate called after throwing an instance of 'std::future_error'
what(): No associated state
我使用 std::async 在 lambda 函数中返回向量的方式有问题吗?
以下代码有效。 注释掉的行是问题所在。 正如 JaredC 所说,问题是在内部循环中使用 get() 。 此外,从内存中为每个元素获取整个向量的效率会非常低,但这对我来说只是不好的做法。 y_futures 是未来双精度向量的向量。
for (size_t i = 0; i < parts; ++i) {
std::vector<double> temp = y_futures[i].get();
for (size_t j = 0; j < num_rows_; ++j) {
// y(j) = y_futures[i].get()[j];
y(j) += temp[j];
}
} ````
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.