2014-11-24 93 views
0

我有一個要求,我的計時器必須根據2個條件進行重置,以先發生者爲準。如何重新啓動提升截止日期計時器

  1. 當計時器到期
  2. 當滿足特定條件(如內存達到某一限度)

我以下步驟:

boost::asio::io_service io; 
boost::asio::deadline_timer t(io, boost::posix_time::seconds(1)); 
boost::mutex mtx1; 

void run_io_service() 
{ 
    io.run(); 
} 

void print(const boost::system::error_code& /*e*/) 
{ 
    boost::mutex::scoped_lock lock(mtx1); 
    std::cout << "Hello, world!\n"; 
    t.expires_from_now(boost::posix_time::seconds(1)); 
    t.async_wait(print); 
    std::cout << "Print executed\n"; 
} 
int main() 
{ 
    t.async_wait(print); 
    boost::thread monitoring_thread = boost::thread(run_io_service); 
    boost::this_thread::sleep(boost::posix_time::seconds(2)); 
    t.cancel(); 
    std::cout << "Resetting Timer\n"; 
    t.async_wait(print); 
    boost::this_thread::sleep(boost::posix_time::seconds(2)); 
    t.cancel(); 
    io.stop(); 
    monitoring_thread.join(); 
    return 0; 
} 

此代碼工作正常,直到時間計時器尚未取消。 一旦定時器被取消,定時器不能以預期的方式工作,它根本不起作用。

我在做什麼錯?

+0

你能否澄清你期望這個程序輸出什麼,它實際輸出什麼,以及爲什麼你認爲這意味着定時器不工作? – 2014-11-24 08:10:12

回答

2

第一個問題是如果出現錯誤(例如被取消),處理程序仍將被調用,則需要檢查錯誤代碼。

void print(const boost::system::error_code& e) 
{ 
    if(e) return; // we were cancelled 
    // actual error code for cancelled is boost::asio::error::operation_aborted 

    boost::mutex::scoped_lock lock(mtx1); 
    std::cout << "Hello, world!\n"; 
    t.expires_from_now(boost::posix_time::seconds(1)); 
    t.async_wait(print); 
    std::cout << "Print executed\n"; 
} 

其次,當你取消計時器,離開了io_service對象沒有任何工作,這意味着run_io_service線程將終止,讓你沒有服務。整個節目過程中保持服務活着,給它一個工作對象在主開始:

int main() { 
    boost::asio::io_service::work work(io); 
    ... 

和..如sehe提到的,你是不是安全處理的定時器(或std ::法院) 。當你打印重置信息並重置定時器時,你應該鎖定mtx1,否則墨菲法則規定它可能在處理程序正在運行並且弄亂了事情的時刻發生。

+0

這是現貨。 +1 – sehe 2014-11-24 08:24:22

2

您需要設置新的過期時間。

事實上,您不必在此事件中明確取消,因爲設置新的期望會隱式取消任何待處理的異步等待。

請記住deadline_timer對象本身並不是線程安全的,因此您需要保持計時器突變同步。

+0

謝謝。處理錯誤幫助。 那麼,每次我們需要重置計時器時,我們不需要停止io服務嗎?在相同的定時器上使用async_wait會重置它? – garima721 2014-11-24 11:34:09

+0

不,是的。你可以隨時查看文檔。 (順便提一下,'io_service'是線程安全的) – sehe 2014-11-24 11:52:39

+0

非常感謝。這解決了我的問題。 – garima721 2014-11-25 02:48:03