I'm trying to implement a small watchdog timer class in C++ 11 that should call some code when it expires.
Watchdog.h:
#pragma once
#include <thread>
#include <atomic>
class Watchdog
{
public:
Watchdog();
Watchdog(unsigned int milliseconds, std::function<void()> callback);
~Watchdog();
void Start(unsigned int milliseconds, std::function<void()> callback);
void Stop();
void Pet();
private:
unsigned int _interval;
std::atomic<unsigned int> _timer;
std::atomic<bool> _running;
std::thread _thread;
std::function<void()> _callback;
void Loop();
};
Watchdog.cpp:
#include "Watchdog.h"
Watchdog::Watchdog() :
_interval(0),
_timer(0),
_running(false)
{
}
Watchdog::Watchdog(unsigned int milliseconds, std::function<void()> callback)
{
Start(milliseconds, callback);
}
Watchdog::~Watchdog()
{
}
void Watchdog::Start(unsigned int milliseconds, std::function<void()> callback)
{
_interval = milliseconds;
_timer = 0;
_callback = callback;
_running = true;
_thread = std::thread(&Watchdog::Loop, this);
}
void Watchdog::Stop()
{
_running = false;
_thread.join();
}
void Watchdog::Pet()
{
_timer = 0;
}
void Watchdog::Loop()
{
while (_running)
{
_timer++;
if (_timer >= _interval)
{
_running = false;
_callback();
}
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
However, this thread loop seems a bit dirty to me, and std::this_thread::sleep_for
is not accurate (it sleeps for at least the specified amount, meaning it can be longer than 1 ms), is there a better way to achieve this functionality?