Ember
A C++ 20 'game engine' built with SDL3 with wide platform support.
thread_pool.h
Go to the documentation of this file.
1 #pragma once
2 #include "engine_sys.h"
3 #include "logging_sys.h"
4 
14 class ThreadManager final: public EngineManager {
15 public:
16  explicit ThreadManager(size_t threads);
17  ~ThreadManager() override;
18 
19  template <class F, class... Args>
20  auto enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))>;
21 
22  bool initialize() override;
23 
24  void update(double delta_time) override;
25 
26  void shutdown() override;
27 
28 private:
29  std::vector<std::thread> _workers;
30  std::queue<std::function<void()>> tasks;
31 
32  std::mutex _queue_mutex;
33  std::condition_variable condition;
34  bool is_running = false;
35 };
36 
37 
38 template <class F, class... Args>
39 auto ThreadManager::enqueue(F&& f, Args&&... args) -> std::future<decltype(f(args...))> {
40 #if defined(SDL_PLATFORM_EMSCRIPTEN)
41  LOG_INFO("ThreadPool not supported on Web builds.");
42 #else
43 
44  using return_type = decltype(f(args...));
45 
46  auto task = std::make_shared<std::packaged_task<return_type()>>(
47  std::bind(std::forward<F>(f), std::forward<Args>(args)...)
48  );
49 
50  std::future<return_type> res = task->get_future();
51 
52  {
53  std::unique_lock lock(_queue_mutex);
54  if (!is_running) {
55  throw std::runtime_error("ThreadPool isn't running, cannot enqueue new tasks.");
56  }
57 
58  tasks.emplace([task]() { (*task)(); });
59  }
60 
61  condition.notify_one();
62  return res;
63 #endif
64 
65 }
Base class for all engine systems.
Definition: engine_sys.h:10
ThreadManager class.
Definition: thread_pool.h:14
void update(double delta_time) override
Definition: thread_pool.cpp:42
~ThreadManager() override
bool initialize() override
Definition: thread_pool.cpp:36
void shutdown() override
Definition: thread_pool.cpp:45
ThreadManager(size_t threads)
Definition: thread_pool.cpp:4
auto enqueue(F &&f, Args &&... args) -> std::future< decltype(f(args...))>
Definition: thread_pool.h:39
#define LOG_INFO(...)
INFO logging.
Definition: logging_sys.h:75