boost deadline_timer issue

你离开我真会死。 提交于 2019-12-13 13:41:48

问题


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));
}

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.


回答1:


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;
}


来源:https://stackoverflow.com/questions/11700566/boost-deadline-timer-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!