-
Notifications
You must be signed in to change notification settings - Fork 0
/
PeriodicCallback.hpp
executable file
·114 lines (96 loc) · 2.38 KB
/
PeriodicCallback.hpp
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <unistd.h>
#include <chrono>
#include <future>
#include <functional>
class PeriodicCallback
{
public:
PeriodicCallback(
std::size_t interval_us = 1000000,
std::function<void(void)> func = NULL,
std::string prefix = "TPI: ",
std::string suffix = "\n")
:_execute(false) ,
_tic(0) ,
_interval_us(interval_us) ,
_func(func) ,
_prefix(prefix) ,
_suffix(suffix) ,
_time(std::chrono::high_resolution_clock::now())
{}
~PeriodicCallback() {
if( _execute.load(std::memory_order_acquire) ) {
stop();
};
}
void stop() {
_execute.store(false, std::memory_order_release);
if( _thd.joinable() )
_thd.join();
}
void start() {
if( _execute.load(std::memory_order_acquire) ) {
stop();
};
_execute.store(true, std::memory_order_release);
_thd = std::thread([this]() {
while (_execute.load(std::memory_order_acquire)) {
_time = std::chrono::high_resolution_clock::now();
if (_func) {
_func();
} else {
print();
}
resetTics();
const std::size_t sleep_us = _interval_us - getCurrentIntervallDuration<std::chrono::microseconds>();
if (sleep_us > 0) {
std::this_thread::sleep_for(std::chrono::microseconds(sleep_us));
} else {
std::cerr << "Warning: Interval to short\n";
}
}
});
}
bool isRunning() const noexcept {
return ( _execute.load(std::memory_order_acquire) && _thd.joinable() );
}
void setIntervalFunction(std::function<void(void)> func = NULL) {
_func = func;
}
void tic() {
++_tic;
}
void untic() {
--_tic;
}
void resetTics() {
_tic = 0;
}
void callUserFunction() {
_func();
}
std::size_t getTics() {
return _tic;
}
std::size_t getIntervallDuration() {
return _interval_us;
}
template<typename T>
std::size_t getCurrentIntervallDuration() {
const auto elapsed = std::chrono::high_resolution_clock::now() - _time;
return std::chrono::duration_cast<T>(elapsed).count();
}
private:
void print() {
std::cout << _prefix << getTics() << _suffix;
}
std::atomic<bool> _execute;
std::size_t _tic;
std::size_t _interval_us;
std::function<void(void)> _func;
std::string _prefix;
std::string _suffix;
std::chrono::high_resolution_clock::time_point _time;
std::thread _thd;
};