简体   繁体   English

在 boost 线程中运行 boost asio io_service

[英]Running boost asio io_service in a boost thread

I'm using the boost daytime examples as a starter for a project that requires 2 way communication between machines and now need to launch the asio io_service in its own thread so I can pass data across seperatley.我正在使用 boost daytime 示例作为一个项目的启动器,该项目需要机器之间的 2 路通信,现在需要在自己的线程中启动 asio io_service 以便我可以跨 seperatley 传递数据。 Here is the basis of my code: http://www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime7/src.html这是我的代码的基础: http : //www.boost.org/doc/libs/1_35_0/doc/html/boost_asio/tutorial/tutdaytime7/src.html

It all works fine if I invoke the service in main with如果我在 main 中调用服务,一切正常

io_service.run()

However, if I try to create a thread group and launch there like so:但是,如果我尝试创建一个线程组并像这样在那里启动:

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

The code compiles and runs, the port numbers are quoted by cout correctly but it doesn't seem to open a listening port as the client gets a connection refused, although the server program seems to be ticking away awaiting connections.代码编译并运行,端口号由 cout 正确引用,但它似乎没有打开侦听端口,因为客户端连接被拒绝,尽管服务器程序似乎正在等待连接。

What is happening here please?请问这里发生了什么?

My guess is that your code will work, if you put tgroup.join_all();我的猜测是你的代码会起作用,如果你把tgroup.join_all(); before catch : catch前:

...
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 and server objects go out of scope here and get destroyed, possibly before thread from thread group even start running. io_service和服务器对象在这里超出范围并被破坏,可能在线程组中的线程甚至开始运行之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM