Search code examples
c++multithreadingboostboost-asioboost-thread

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. Here is the basis of my code: 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

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.

What is happening here please?


Solution

  • My guess is that your code will work, if you put tgroup.join_all(); before 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.