io_service在线程内运行

时间:2014-10-22 14:35:27

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

为什么在这个简单的类中,如果我直接使用 io.run(),则会调用该函数,否则如果要求运行到其他线程,则不会调用print?

#include <iostream>
#include <boost/thread.hpp>
#include <boost/asio.hpp>

using namespace std;

class test
{
  public:
    test()
    {
      io.post(boost::bind(&test::print, this));
      //io.run();
      t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
    }

    void print()
    {
      cout << "test..." << endl;
    }

  private:
    boost::thread t;
    boost::asio::io_service io;
};

int main()
{
  test();
  return 0;
}

2 个答案:

答案 0 :(得分:1)

io_service :: run()将完成所有未完成的任务,并在完成后返回。如果你不打电话,它什么都不做。如果您这样做:

boost::asio::io_service::work work(io);

另一个线程将为您执行此操作并运行,直到您以某种方式停止它。

答案 1 :(得分:1)

在允许io_service完全运行之前,线程对象正在被销毁。 thread析构函数documentation表示:

  

[...]程序员必须确保在线程仍可连接时永远不会执行析构函数。

如果定义了BOOST_THREAD_PROVIDES_THREAD_DESTRUCTOR_CALLS_TERMINATE_IF_JOINABLE,程序将在线程析构函数调用std::terminate()时中止。


如果io_service应该运行完成,那么考虑加入Test的析构函数中的线程。以下是demonstrates在线程完成时同步的完整示例:

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread.hpp>

class test
{
public:
  test()
  {
    io.post(boost::bind(&test::print, this));
    t = boost::thread(boost::bind(&boost::asio::io_service::run, &io));
  }

  ~test()
  {
    if (t.joinable())
      t.join();  
  }

  void print()
  {
    std::cout << "test..." << std::endl;
  }

private:
  boost::thread t;
  boost::asio::io_service io;
};

int main()
{
  test();
  return 0;
}

输出:

test...
相关问题