]> git.stg.codes - stg.git/blob - projects/stargazer/eventloop.h
More std::jthread
[stg.git] / projects / stargazer / eventloop.h
1 #ifndef __EVENT_LOOP_H__
2 #define __EVENT_LOOP_H__
3
4 #include "actions.h"
5
6 #include <mutex>
7 #include <condition_variable>
8 #pragma GCC diagnostic push
9 #pragma GCC diagnostic ignored "-Wshadow"
10 #include <jthread.hpp>
11 #pragma GCC diagnostic pop
12
13 class EVENT_LOOP
14 {
15     public:
16         static EVENT_LOOP& instance();
17
18         bool Start();
19         bool Stop();
20
21         template <class ACTIVE_CLASS, typename DATA_TYPE>
22         void Enqueue(ACTIVE_CLASS & ac,
23                      typename ACTOR<ACTIVE_CLASS, DATA_TYPE>::TYPE a,
24                      DATA_TYPE d)
25         {
26             std::lock_guard lock(m_mutex);
27             // Add new action
28             m_list.Enqueue(ac, a, d);
29             // Signal about new action
30             m_cond.notify_all();
31         }
32
33     private:
34         std::jthread m_thread;
35         std::mutex m_mutex;
36         std::condition_variable m_cond;
37
38         ACTIONS_LIST m_list;
39
40         EVENT_LOOP() = default;
41
42         void Run(std::stop_token token);
43 };
44
45 #endif