Created
August 26, 2021 12:19
-
-
Save commander-trashdin/054ac534170610774a9ff36ad10cc85d to your computer and use it in GitHub Desktop.
Parallel "reduce"
This file contains hidden or 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
| 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