c++ - io_service 在线程内运行

标签 c++ boost-asio boost-thread

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

#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;
}

最佳答案

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

[...] the programmer must ensure that the destructor is never executed while the thread is still joinable.

如果定义了 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...

关于c++ - io_service 在线程内运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26510075/

相关文章:

c++ - 为什么在使用 boost::asio 时每个连接都需要 strand?

c++ - boost::thread::join() 崩溃试图引用销毁的 thread_info

C++ 错误 C2065 : undeclared identifier

c++ - 字符串转wstring,编码问题

c++ - eof 错误读取文本文件片段并写入 boost.asio 套接字

c++ - Boost 线程串行运行,而不是并行运行

c++ - 使用互斥量的正确方法

c++ - 使用类成员函数作为回调?

c++ - 是否不需要默认生成的构造函数来构造所有基类?

c++ - 当线程安全容器上有大量计算和推送/弹出时,来自 boost asio 的同步或异步更好吗?