简体   繁体   中英

Returning std:vector with std::async c++11

I have a problem returning std::vector using std::future and std::async. Why does

#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;

}

compilled with g++ -std=c++11 -pthread work as expected printing

0 1 2 3 4 5 6 7 8 9

but

#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;

}

compiled in the same way throw

terminate called after throwing an instance of 'std::future_error'
  what():  No associated state

Is there something wrong with the way I am returning the vector in the lambda function with std::async?

You are calling get() multiple times on the elements of sumarray . According to the documentation :

valid() is false after a call to this method.

This means that you can't call get() more than once as your inner loop does.

The following code works. The commented out line was the problem. As JaredC said, the issue was using get() in the inner loop. Also it would have been horribly inefficient to fetch the entire vector from memory for every element, but that was just bad practice on my part. y_futures is a vector of future vectors of doubles.

 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];
    }
  }    ````

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM