我可以使用Boost Signals2和Threads在C ++中创建一个软件看门狗定时器线程吗? [英] Can I create a software watchdog timer thread in C++ using Boost Signals2 and Threads?

查看:228
本文介绍了我可以使用Boost Signals2和Threads在C ++中创建一个软件看门狗定时器线程吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在当前的单线程应用程序中从其他人的库运行函数Foo。大多数时候,我打电话给Foo,它真的很快,有时,我打电话给Foo,它需要永远。我不是一个耐心的男人,如果Foo会永远,我想停止执行Foo,而不是用这些参数调用。

I am running function Foo from somebody else's library in a single-threaded application currently. Most of the time, I make a call to Foo and it's really quick, some times, I make a call to Foo and it takes forever. I am not a patient man, if Foo is going to take forever, I want to stop execution of Foo and not call it with those arguments.

什么是最好的方法以受控的方式调用Foo(我当前的环境是POSIX / C ++),这样我可以在一定秒数后停止执行。我觉得在这里做的正确的事情是创建第二个线程调用Foo,而在我的主线程中,我创建一个定时器函数,最终将信号第二线程,如果它用完了时间。

What is the best way to call Foo in a controlled manner (my current environment is POSIX/C++) such that I can stop execution after a certain number of seconds. I feel like the right thing to do here is to create a second thread to call Foo, while in my main thread I create a timer function that will eventually signal the second thread if it runs out of time.

有没有另一个更适合的模型(和解决方案)?

Is there another, more apt model (and solution)? If not, would Boost's Signals2 library and Threads do the trick?

推荐答案

你可以在第二个线程调用Foo超时。例如:

You can call Foo on a second thread with a timeout. For example:

#include <boost/date_time.hpp> 
#include <boost/thread/thread.hpp>

boost::posix_time::time_duration timeout = boost::posix_time::milliseconds(500);
boost::thread thrd(&Foo);

if (thrd.timed_join(timeout))
{
  //finished
}
else
{
  //Not finished;
}

这篇关于我可以使用Boost Signals2和Threads在C ++中创建一个软件看门狗定时器线程吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆