]> git.stg.codes - stg.git/blob - projects/stargazer/eventloop.cpp
More std::jthread
[stg.git] / projects / stargazer / eventloop.cpp
1 #include "stg/common.h"
2 #include "eventloop.h"
3
4 #include <csignal>
5 #include <cerrno>
6 #include <cstring>
7
8 EVENT_LOOP& EVENT_LOOP::instance()
9 {
10     static EVENT_LOOP el;
11     return el;
12 }
13
14 bool EVENT_LOOP::Start()
15 {
16 m_thread = std::jthread([this](auto token){ Run(std::move(token)); });
17 return false;
18 }
19
20 bool EVENT_LOOP::Stop()
21 {
22 m_thread.request_stop();
23 // Wake up thread
24 m_cond.notify_all();
25 m_thread.join();
26 return false;
27 }
28
29 void EVENT_LOOP::Run(std::stop_token token)
30 {
31 sigset_t signalSet;
32 sigfillset(&signalSet);
33 pthread_sigmask(SIG_BLOCK, &signalSet, NULL);
34
35 printfd(__FILE__, "EVENT_LOOP::Runner - Before start\n");
36 while (!token.stop_requested())
37     {
38     // Create new empty actions list
39     ACTIONS_LIST local;
40         {
41         std::unique_lock lock(m_mutex);
42         // Check for any actions...
43         // ... and sleep until new actions added
44         printfd(__FILE__, "EVENT_LOOP::Runner - Sleeping until new actions arrived\n");
45         m_cond.wait(lock);
46         // Check for running after wake up
47         if (token.stop_requested())
48             break; // Don't process any actions if stopping
49         if (!m_list.empty())
50             local.swap(m_list);
51         }
52     // Fast swap with current
53     m_list.swap(local);
54     // Invoke all current actions
55     printfd(__FILE__, "EVENT_LOOP::Runner - Invoke %d actions\n", local.size());
56     local.InvokeAll();
57     }
58 printfd(__FILE__, "EVENT_LOOP::Runner - Before stop\n");
59 }