我想在C++ 11中實現一個小的看門狗定時器類,它應該在過期時調用一些代碼。在C++中實現看門狗定時器11
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));
}
}
然而,這個線程循環似乎有點髒我,std::this_thread::sleep_for
是不準確的(它休眠至少指定的數量,這意味着它可以超過1毫秒),是否有更好的方法來實現此功能?
而是使用條件變量並等待它發送信號的某個時間。 –
我不明白,爲什麼你不只是'std :: this_thread :: sleep_for(std :: chrono :: milliseconds(_interval));'? –
另外,你的'Start'方法可以啓動多個線程,在檢查'_running'並設置它之間有四行。應該原子地做它http://en.cppreference.com/w/cpp/atomic/atomic_flag_test_and_set 例如:'if(_running.test_and_set(_running))' –