C ++:定时回调后的WHILE循环阻止回调?

时间:2013-11-06 09:09:38

标签: c++ loops boost timer boost-asio

我正在使用from boost建议的解决方案进行定时回调,可以找到here。我正在使用它与其他方法并行运行定时回调。但是当我在设置回调后执行循环时,回调停止:

//this is the main cpp file

void print(const boost::system::error_code& /*e*/)
{
  std::cout << "Hello, world!\n";
}

int main(int argc, char** argv)
{
        boost::asio::io_service io;
        boost::asio::deadline_timer t(io, boost::posix_time::seconds(1));
        t.async_wait(print);
        io.run();

        ....some part later I then call a function with while(){} loop inside....
        eng.Loopfunction();

调用Loopfunction()后,定时回调不再起作用。你知道如何克服这个问题吗?

感谢。

1 个答案:

答案 0 :(得分:1)

  

定时回调不再起作用

它只被调用一次吗?

根据代码:

  1. io.run()阻止主线程
  2. print被调用一次
  3. io.run()取消阻止主线程
  4. eng.Loopfunction被称为
  5. 它必须如何运作。请注意,deadline_timer仅被调用一次。如果您希望每秒调用一次计时器,则需要在deadline_timer::async_wait结束时调用print,如下所示:

    boost::asio::io_service io;
    deadline_timer t(io);
    
    void print(const boost::system::error_code& /*e*/)
    {
      std::cout << "Hello, world!\n";
    
      // call this function again in 1 second
      t.expires_from_now( boost::posix_time::seconds(1) );
      t.async_wait(print);
    }
    
    int main(int argc, char** argv)
    {
        t.expires_from_now( boost::posix_time::seconds(1) );
        t.async_wait(print);
        io.run();
    
相关问题