C++: splitting a sum across std::async tasks
Data parallelism divides a large data set into independent parts that are processed at the same time. std::async launches a function and returns a std::future, a handle for the eventual result. Calling get waits for the task and returns its value or rethrows its exception.
C++
#include <functional>
#include <future>
#include <iostream>
#include <numeric>
#include <vector>
long long sum_range(const std::vector<int>& v, std::size_t from, std::size_t to) {
return std::accumulate(v.begin() + from, v.begin() + to, 0LL);
}
int main() {
std::vector<int> data(1000);
std::iota(data.begin(), data.end(), 1);
auto first = std::async(std::launch::async, sum_range, std::cref(data), 0, 500);
auto second = std::async(std::launch::async, sum_range, std::cref(data), 500, 1000);
long long total = first.get() + second.get();
std::cout << "sum 1..1000 = " << total << "\n";
}