]> git.stg.codes - stg.git/blob - projects/stargazer/async_pool.h
Use std::lock_guard instead of STG_LOCKER.
[stg.git] / projects / stargazer / async_pool.h
1 #pragma once
2
3 #include <functional>
4 #include <deque>
5 #include <mutex>
6 #include <condition_variable>
7 #pragma GCC diagnostic push
8 #pragma GCC diagnostic ignored "-Wshadow"
9 #include <jthread.hpp>
10 #pragma GCC diagnostic pop
11 #include <jthread.hpp>
12
13 namespace STG
14 {
15
16 class AsyncPool
17 {
18     public:
19         AsyncPool() = default;
20
21         void start();
22         void stop();
23
24         template <typename F>
25         void enqueue(F&& f)
26         {
27             {
28                 std::lock_guard lock(m_mutex);
29                 m_tasks.emplace_back(std::forward<F>(f));
30             }
31             m_cond.notify_all();
32         }
33
34     private:
35         using Task = std::function<void ()>;
36         using Queue = std::deque<Task>;
37
38         std::mutex m_mutex;
39         std::condition_variable m_cond;
40         Queue m_tasks;
41         std::jthread m_thread;
42
43         void run(std::stop_token token) noexcept;
44 };
45
46 namespace AsyncPoolST
47 {
48
49 AsyncPool& instance();
50
51 inline
52 void start() { instance().start(); }
53 inline
54 void stop() { instance().stop(); }
55
56 template <typename F>
57 inline
58 void enqueue(F&& f) { instance().enqueue(std::forward<F>(f)); }
59
60 };
61
62 }