| 40 | */ |
| 41 | template <class It, class Callable> |
| 42 | void parallelMap(It begin, It end, Callable callable, std::size_t nThreads) |
| 43 | { |
| 44 | std::mutex m; |
| 45 | std::vector<std::thread> threads(nThreads); |
| 46 | |
| 47 | // Create the thread: |
| 48 | // - The mutex is only used to fetch/increment the iterator. |
| 49 | // - The callable is copied in each thread to avoid conflicts. |
| 50 | for (auto& thread : threads) { |
| 51 | thread = startSafeThread([&m, &begin, end, callable]() { |
| 52 | while (true) { |
| 53 | decltype(begin) it; |
| 54 | { |
| 55 | std::scoped_lock lock(m); |
| 56 | if (begin == end) { |
| 57 | break; |
| 58 | } |
| 59 | it = begin++; |
| 60 | } |
| 61 | if (it != end) { |
| 62 | std::invoke(callable, *it); |
| 63 | } |
| 64 | } |
| 65 | }); |
| 66 | } |
| 67 | |
| 68 | // Join everything: |
| 69 | for (auto& t : threads) { |
| 70 | t.join(); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | } // namespace MOShared |
| 75 |
no test coverage detected