And*_*ndy 3 c++ multithreading boost sleep
我每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)));
}
Run Code Online (Sandbox Code Playgroud)
在新线程中调用以下方法:
void HeartBeat::TimerStart ()
{
while (1)
{
cout << "heartbeat..." << endl;
boost::this_thread::sleep(boost::posix_time::seconds (TimerSeconds));
addHeartBeat();
}
}
Run Code Online (Sandbox Code Playgroud)
这会产生任何问题的心跳.但是我希望能够将睡眠定时器重置为零.是否有一种简单的方法可以做到这一点,或者我应该使用除此之外的其他方式
boost::this_thread::sleep
Run Code Online (Sandbox Code Playgroud)
为了我的睡眠?
操作系统:Redhat
IDE:Eclipse
代码语言:C++
我看过用了
m_pHBThread->interrupt();
Run Code Online (Sandbox Code Playgroud)
它似乎是我所追求的,所以谢谢你!
这听起来就像异步计时器那样.既然你已经使用了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 timer\n";
hb.reset();
sleep(15);
}
Run Code Online (Sandbox Code Playgroud)
测试运行:
~ $ ./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...
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1695 次 |
| 最近记录: |