7#include <condition_variable>
9namespace sysio {
namespace vm {
18 template <
typename TimeUnits>
19 explicit watchdog(
const TimeUnits& duration) : _duration(duration) {}
27 return guard(_duration,
static_cast<F&&
>(callback));
33 guard(
const guard&) =
delete;
34 guard& operator=(
const guard&) =
delete;
36 template <
typename TimeUnits,
typename F>
37 guard(
const TimeUnits& duration, F&& callback)
38 : _callback(static_cast<F&&>(callback)),
41 _start(
std::chrono::steady_clock::now()) {
43 _timer = std::thread(&guard::runner,
this);
47 auto _lock = std::unique_lock(_mutex);
60 auto _lock = std::unique_lock(_mutex);
62 _cond.wait_until(_lock, _start + _duration, [&]() {
return _run_state != running; });
63 if (_run_state == running) {
64 _run_state = interrupted;
68 enum state_t { running, interrupted, stopped };
69 using time_point_type = std::chrono::time_point<std::chrono::steady_clock>;
70 using duration_type = std::chrono::steady_clock::duration;
73 std::condition_variable _cond;
74 std::function<void()> _callback;
76 duration_type _duration;
77 time_point_type _start;
79 std::chrono::steady_clock::duration _duration;
null_watchdog scoped_run(F &&)
guard scoped_run(F &&callback)
watchdog(const TimeUnits &duration)