Skip to content

Instantly share code, notes, and snippets.

@commander-trashdin
Created August 26, 2021 12:19
Show Gist options
  • Select an option

  • Save commander-trashdin/054ac534170610774a9ff36ad10cc85d to your computer and use it in GitHub Desktop.

Select an option

Save commander-trashdin/054ac534170610774a9ff36ad10cc85d to your computer and use it in GitHub Desktop.
Parallel "reduce"
template <class RandomAccessIterator, class T, class Func>
T Reduce(RandomAccessIterator first, RandomAccessIterator last, const T& initial_value, Func func) {
std::vector<std::thread> workers;
std::atomic<T> cur_value(initial_value);
auto dist = std::distance(first, last);
auto seglen = dist / 7;
auto rem = dist % 7;
if (seglen != 0) {
for (size_t i = 0; i < 7; i++) {
workers.emplace_back([&first, &last, &i, &func, &cur_value, &seglen] {
auto it = first + i * seglen;
while (it != std::min(last, first + (i + 1) * seglen)) {
cur_value = func(cur_value, *it++);
}
});
}
}
workers.emplace_back([&first, &last, &rem, &func, &cur_value, &seglen] {
auto it = last - rem;
while (it != last) {
cur_value = func(cur_value, *it++);
}
});
for (auto& worker : workers) {
worker.join();
}
return cur_value;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment