在boost线程中运行boost asio io_service

3
我正在使用Boost Daytime示例作为需要两台机器之间进行双向通信的项目的起点,现在我需要在其自己的线程中启动asio io_service,以便我可以单独传递数据。这是我的代码基础:http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime7/src.html
如果我在main函数中调用服务,则一切都正常工作。
io_service.run()

然而,如果我尝试创建一个线程组并在那里启动,就像这样:
int main()
{
    boost::thread_group tgroup;
  try
  {
    boost::asio::io_service io_service;
    tcp_server server1(io_service);
    udp_server server2(io_service);

    tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));

     std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;

  }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

   tgroup.join_all();
  return 0;
}

代码编译和运行正常,cout正确引用了端口号,但似乎没有打开监听端口,因为客户端收到连接拒绝的信息,而服务器程序似乎正在等待连接。

请问这里发生了什么?

1个回答

2

我猜你的代码会在将catch之前加入tgroup.join_all();后工作:

...
try {
  boost::asio::io_service io_service;
  tcp_server server1(io_service);
  udp_server server2(io_service);

  tgroup.create_thread(boost::bind(&boost::asio::io_service::run, &io_service));

  std::cout << "Server running on TCP port " << tcpport << std::endl << "Server running on UDP port " << udpport << std::endl;
  tgroup.join_all();
}
...

在这里,io_service和服务器对象超出范围并被销毁,可能在线程组的线程甚至开始运行之前就被销毁了。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接