bstamour已经展示了规范/更简单的方法。但是,如果迭代速度很关键和/或结果类型必须是:std::vector<double>
std::vector<double> results(A.size());
std::vector<std::future<void>> futures;
futures.reserve(A.size()); // second allocation
auto store_result = [](double& result, double x, double y)
{ result = square_add(x, y); };
// non-capturing lambda might give better performance, test it
// launch the async operations
for(int i = 0; i != A.size(); ++i)
futures.emplace_back(std::async(store_result, std::ref(results[i]), A[i], 3));
// wait for all results to become ready
for(auto& e : futures)
e.get();
// results are in the `results` vector
for(auto const& e : results)
std::cout << e << std::endl;
完整示例:
#include <iostream>
#include <thread>
#include <future>
#include <vector>
using namespace std;
double square_add(double x, double y) { return x*x+y; }
int main() {
vector<double> A = {1,2,3,4,5};
// Single evaluation
std::cout << "single evaluation" << std::endl;
auto single_result = std::async(square_add,A[2],3);
cout << "Evaluating a single index " << single_result.get() << endl;
// Blocking map
std::cout << "\n\n";
std::cout << "blocking map" << std::endl;
for(auto &x:A) {
auto blocking_result = std::async(square_add,x,3);
cout << "Evaluating a single index " << blocking_result.get() << endl;
}
// Non-blocking map?
// bstamour's solution:
std::cout << "\n\n";
std::cout << "bstamour's solution" << std::endl;
{
std::vector<std::future<double>> future_doubles;
future_doubles.reserve(A.size());
for (auto& x : A) {
// Might block, but also might not.
future_doubles.push_back(std::async(square_add, x, 3));
}
// Now block on all of them one at a time.
for (auto& f_d : future_doubles) {
std::cout << f_d.get() << std::endl;
}
}
// DyP's solution
std::cout << "\n\n";
std::cout << "DyP's solution" << std::endl;
{
std::vector<double> results(A.size());
std::vector<std::future<void>> futures;
futures.reserve(A.size()); // second allocation
auto store_result = [](double& result, double x, double y) { result = square_add(x, y); };
for(int i = 0; i != A.size(); ++i)
futures.emplace_back( std::async(store_result, std::ref(results[i]), A[i], 3) );
for(auto& e : futures)
e.get();
for(auto const& e : results)
std::cout << e << std::endl;
}
return 0;
}