Last active
May 17, 2021 11:44
-
-
Save SuperFola/981b3ecb601dcc6f469247551e302c60 to your computer and use it in GitHub Desktop.
A demonstration of how to add parallelism using only standard C++ 17
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <future> | |
#include <vector> | |
#include <array> | |
#include <numeric> // needed for the std::iota part of the example | |
using VecIt = std::vector<int>::iterator; | |
int task(std::size_t task_id, VecIt begin, std::size_t count) | |
{ | |
int sum = 0; | |
for (VecIt it = begin, end = begin + count; it != end; ++it) | |
sum += *it; | |
return sum; | |
} | |
int main() | |
{ | |
// create fake data: 0, 1, 2, ... 134 | |
std::vector<int> input_data(135); | |
std::iota(input_data.begin(), input_data.end(), 0); | |
// creating the workers | |
constexpr std::size_t WorkerCount = 4; | |
std::array<std::future<int>, WorkerCount> futures; | |
std::size_t data_size = input_data.size(); | |
std::size_t block_size = data_size / WorkerCount; | |
for (std::size_t i = 0; i < WorkerCount; ++i) | |
{ | |
// the range of data on which we shall work | |
std::size_t start = i * block_size, | |
count = (i + 1 != WorkerCount) ? (block_size) : (data_size - i * block_size); | |
futures[i] = std::async( | |
std::launch::async, | |
[i, start, count, &input_data](){ | |
return task(i, input_data.begin() + start, count); | |
} | |
); | |
} | |
// wait and harvest results | |
int total = 0; | |
for (std::size_t i = 0; i < WorkerCount; ++i) | |
total += futures[i].get(); | |
std::cout << "harvested: " << total << ", expected: " << (data_size * (data_size - 1) / 2) << "\n"; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment