2012-07-28 67 views
2

下面是一個用定時器封裝線程的測試類的實現。 奇怪的是,如果截止日期設置爲500毫秒,它可以工作,但如果我將其設置爲1000毫秒,則不會。我究竟做錯了什麼?boost deadline_timer issue

#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 我已經注意到,程序stucks(或至少標準輸出在控制檯許多秒,約30),那麼大量的「timerBehavior」字符串一起打印出來,如果他們已經在某個地方排隊了。

+0

你應該確保,你的服務沒有失去工作。沒有任何東西阻止線程先啓動並運行service.run()一次。然後在線程失效後,TestTimer c'tor的第二行被執行。 – 2012-07-28 11:49:07

+0

我應該怎麼做? – Sindico 2012-07-28 12:00:21

+0

@Torsten:我已更新了我的問題,並提供了更多詳細信息。我使用Eclipse與gcc – Sindico 2012-07-28 12:44:20

回答

4

您的程序可能有幾個問題。從你所顯示的,很難說,如果程序在計時器有機會觸發之前停止。而且,如果要在換行符後刷新輸出,則不會刷新輸出,而使用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; 
} 
+0

+1不錯的完整答案 – 2012-07-28 16:56:30

相關問題