簡體   English   中英

使用 std::async c++11 返回 std:vector

[英]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 函數中返回向量的方式有問題嗎?

您在sumarray的元素上多次調用get() 根據文檔

調用此方法后,valid() 為 false。

這意味着您不能像內部循環那樣多次調用get()

以下代碼有效。 注釋掉的行是問題所在。 正如 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM