co_ecs 0.9.0
Cobalt ECS
Loading...
Searching...
No Matches
task.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <array>
4#include <atomic>
5#include <functional>
6
7namespace co_ecs {
8
10class task_t {
11public:
13 task_t() = default;
14
18 task_t(auto&& func, task_t* parent = nullptr) : _func(std::forward<decltype(func)>(func)), _parent(parent) {
19 _unfinishedTasks.store(1, std::memory_order::relaxed);
20 if (_parent) {
21 _parent->_unfinishedTasks.fetch_add(1, std::memory_order::relaxed);
22 }
23 }
24
26 void execute() {
27 _func();
28 finish();
29 }
30
33 bool is_completed() const noexcept {
34 return _unfinishedTasks.load(std::memory_order::relaxed) == 0;
35 }
36
39 task_t* parent() const noexcept {
40 return _parent;
41 }
42
43private:
44 void finish() {
45 _unfinishedTasks.fetch_sub(1, std::memory_order::relaxed);
46
47 if (is_completed() && _parent) {
48 _parent->finish();
49 }
50 }
51
52 std::function<void()> _func{};
53 task_t* _parent{};
54 std::atomic<uint16_t> _unfinishedTasks;
55};
56
59class task_pool {
60public:
62 constexpr static std::size_t max_tasks = 4096;
63
68 static task_t* allocate(auto&& func, task_t* parent = nullptr) {
69 auto& task = _tasks_array[_task_counter++ & (max_tasks - 1)];
70 task.~task_t();
71 new (&task) task_t(std::forward<decltype(func)>(func), parent);
72 return &task;
73 }
74
75private:
76 static inline thread_local std::size_t _task_counter;
77 static inline thread_local std::array<task_t, max_tasks> _tasks_array;
78};
79
80} // namespace co_ecs
Manages a pool of tasks, allocated from a circular array. Tasks are reused instead of being deallocat...
Definition task.hpp:59
static constexpr std::size_t max_tasks
Maximum number of tasks that can exist at any given time per worker.
Definition task.hpp:62
static task_t * allocate(auto &&func, task_t *parent=nullptr)
Allocates a task with the specified function and parent, placing it in a circular buffer.
Definition task.hpp:68
Represents a task that can be executed, monitored for completion, and linked to a parent task.
Definition task.hpp:10
task_t(auto &&func, task_t *parent=nullptr)
Constructs a task from a callable function and optionally links it to a parent task.
Definition task.hpp:18
task_t * parent() const noexcept
Retrieves the parent task if it exists.
Definition task.hpp:39
void execute()
Executes the task's function and marks it as completed.
Definition task.hpp:26
task_t()=default
Constructs an empty task.
bool is_completed() const noexcept
Checks if the task has been completed.
Definition task.hpp:33
Definition archetype.hpp:11
STL namespace.