Loading...
Searching...
No Matches
watchdog.hpp
/*
SPDX-License-Identifier: MIT
Copyright © 2023 Amebis
*/
#pragma once
#include "compat.hpp"
#include <chrono>
#include <condition_variable>
#include <functional>
#include <mutex>
#include <thread>
namespace stdex
{
template <class _Clock, class _Duration = typename _Clock::duration>
class watchdog
{
public:
watchdog(_In_ _Duration timeout, _In_ std::function<void()> callback) :
m_phase(0),
m_quit(false),
m_timeout(timeout),
m_callback(callback),
m_thread([](_Inout_ watchdog& wd) { wd.run(); }, std::ref(*this))
{}
~watchdog()
{
{
const std::lock_guard<std::mutex> lk(m_mutex);
m_quit = true;
}
m_cv.notify_one();
if (m_thread.joinable())
m_thread.join();
}
void reset()
{
{
const std::lock_guard<std::mutex> lk(m_mutex);
m_phase++;
}
m_cv.notify_one();
}
protected:
void run()
{
for (;;) {
std::unique_lock<std::mutex> lk(m_mutex);
auto phase = m_phase;
if (m_cv.wait_for(lk, m_timeout, [&] {return m_quit || phase != m_phase; })) {
if (m_quit)
break;
}
else {
m_callback();
break;
}
}
}
protected:
size_t m_phase;
bool m_quit;
_Duration m_timeout;
std::function<void()> m_callback;
std::mutex m_mutex;
std::condition_variable m_cv;
std::thread m_thread;
};
}
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:84
stdex::watchdog::m_timeout
_Duration m_timeout
How long the watchdog is waiting for a reset.
Definition watchdog.hpp:86
stdex::watchdog::~watchdog
~watchdog()
Stops the watchdog.
Definition watchdog.hpp:41
stdex::watchdog::m_quit
bool m_quit
Quit the watchdog.
Definition watchdog.hpp:85
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:87