我需要心跳信号每10秒左右。为了实现这一点,我用下面的构造函数生成了一个类:
HeartBeat::HeartBeat (int Seconds, MessageQueue * MsgQueue)
{
TimerSeconds = Seconds;
pQueue = MsgQueue;
isRunning = true;
assert(!m_pHBThread);
m_pHBThread = shared_ptr<thread>(new thread(boost::bind(&HeartBeat::TimerStart,this)));
}
在新线程中调用以下方法:
void HeartBeat::TimerStart ()
{
while (1)
{
cout << "heartbeat..." << endl;
boost::this_thread::sleep(boost::posix_time::seconds (TimerSeconds));
addHeartBeat();
}
}
这将产生一个没有任何问题的心跳。然而,我希望能够重置睡眠计时器回到零。是否有一个简单的方法来做到这一点,或者我应该使用其他的
boost::this_thread::sleep
为我的睡眠?
操作系统:Redhat
Eclipse IDE:代码语言:c++
<标题>编辑:
我考虑过使用
m_pHBThread->interrupt();
这似乎是我所追求的,所以谢谢你!
标题>这听起来就像异步计时器所做的。既然您已经在使用boost了,也许从长远来看,使用boost自己的异步计时器是有意义的?
#include <iostream>
#include <boost/thread.hpp>
#include <boost/date_time.hpp>
#include <boost/asio.hpp>
boost::posix_time::ptime now()
{
return boost::posix_time::microsec_clock::local_time();
}
class HeartBeat {
boost::asio::io_service ios;
boost::asio::deadline_timer timer;
boost::posix_time::time_duration TimerSeconds;
boost::thread thread;
public:
HeartBeat(int Seconds) : ios(), timer(ios),
TimerSeconds(boost::posix_time::seconds(Seconds))
{
reset(); // has to start timer before starting the thread
thread = boost::thread(boost::bind(&boost::asio::io_service::run,
&ios));
}
~HeartBeat() {
ios.stop();
thread.join();
}
void reset()
{
timer.expires_from_now(TimerSeconds);
timer.async_wait(boost::bind(&HeartBeat::TimerExpired,
this, boost::asio::placeholders::error));
}
void TimerExpired(const boost::system::error_code& ec)
{
if (ec == boost::asio::error::operation_aborted) {
std::cout << "[" << now() << "] timer was reset" << std::endl;
} else {
std::cout << "[" << now() << "] heartbeat..." << std::endl;
reset();
}
}
};
int main()
{
std::cout << "[" << now() << "] starting up.n";
HeartBeat hb(10);
sleep(15);
std::cout << "[" << now() << "] Resetting the timern";
hb.reset();
sleep(15);
}
测试运行:
~ $ ./test
[2011-Sep-07 12:08:17.348625] starting up.
[2011-Sep-07 12:08:27.348944] heartbeat...
[2011-Sep-07 12:08:32.349002] Resetting the timer
[2011-Sep-07 12:08:32.349108] timer was reset
[2011-Sep-07 12:08:42.349160] heartbeat...
也许您可以使用interrupt()来完成此操作。
嗯,每次心跳都启动一个新线程是不太有效的…我会用一个线程来代替,并在其中添加一个sleep。如果你需要改变心跳频率,那么你可以终止当前线程,用新的睡眠时间启动一个新的线程。你可以使用boost::线程和中断信号。
编辑:查看这里关于boost线程的信息:boost线程管理
如果你想将时间重置为零并立即执行你的代码,那么在boost::thread_interrupted…
EDIT2:我没有正确地查看代码,我认为每次心跳启动一个新线程的常见错误就在那里…对不起,是我的错……我想我不喜欢的事实,线程的名称是:TimerStart()
无论如何,我认为使用interrupt()并捕获它应该工作,如果你需要立即执行心跳