Joedb 10.3.2
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 if (interval.count() > 0)
70 {
71 stopped = false;
72 thread = std::thread([this](){keep_alive();});
73 }
74 }
75
76 void stop()
77 {
78 if (!stopped)
79 {
80 {
81 Lock<Channel&> lock(client.get_channel());
82 thread_must_stop = true;
83 }
84 condition.notify_one();
85 if (thread.joinable())
86 thread.join();
87 stopped = true;
88 }
89 }
90
92 {
93 if (!stopped)
94 try {stop();} catch (...) {}
95 }
96 };
97}
98
99#endif
Keep_Alive_Thread(Ping_Client &client, std::chrono::milliseconds interval)
virtual ~Ping_Client()=default