summaryrefslogtreecommitdiff
path: root/src/thread_utils.h
diff options
context:
space:
mode:
authorMikaël Capelle <capelle.mikael@gmail.com>2020-05-24 14:39:39 +0200
committerMikaël Capelle <capelle.mikael@gmail.com>2020-05-24 14:39:39 +0200
commitff4fbbdc5fa5ada01bd5bc3d8f8004279d7cc6b8 (patch)
tree10ed90d03a7942a45513f04c87f12a122e847926 /src/thread_utils.h
parent73248d9e4036ad6b9494f678efbc97e919ebfbcf (diff)
Switch from ThreadPool to a simpler thread map for containers.
Diffstat (limited to 'src/thread_utils.h')
-rw-r--r--src/thread_utils.h55
1 files changed, 55 insertions, 0 deletions
diff --git a/src/thread_utils.h b/src/thread_utils.h
new file mode 100644
index 00000000..fe096a36
--- /dev/null
+++ b/src/thread_utils.h
@@ -0,0 +1,55 @@
+#ifndef MO2_THREAD_UTILS_H
+#define MO2_THREAD_UTILS_H
+
+#include <mutex>
+#include <thread>
+
+namespace MOShared {
+
+/**
+ * @brief Apply the given callable to each element between the two given iterators
+ * in a parallel way.
+ *
+ * The callable should be independent, or properly synchronized, and the source of
+ * the range should not change during this call.
+ *
+ * @param start Beginning of the range.
+ * @param end End of the range.
+ * @param callable Callable to apply to every element of the range. See std::invoke
+ * requirements. Must be copiable.
+ * @param nThreads Number of threads to use.
+ *
+ */
+template <class It, class Callable>
+void parallelMap(It begin, It end, Callable callable, std::size_t nThreads) {
+ std::vector<std::thread> threads(nThreads);
+
+ std::mutex m;
+ for (auto &thread: threads) {
+ thread = std::thread([&m, &begin, end, callable]() {
+ while (true) {
+ decltype(begin) it;
+ {
+ std::scoped_lock lock(m);
+ if (begin == end) {
+ break;
+ }
+ it = begin++;
+ }
+ if (it != end) {
+ std::invoke(callable, *it);
+ }
+ }
+ });
+ }
+
+
+ // Join everything:
+ for (auto& t : threads) {
+ t.join();
+ }
+}
+
+}
+
+#endif