co_ecs 0.9.0
Cobalt ECS
Loading...
Searching...
No Matches
parallel_for.hpp
Go to the documentation of this file.
1#pragma once
2
5
6namespace co_ecs {
7
12template<typename R>
13void parallel_for(R&& range, auto&& func) {
15 auto num_workers = thread_pool.num_workers();
16 auto work_size = std::ranges::distance(range);
17 auto batch_size = work_size / num_workers;
18
19 if (batch_size < 1) {
20 // fast path for small range
21 std::ranges::for_each(range, func);
22 } else {
23 // alias a subrange type that is our batch of work
24 using batch_t = decltype(std::ranges::subrange(range.begin(), range.end()));
25
26 std::vector<batch_t, detail::temp_allocator<batch_t>> batches;
27
28 // prepare batches
29 {
30 batches.reserve(num_workers);
31 auto b = range.begin();
32 auto e = b;
33 for (auto i = 0; i < num_workers; i++) {
34 auto e = (i < num_workers - 1) ? std::next(b, batch_size) : range.end();
35 batches.emplace_back(std::ranges::subrange(b, e));
36 b = e;
37 }
38 }
39
40 // submit batches
41 {
42 task_t* parent = nullptr;
43 for (auto& batch : batches) {
44 auto* task = thread_pool.submit([&batch, &func]() { std::ranges::for_each(batch, func); }, parent);
45 if (!parent) {
46 parent = task;
47 }
48 }
49 thread_pool.wait(parent);
50 }
51 }
52}
53
54} // namespace co_ecs
Represents a task that can be executed, monitored for completion, and linked to a parent task.
Definition task.hpp:10
Generic thread pool implementation.
Definition thread_pool.hpp:17
task_t * submit(auto &&func, task_t *parent=nullptr)
Submit a task to a thread pool.
Definition thread_pool.hpp:276
std::size_t num_workers() const noexcept
Return the number of workers.
Definition thread_pool.hpp:296
static thread_pool & get()
Get thread pool instance.
Definition thread_pool.hpp:264
void wait(task_t *task)
Wait a task to complete.
Definition thread_pool.hpp:282
Definition archetype.hpp:11
void parallel_for(R &&range, auto &&func)
Parallelize func over elements in range.
Definition parallel_for.hpp:13