libfly  6.2.2
C++20 utility library for Linux, macOS, and Windows
task_manager.hpp
1 #pragma once
2 
3 #include "fly/task/types.hpp"
4 #include "fly/types/concurrency/concurrent_queue.hpp"
5 
6 #include <atomic>
7 #include <chrono>
8 #include <future>
9 #include <memory>
10 #include <mutex>
11 #include <vector>
12 
13 namespace fly::task {
14 
15 class TaskRunner;
16 
29 class TaskManager : public std::enable_shared_from_this<TaskManager>
30 {
31  friend class TaskRunner;
32 
33 public:
41  static std::shared_ptr<TaskManager> create(std::uint32_t thread_count);
42 
48  bool start();
49 
61  bool stop();
62 
63 private:
68  struct TaskHolder
69  {
70  TaskLocation m_location;
71  std::weak_ptr<TaskRunner> m_weak_task_runner;
72  std::chrono::steady_clock::time_point m_schedule;
73  Task m_task;
74  };
75 
81  explicit TaskManager(std::uint32_t thread_count) noexcept;
82 
90  void
91  post_task(TaskLocation &&location, std::weak_ptr<TaskRunner> weak_task_runner, Task &&task);
92 
101  void post_task_with_delay(
102  TaskLocation &&location,
103  std::weak_ptr<TaskRunner> weak_task_runner,
104  std::chrono::milliseconds delay,
105  Task &&task);
106 
110  void worker_thread();
111 
115  void timer_thread();
116 
118 
119  std::mutex m_delayed_tasks_mutex;
120  std::vector<TaskHolder> m_delayed_tasks;
121 
122  std::atomic_bool m_keep_running;
123 
124  std::vector<std::future<void>> m_futures;
125 
126  std::uint32_t m_thread_count;
127 };
128 
129 } // namespace fly::task
Definition: task_manager.hpp:30
bool stop()
Definition: task_manager.cpp:63
static std::shared_ptr< TaskManager > create(std::uint32_t thread_count)
Definition: task_manager.cpp:16
bool start()
Definition: task_manager.cpp:39
Definition: task_runner.hpp:113
Definition: types.hpp:17