下面是用计时器包装线程的测试类的实现。
奇怪的是,如果截止时间设置为 500 毫秒,它可以工作,但如果我将其设置为 1000 毫秒,它就不起作用。我究竟做错了什么?
#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));
}
UPDATE 1我注意到程序卡住了(或者至少控制台中的标准输出持续了很多秒,大约 30 秒),然后很多“timerBehavior”字符串一起打印出来,就好像它们已在某个地方排队一样。
您的程序可能有几个问题。从您所显示的情况来看,很难说程序是否在计时器有机会触发之前停止。而且,如果您想在换行符后刷新输出,请不要刷新输出,请使用 std::endl 。第三,如果您的线程要运行 io_service.run() 函数,则该线程可能会发现一个空的 io 队列,并且 run() 将立即返回。为了防止这种情况发生,有一个工人阶级可以防止这种情况发生。这是我的示例,来自您的代码,可能会按预期工作:
#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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)