据我了解,我应该能够使用 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/