Tuesday, 1 October 2013

How do I asynchronously map values onto a function with threading?

How do I asynchronously map values onto a function with threading?

I'm trying to learn how to execute "embarrassingly" parallel tasks in
C++11. A common pattern I come across is get the result of a function when
evaluated over a range of values, similar to calling python's
multiprocessing.Pool.map. I've written a minimal example that shows what I
know how to do, namely call a single process and wait for the result. How
can I "map" this call asynchronously and wait until all values are done?
Ideally, I'd like the results in a vector of the same length and order as
the original.
#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
auto single_result = std::async(square_add,A[2],3);
cout << "Evaluating a single index " << single_result.get() << endl;
// Blocking map
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?
return 0;
}
Note: to get this code to compile with gcc I need the -pthreads flag.

No comments:

Post a Comment