opynsim
Unofficial C++ Documentation
Loading...
Searching...
No Matches
paralellization_helpers.h
Go to the documentation of this file.
1#pragma once
2
4
5#include <concepts>
6#include <cstddef>
7#include <future>
8#include <span>
9#include <thread>
10#include <vector>
11
12namespace osc
13{
14 // perform a parallelized and "Chunked" ForEach, where each thread receives an
15 // independent chunk of data to process
16 //
17 // this is a poor-man's `std::execution::par_unseq`, because C++17's <execution>
18 // isn't fully integrated into MacOS
19 template<typename T, std::invocable<T&> UnaryFunction>
21 size_t min_chunk_size,
22 std::span<T> values,
24 {
25 const size_t chunk_size = max(min_chunk_size, values.size()/std::thread::hardware_concurrency());
26 const size_t num_tasks = values.size()/chunk_size;
27
28 if (num_tasks > 1) {
29 std::vector<std::future<void>> tasks;
30 tasks.reserve(num_tasks);
31
32 for (size_t i = 0; i < num_tasks-1; ++i) {
33 const size_t chunk_begin = i * chunk_size;
34 const size_t chunk_end = (i+1) * chunk_size;
35 tasks.push_back(std::async(std::launch::async, [values, mutator, chunk_begin, chunk_end]()
36 {
37 for (size_t j = chunk_begin; j < chunk_end; ++j) {
39 }
40 }));
41 }
42
43 // last worker must also handle the remainder
44 {
45 const size_t chunk_begin = (num_tasks-1) * chunk_size;
46 const size_t chunk_end = values.size();
47 tasks.push_back(std::async(std::launch::async, [values, mutator, chunk_begin, chunk_end]()
48 {
49 for (size_t i = chunk_begin; i < chunk_end; ++i) {
51 }
52 }));
53 }
54
55 for (std::future<void>& task : tasks) {
56 task.get();
57 }
58 }
59 else {
60 // chunks would be too small if parallelized: just do it sequentially
61 for (T& value : values) {
62 mutator(value);
63 }
64 }
65 }
66}
Definition custom_decoration_generator.h:5
constexpr auto max(Angle< Rep1, Units1 > x, Angle< Rep2, Units2 > y) -> std::common_type_t< decltype(x), decltype(y)>
Definition angle.h:283
void for_each_parallel_unsequenced(size_t min_chunk_size, std::span< T > values, UnaryFunction mutator)
Definition paralellization_helpers.h:20
constexpr U to(T &&value)
Definition conversion.h:56