在循环中调用boost io_service poll

call boost io_service poll in a loop

本文关键字:service poll io boost 循环 调用      更新时间:2023-10-16

我目前正在尝试使用boost::asio从循环中手动更新我的程序的一部分,如下所示:

class A
{
   A::A() : m_io() {}
   A::update()
   {
     m_io.poll();
     //do other stuff
   }
   A::postSomething()
   {
     while(1)
     {
       m_io.post(...);
       sleep(1000);
     }
   }
}
void main()
{
  A a;
  boost::thread thr(boost::bind(&A::postSomething, &a));
  while(1)
  {
    a.update();
  }
}

如果我运行程序,没有post()被处理。但是,如果我像这样在类成员update()中添加m_io.reset():

A::update()
{
  m_io.poll();
  //do other stuff
  m_io.reset();
} 

这似乎有效,但我仍然想知道这样做是否正确??我是否冒着因为reset()而丢失post()调用的风险?

谢谢。

下面是如何使用工作对象的演示:Live On Coliru

#include <iostream>
#include <boost/asio.hpp>
#include <boost/optional.hpp>
#include <boost/thread.hpp>
class A
{
    using ios = boost::asio::io_service;
    ios                        m_io;
    boost::optional<ios::work> m_active;
  public:
    A() : m_io(), m_active(ios::work(m_io)) {}
    ~A() {
        m_active.reset();
        m_io.run(); // to completion
    }
    void update()
    {
        m_io.poll();
        //do other stuff
    }
    void postSomething()
    {
        int i = 0;
        while(m_active)
        {
            m_io.post([&]{std::cout<<"something" << ++i << "n";});
            boost::this_thread::sleep_for(boost::chrono::milliseconds(250));
        }
    }
};
int main()
{
    boost::thread thr;
    {
        A a;
        thr = boost::thread(boost::bind(&A::postSomething, &a));
        for (int i = 0; i < 300; ++i)
        {
            boost::this_thread::sleep_for(boost::chrono::milliseconds(5));
            a.update();
        }
    }
    thr.join(); // thread will not join unless A is destructed (m_active is cleared)
}

然而,你可能还想看看开发Boost Asio扩展,因为这将允许你"只run()",仍然交错你自己的(大概是非io)任务