c++ - boost::asio 异步定时器作为中断

标签 c++ boost timer boost-asio interrupt

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

我整理了以下测试程序,它只打印处理程序消息,从不打印 rand() 值。我想要的是看到所有 float 在屏幕上向下滚动,然后每 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;
}

最佳答案

这个:

io_service.run();

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

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

关于c++ - boost::asio 异步定时器作为中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8258864/

相关文章:

c++ - Boost - 构建时关于取消引用指针的警告

c++ - 如何在 x86 和 x64 平台之间使用 boost::serialization

python - 如何使用线程来创建多个独立的可重用对象实例?

python - 如何在Python中的特定时间间隔后运行一个方法?

android - 在 Eclipse 中查看变量时 gdb 进程崩溃

c++ - 警告 : statement has no effect (C++)

c++ - 什么是 undefined reference /未解析的外部符号错误,我该如何解决?

c++ - 读取和解析 JSON 文件 C++ BOOST

c++ - C++ 中的 std::vector 与 std::array

c - 在 C 中实现定时事件