2016-06-07 153 views
1

我需要能够在失效时间后测试函数被调用。在这个失败后,我写了一个小MCE,演示了测试的要点。它不返回处理程序就返回。steady_timer没有触发

取消注释下面的行是否有一个处理程序过期?导致它回显1到控制台,这意味着有一个未到期的处理程序。

按照documentation

The handler will be called when:

  • The timer has expired.
  • The timer was cancelled, in which case the handler is passed the error code boost::asio::error::operation_aborted.

所以我觉得我至少应该得到“处理程序”显示在屏幕上时,该行是注释。

担心如果您在sleep_foryield行之后移动它,仍然有一个处理程序处于活动状态。

为什么我的计时器没有启动?

MCE:

#include <boost/asio.hpp> 
#include <boost/asio/steady_timer.hpp> 
#include <iostream> 
#include <thread> 

void handler(const boost::system::error_code& error) 
{ 
    std::cout << "handler." << std::endl; 
    if (!error) 
    { 
     std::cout << "Timer expired." << std::endl; 
    } 
} 

int main(int argc, char* argv[]) 
{ 
    boost::asio::io_service io_service; 

    // Construct a timer without setting an expiry time. 
    boost::asio::steady_timer timer(io_service); 

    // expire immediately 
    timer.expires_from_now(std::chrono::seconds(0)); 

    // Wait for the timer to expire. 
    timer.async_wait(handler); 

    // is there a handler to expire? 
    // std::cout << "Expiry : " << timer.expires_from_now(std::chrono::seconds(1)) << std::endl; 

    // added to allow the timer to expire 
    std::this_thread::sleep_for(std::chrono::seconds(2)); 
    std::this_thread::yield(); 
} 

回答

1

问题

您正在使用的wait异步变种,而无需调用io_service.run();

This call is required because operating system-specific functions have to take over control. Remember that it is the I/O service in the I/O service object which implements asynchronous operations based on operating system-specific functions.

解决方案

int main(int argc, char* argv[]) 
{ 
    boost::asio::io_service io_service; 

    // Construct a timer without setting an expiry time. 
    boost::asio::steady_timer timer(io_service); 

    // expire immediately 
    timer.expires_from_now(std::chrono::seconds(0)); 

    // Wait for the timer to expire. 
    timer.async_wait(handler); 

    io_service.run(); 
} 
+0

好的。这工作。如果boost站点上的示例代码显示了这一点,这将有所帮助。然而,在计时器开始之后不得不启动'io_service',至少可以说是尴尬的。每次我重置计时器时,是否需要调用'run()'?我是否需要每次“停止”或“重置”服务?我还没有为此创建单元测试,但知识将有所帮助。 –

+0

看看这个[教程](http://theboostcpplibraries.com/boost.asio-io-services-and-io-objects)。我总是重置,然后在重置计时器后运行'io_service',但我不确定是否有解决方法。如果你不能在主线程中运行'io_service',那么你总是可以在后台线程中运行它。 –