gpt4 book ai didi

C++11看门狗类,测试应用不想退出

转载 作者:行者123 更新时间:2023-11-30 03:33:36 28 4
gpt4 key购买 nike

我正在使用在线 C++11 编译器,链接在这里:cpp.sh (C++ 外壳)。

在我当前的项目中,我想要一个看门狗类,以便能够以某种方式检查线程或 FSM(例如)的状态。

经过一些工作(我不是 C++11 高手),我终于得到了下面的代码,编译正常。
我也做了一些基本/琐碎的测试,但似乎测试程序不想退出
它显示“程序正在运行”,(强制)退出的唯一方法是点击“停止”按钮...:(

好吧,我的问题:我做错了什么?
非常感谢您提供的任何想法和建议。

这是完整代码,包括我的测试应用:

Watchdog (as MCVE):

#include <thread>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <iostream>

using namespace std::chrono;

class Watchdog
{
public:
Watchdog();
~Watchdog();
void Start(unsigned int milliseconds, std::function<void()> callback = 0);
void Stop();
void Pet();

private:
unsigned int m_interval;
std::atomic<bool> m_running;
std::thread m_thread;
std::function<void()> m_callback;
std::mutex m_mutex;
steady_clock::time_point m_lastPetTime;
std::condition_variable m_stopCondition;
void Loop();
};

Watchdog::Watchdog()
{
m_running = false;
}

Watchdog::~Watchdog()
{
Stop();
}

void Watchdog::Start(unsigned int milliseconds, std::function<void()> callback)
{
std::unique_lock<std::mutex> locker(m_mutex);
if(m_running == false)
{
m_lastPetTime = steady_clock::now();
m_interval = milliseconds;
m_callback = callback;
m_running = true;
m_thread = std::thread(&Watchdog::Loop, this);
}
}

void Watchdog::Stop()
{
std::unique_lock<std::mutex> locker(m_mutex);
if(m_running == true)
{
m_running = false;
m_stopCondition.notify_all();
m_thread.join();
}
}

void Watchdog::Pet()
{
std::unique_lock<std::mutex> locker(m_mutex);
m_lastPetTime = steady_clock::now();
m_stopCondition.notify_all();
}

void Watchdog::Loop()
{
std::unique_lock<std::mutex> locker(m_mutex);
while(m_running == true)
{
if(m_stopCondition.wait_for(locker, milliseconds(m_interval)) == std::cv_status::timeout)
{
if(m_callback != nullptr)
m_callback();
}
}
}

int main(int argc, char *argv[])
{
Watchdog wdog;

wdog.Start(3000, [] { std::cout << " WDOG TRIGGERED!!! "; });
for(auto i = 0; i < 10; i++)
{
std::cout << "[+]";
wdog.Pet();
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}

-

最佳答案

你在这里造成了僵局。

void Watchdog::Stop()
{
std::unique_lock<std::mutex> locker(m_mutex);
if(m_running == true)
{
m_running = false;
m_stopCondition.notify_all();
m_thread.join();
^ ~~~~~~~~~~~~~~
m_mutex is locked; m_thread cannot continue execution
}
}

一些额外的建议:使用简单的 if 条件,不要与 truefalse 进行比较。

关于C++11看门狗类,测试应用不想退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42733379/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com