JustEnoughMod
Loading...
Searching...
No Matches
TaskPool.hpp
1#ifndef SCHED_TASKPOOL_HPP
2#define SCHED_TASKPOOL_HPP
3
4#include <core/Logger.hpp>
5#include <util/Queue.hpp>
6
7#include <utility>
8
9namespace JEM {
10 class TaskPool {
11 public:
12 TaskPool(unsigned int count = std::thread::hardware_concurrency()) {
13 getSystemLogger()->info("Creating {} thread runners", count);
14
15 for (unsigned int i = 0; i < count; ++i) {
16 m_pool.emplace_back(std::bind_front(&TaskPool::Runner, this), i + 1);
17 }
18 }
19
20 void push(std::function<void()> func) {
21 m_taskQueue.push(std::move(func));
22 }
23
24 ~TaskPool() {
25 getSystemLogger()->info("Destroying {} thread runners", m_pool.size());
26
27 for (auto &thread : m_pool) {
28 thread.request_stop();
29 }
30 m_cond.notify_all();
31 }
32
33 private:
34 std::vector<std::jthread> m_pool;
35 JEM::queue<std::function<void()>> m_taskQueue;
36
37 std::mutex m_mutex;
38 std::condition_variable m_cond;
39
40 void Runner(const std::stop_token token, int /*id*/) {
41 while (!token.stop_requested()) {
42 std::unique_lock<std::mutex> lock(m_mutex);
43
44 m_cond.wait(lock, [this, &token]() { return !m_taskQueue.empty() || token.stop_requested(); });
45
46 lock.unlock();
47 m_cond.notify_one();
48
49 if (!m_taskQueue.empty() && !token.stop_requested()) {
50 auto func = m_taskQueue.pop();
51 func();
52 }
53 }
54 }
55 };
56} // namespace JEM
57
58#endif
Definition TaskPool.hpp:10
Definition Queue.hpp:11
void func()
Definition group.cpp:13