在循环中调用boost io_service poll

时间:2014-06-12 17:43:41

标签: c++ boost boost-asio boost-thread

我目前正在尝试使用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()调用吗?

感谢。

1 个答案:

答案 0 :(得分:0)

以下是如何使用工作对象的演示: 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)
}

但是,您可能还需要查看 Developing Boost Asio Extensions ,因为这样您只需run()&#34;并且仍然交错你自己的(可能是非IO)任务