stdex Additional custom or not Standard C++ covered algorithms

Loading...
Searching...
No Matches
watchdog.hpp
1/*
2 SPDX-License-Identifier: MIT
3 Copyright © 2023-2024 Amebis
4*/
5
6#pragma once
7
8#include "compat.hpp"
9#include <chrono>
10#include <condition_variable>
11#include <functional>
12#include <mutex>
13#include <thread>
14
15 namespace stdex
16{
20 template <class _Clock, class _Duration = typename _Clock::duration>
21 class watchdog
22 {
23 public:
30 watchdog(_In_ _Duration timeout, _In_ std::function<void()> callback) :
31 m_phase(0),
32 m_quit(false),
33 m_timeout(timeout),
34 m_callback(callback),
35 m_thread([](_Inout_ watchdog& wd) { wd.run(); }, std::ref(*this))
36 {}
37
41 ~watchdog()
42 {
43 {
44 const std::lock_guard<std::mutex> lk(m_mutex);
45 m_quit = true;
46 }
47 m_cv.notify_one();
48 if (m_thread.joinable())
49 m_thread.join();
50 }
51
57 void reset()
58 {
59 {
60 const std::lock_guard<std::mutex> lk(m_mutex);
61 m_phase++;
62 }
63 m_cv.notify_one();
64 }
65
66 protected:
67 void run()
68 {
69 size_t phase;
70 for (;;) {
71 {
72 std::unique_lock<std::mutex> lk(m_mutex);
73 phase = m_phase;
74 if (m_cv.wait_for(lk, m_timeout, [&] {return m_quit || phase != m_phase; })) {
75 if (m_quit)
76 break;
77 // reset() called in time.
78 continue;
79 }
80 }
81 // Timeout
82 m_callback();
83 {
84 // Sleep until next reset().
85 std::unique_lock<std::mutex> lk(m_mutex);
86 m_cv.wait(lk, [&] {return m_quit || phase != m_phase; });
87 if (m_quit)
88 break;
89 }
90 }
91 }
92
93 protected:
94 size_t m_phase;
95 bool m_quit;
96 _Duration m_timeout;
97 std::function<void()> m_callback;
98 std::mutex m_mutex;
99 std::condition_variable m_cv;
100 std::thread m_thread;
101 };
102}
stdex::watchdog
Triggers callback if not reset frequently enough.
Definition watchdog.hpp:22
stdex::watchdog::watchdog
watchdog(_Duration timeout, std::function< void()> callback)
Starts the watchdog.
Definition watchdog.hpp:30
stdex::watchdog::m_phase
size_t m_phase
A counter we are incrementing to keep the watchdog happy.
Definition watchdog.hpp:94
stdex::watchdog::m_timeout
_Duration m_timeout
How long the watchdog is waiting for a reset.
Definition watchdog.hpp:96
stdex::watchdog::~watchdog
~watchdog()
Stops the watchdog.
Definition watchdog.hpp:41
stdex::watchdog::m_quit
bool m_quit
Quit the watchdog.
Definition watchdog.hpp:95
stdex::watchdog::reset
void reset()
Resets the watchdog.
Definition watchdog.hpp:57
stdex::watchdog::m_callback
std::function< void()> m_callback
The function watchdog calls on timeout.
Definition watchdog.hpp:97