提高deadline_timer问题 [英] boost deadline_timer issue
问题描述
这里有个测试类包装一个带有计时器的线程执行。
奇怪的是,如果截止时间为500毫秒它的工作原理,但如果我将它设置为1000毫秒事实并非如此。我在做什么错了?
Here follows the implementation of a test class wrapping a thread with a timer. The strange thing is that if the deadline is set to 500 milliseconds it works but if I set it to 1000 milliseconds it does not. What am I doing wrong?
#include "TestTimer.hpp"
#include "../SysMLmodel/Package1/Package1.hpp"
TestTimer::TestTimer(){
thread = boost::thread(boost::bind(&TestTimer::classifierBehavior,this));
timer = new boost::asio::deadline_timer(service,boost::posix_time::milliseconds(1000));
timer->async_wait(boost::bind(&TestTimer::timerBehavior, this));
};
TestTimer::~TestTimer(){
}
void TestTimer::classifierBehavior(){
service.run();
};
void TestTimer::timerBehavior(){
std::cout<<"timerBehavior\r";
timer->expires_at(timer->expires_at() + boost::posix_time::milliseconds(1000));
timer->async_wait(boost::bind(&TestTimer::timerBehavior,this));
}
更新1
我注意到,该方案stucks(或至少是标准输出在控制台中的许多秒钟,约30),那么很多timerBehavior字符串被打印出来在一起,如果他们被地方排队。
UPDATE 1 I have noticed that the program stucks (or at least the standard output in the console for many seconds, about 30) then a lot of "timerBehavior" strings are printed out together as if they have been queued somewhere.
推荐答案
您的程序可能有几个问题。从你显示什么,这很难说,如果定时器有一定几率触发前的程序停止。而且,你不刷新你的输出,使用std :: ENDL,如果你要刷新一个新行后的输出。第三,如果你的线程将运行的io_service.run()函数,它可能是该线程找到一个空的IO队列和运行()将立即返回。到prevent即,有一个工作类,将prevent此。这是我的例子,你从code,可能会按预期工作:
You program might have several problems. From what you have shown, it's hard to say, if the program stops before the timer had a chance to trigger. And, you do not flush your output, use std::endl, if you want to flush the output after a newline. Third, if your thread is going to run the io_service.run() function, it might be that the thread finds an empty io queue and run() will return immediately. To prevent that, there is a work class, that will prevent this. Here is my example, from you code, that might work as expected:
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include <iostream>
class TestTimer
{
public:
TestTimer()
: service()
, work( service )
, thread( boost::bind( &TestTimer::classifierBehavior,this ) )
, timer( service,boost::posix_time::milliseconds( 1000 ) )
{
timer.async_wait( boost::bind( &TestTimer::timerBehavior, this ) );
}
~TestTimer()
{
thread.join();
}
private:
void classifierBehavior()
{
service.run();
}
void timerBehavior() {
std::cout << "timerBehavior" << std::endl;
timer.expires_at( timer.expires_at() + boost::posix_time::milliseconds( 1000 ) );
timer.async_wait( boost::bind( &TestTimer::timerBehavior,this ) );
}
boost::asio::io_service service;
boost::asio::io_service::work work;
boost::thread thread;
boost::asio::deadline_timer timer;
};
int main()
{
TestTimer test;
}
这篇关于提高deadline_timer问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!