我想达到的目标是:
在接收模式下运行radio并检查传入的包。一秒钟一次,如定时器中断,执行并切换到发送模式,发送一个包,然后返回到接收模式。
现在我有以下代码:

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(boost::bind(sendSyncToDevices, boost::asio::placeholders::error, &t));

    io.run();
}

void sendSyncToDevices(const boost::system::error_code& ,
    boost::asio::deadline_timer* t)
{
  DoSomething();
  t->expires_at(t->expires_at() + boost::posix_time::seconds(1));
  t->async_wait(boost::bind(sendSyncToDevices, boost::asio::placeholders::error, t));


}

但是io.run()是一个阻塞调用。有人能告诉我如何添加额外的while(1)循环来检查收音机上的消息吗?
谢谢!

最佳答案

你也可以在类似的帖子里得到答案
How do I perform a nonblocking read using asio?
他们讨论了一种使读/写调用不阻塞的方法。
或者,
在应用程序代码上执行while(1)可能不是等待事件或I/O的最佳方式。您还可以尝试在这些文件描述符上使用select()轮询样式(更多是C样式的编程)。Select()本质上是一个poll()函数,比while(1)和一次又一次地读取文件要好得多。
希望这有帮助。

关于c++ - 主程序中的Boost Timer中断,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19031357/

10-12 07:35
查看更多