3

下面是一个用计时器包装线程的测试类的实现。奇怪的是,如果最后期限设置为 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));
}

更新 1 我注意到程序卡住了(或者至少在控制台中的标准输出停留了很多秒,大约 30 秒)然后很多“timerBehavior”字符串被一起打印出来,就好像它们已经在某个地方排队一样。

4

1 回答 1

5

你的程序可能有几个问题。从您所展示的内容来看,很难说程序是否在计时器有机会触发之前停止。而且,如果您想在换行符之后刷新输出,请不要刷新输出,请使用 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;
}
于 2012-07-28T14:19:53.477 回答