最近被问到怎么用C++11写watchdog,考虑了一会儿,答对了思路,但是没能写出来。于是去翻了下chatgpt,看了几眼后自己尝试写了下,代码如下,权当存档
#include <thread>
#include <atomic>
#include <iostream>
class WatchDog
{
public:
WatchDog(int count, int interval)
: m_count(count), m_interval(interval)
{
}
~WatchDog()
{
if (m_thread.joinable())
{
m_thread.join();
}
}
void start()
{
if (m_run)
{
return;
}
m_run = true;
m_thread = std::thread([this]()
{
int count = 0;
while (m_run)
{
std::this_thread::sleep_for(std::chrono::seconds(m_interval));
if (!m_reset)
{
++count;
if (count > m_count)
{
std::cerr << "error" << std::endl;
break;
}
}
else
{
count = 0;
m_reset = false;
}
}
});
}
void reset()
{
m_reset = true;
}
void stop()
{
m_run = false;
}
private:
std::atomic<bool> m_run = false;
std::thread m_thread;
int m_count;
int m_interval;
std::atomic<bool> m_reset = false;
};
int main()
{
WatchDog wd(10, 1);
wd.start();
int times = 0;
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
++times;
if (times == 5)
{
wd.reset();
}
else if (times == 20)
{
break;
}
}
wd.stop();
return 0;
}
而最近也在看《剑指offer》和有空的时候就刷下leetcode,后续估计会把从中学到的一些算法思路写一下。
就这样。