boost deadline_timer issue

2019-07-07 01:07发布

问题:

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