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 を使用します。3 番目に、スレッドが 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 に答える