Joedb 10.4.6
The Journal-Only Embedded Database
Loading...
Searching...
No Matches
Keep_Alive_Thread.h
Go to the documentation of this file.
1#ifndef joedb_Keep_Alive_Thread_declared
2#define joedb_Keep_Alive_Thread_declared
3
5#include "joedb/Thread_Safe.h"
6
7#include <thread>
8#include <condition_variable>
9
10namespace joedb
11{
13 {
14 friend class Keep_Alive_Thread;
15
16 private:
17 virtual Thread_Safe<Channel&> &get_channel() = 0;
18 virtual void locked_ping(Lock<Channel&> &lock) = 0;
19
20 public:
21 void ping()
22 {
23 Lock<Channel&> lock(get_channel());
24 locked_ping(lock);
25 }
26
27 virtual ~Ping_Client() = default;
28 };
29
31 {
32 private:
33 Ping_Client &client;
34 const std::chrono::milliseconds interval;
35
36 bool thread_must_stop;
37 bool stopped;
38 std::thread thread;
39 std::condition_variable condition;
40
41 void keep_alive()
42 {
43 try
44 {
45 Lock<Channel&> lock(client.get_channel());
46
47 while (!thread_must_stop)
48 {
49 condition.wait_for(lock, interval);
50
51 if (thread_must_stop)
52 break;
53
54 client.locked_ping(lock);
55 }
56 }
57 catch(...)
58 {
59 }
60 }
61
62 public:
63 Keep_Alive_Thread(Ping_Client &client, std::chrono::milliseconds interval):
64 client(client),
65 interval(interval),
66 thread_must_stop(false),
67 stopped(true)
68 {
69 }
70
71 void start()
72 {
73 if (stopped && interval.count() > 0)
74 {
75 thread_must_stop = false;
76 thread = std::thread([this](){keep_alive();});
77 stopped = false;
78 }
79 }
80
81 void stop()
82 {
83 if (!stopped)
84 {
85 {
86 Lock<Channel&> lock(client.get_channel());
87 thread_must_stop = true;
88 }
89 condition.notify_one();
90 if (thread.joinable())
91 thread.join();
92 stopped = true;
93 }
94 }
95
97 {
98 if (!stopped)
99 try {stop();} catch (...) {}
100 }
101 };
102}
103
104#endif
Keep_Alive_Thread(Ping_Client &client, std::chrono::milliseconds interval)
virtual ~Ping_Client()=default