Last active
November 13, 2019 13:18
-
-
Save estama/d0fb850a83f1751c627d5caf01be4e72 to your computer and use it in GitHub Desktop.
Basic parallel_for
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
| #include <algorithm> | |
| #include <future> | |
| #include <thread> | |
| template<typename randomIt, typename FN> | |
| void parallel_for(const randomIt start, const randomIt end, const int step, const FN &mapFun, const int threadCount = -1, const int granularity = 1, const int threadStart = 0) noexcept { | |
| int threadSize = threadCount; | |
| if (threadSize < 0) { | |
| const unsigned threadHint = std::thread::hardware_concurrency(); | |
| threadSize = threadHint == 0 ? 2 : threadHint; | |
| } | |
| const unsigned arraySize = (end - start) / step; | |
| threadSize = std::max(1, std::min(arraySize, threadSize - threadStart)); | |
| if ((threadSize <= 1) | (arraySize <= granularity)) { | |
| mapFun(start, end, threadStart); | |
| } else { | |
| const unsigned tmiddle = threadStart + threadSize / 2; | |
| const randomIt amiddle = start + (arraySize / 2) * step; | |
| auto t = std::async([&]() { parallel_for(amiddle, end, step, mapFun, threadStart + threadSize, granularity, tmiddle); }); | |
| parallel_for(start, amiddle, step, mapFun, tmiddle, granularity, threadStart); | |
| t.wait(); | |
| } | |
| } | |
| template<typename randomIt, typename FN> | |
| void parallel_for(const randomIt start, const randomIt end, const FN &mapFun, const int threadCount = -1, const int granularity = 1) noexcept { | |
| parallel_for(start, end, 1, mapFun, threadCount, granularity); | |
| } | |
| /* | |
| void example() { | |
| parallel_for(0, 10000, [&](const int start, const int end, const int threadId) { | |
| for (int i = start; i < end; i++) { | |
| // DOSTUFF | |
| } | |
| }); | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment