【问题标题】:boost::asio asynchronous timer as an interruptboost::asio 异步定时器作为中断
【发布时间】:2011-11-24 14:48:07
【问题描述】:

据我了解,我应该能够使用 boost:asio 异步计时器每隔 n 毫秒触发一次回调,而我的程序正在执行其他操作而无需线程。这个假设正确吗?

我将以下测试程序放在一起,它只打印处理程序消息,从不打印 rand() 值。我想要的是看到所有的浮点数在屏幕上向下滚动,然后每 250 毫秒就会出现一条处理程序消息。

代码如下:

#include <iostream>
#include <vector>
#include <cstdlib>

#include <boost/asio.hpp>
#include <boost/date_time.hpp>
#include <boost/thread.hpp>

boost::asio::io_service io_service;
boost::posix_time::time_duration interval(boost::posix_time::milliseconds(250));
boost::asio::deadline_timer timer(io_service,interval);

void handler(const boost::system::error_code& error);

void timer_init() {
   timer.expires_at(timer.expires_at()+interval);
   timer.async_wait(handler);
}

void handler(const boost::system::error_code& error) {
   static long count=0;
   std::cout << "in handler " << count++ << std::endl;
   std::cout.flush();
   timer_init();
}

int main(int argc, char **argv) {
   timer.async_wait(handler);
   io_service.run();

   std::vector<double> vec;
   for (long i=0; i<1000000000; i++) {
      double x=std::rand();
      std::cout << x << std::endl;
      std::cout.flush();
      vec.push_back(x);
   }
   return 0;
}

【问题讨论】:

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


    【解决方案1】:

    这个:

    io_service.run();
    

    是一个阻塞调用。的确,您可以使用 ASIO 在一个线程中异步发生多件事,但您不能让 ASIO 与未与 ASIO 集成的代码在同一线程中运行。这是一个经典的事件驱动模型,所有工作都是为了响应一些就绪通知(在您的情况下为计时器)而完成的。

    尝试将您的向量/rand 代码移动到一个函数并将该函数传递给 io_service::post(),然后它将在其 run() 方法的上下文中运行该代码。然后,当您调用 run() 时,这两件事都会发生(虽然不是真正同时发生,因为这需要线程)。

    【讨论】:

    • “您不能让 ASIO 与未与 ASIO 集成的代码在同一线程中运行”——这并不准确。可以将主应用程序循环与poll_one 调用交错。
    • 顺便说一句,如果他posts 整个函数,定时器处理程序不会被调用,直到函数结束。
    【解决方案2】:

    正如 John Zwinck 所提到的,io_service::run() 阻塞 - 这是一个主要的 asio 循环,用于调度完成处理程序。但是,您可以通过将io_service::poll_one 与循环交错来“手动”处理io_service 队列,而不是调用run

    for (long i=0; i<1000000000; i++) {
          double x=std::rand();
          std::cout << x << std::endl;
          std::cout.flush();
          vec.push_back(x);
          io_service.poll_one();
       }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多