-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrunner_agent.cpp
59 lines (44 loc) · 1.08 KB
/
runner_agent.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <atomic>
#include <chrono>
#include <thread>
#include <utility>
#include <fmt/printf.h>
#include <gsl/gsl_assert>
template <typename Agent> concept IsAgent = requires(Agent agent) {
{agent.doWork()};
};
template <typename Agent> requires IsAgent<Agent> class Runner {
public:
Runner(Agent &&agent) : m_agent(std::forward<Agent>(agent)) {}
constexpr void start() {
m_running = true;
m_thread = std::thread([&]() { run(); });
}
constexpr void run() {
while (m_running) {
m_agent.doWork();
}
}
constexpr void stop() {
m_running = false;
m_thread.join();
}
~Runner() { Expects(m_running == false); }
private:
Agent m_agent;
std::thread m_thread;
std::atomic<bool> m_running{false};
};
template <typename Agent> Runner(Agent &&)->Runner<Agent>;
class HelloWorldAgent {
public:
void doWork() noexcept { fmt::print("Hello, {}!\n", "Nanosecond"); }
};
int main() {
using namespace std::chrono_literals;
auto runner = Runner{HelloWorldAgent{}};
runner.start();
std::this_thread::sleep_for(2s);
runner.stop();
return 0;
}