Boost logo

Boost Users :

Subject: Re: [Boost-users] [Asio] io_service destructor never completes
From: Ragnar Cederlund (ragnar.cederlund_at_[hidden])
Date: 2010-07-06 10:00:11


On Fri, Jul 2, 2010 at 5:55 PM, Ragnar Cederlund <ragnar.cederlund...>wrote:

>
> I'm having trouble with the io_service destructor never completing.
>
[...]

I've finally been able to reproduce the hang on my own machine and have a
small example that exhibits this problem (built using Visual Studio 2005 in
debug mode):

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

using namespace boost::asio;

class ConnectCommand;
typedef boost::shared_ptr<ConnectCommand> ConnectCommandPtr;

class ConnectCommand {
public:
  ConnectCommand(io_service &io_service)
    : m_IoService(io_service)
    , m_Socket(io_service)
  {}

  void Execute() {
    std::cout << "Attempting connection" << std::endl;

    ip::tcp::endpoint ep(ip::address_v4::from_string("127.0.0.1"), 7780);

    m_Socket.async_connect(ep,
      boost::bind(&ConnectCommand::Handle_Connect,
      this, placeholders::error));

    // Stop without waiting for the result
    m_IoService.stop();
  }

private:
  void Handle_Connect(boost::system::error_code &e)
  {
    std::cout << "Connect returned: " << e << "." << std::endl;
  }

  boost::asio::io_service &m_IoService;
  boost::asio::ip::tcp::socket m_Socket;
};

class AsioHang {
public:

  void Run() {
    m_ConnectCommand.reset(new ConnectCommand(m_IoService));
    m_ConnectCommand->Execute();

    m_IoService.run();
  }

private:
  ConnectCommandPtr m_ConnectCommand; // destroyed after io_service object
  boost::asio::io_service m_IoService;
};

int _tmain(int argc, _TCHAR* argv[])
{
  {
    AsioHang hang;
    hang.Run();

    std::cout << "After Run()" << std::endl;
  }
  return 0;
}

In this example, there is a flaw in that the ConnectCommand is destroyed
after the io_service object, but the ConnectCommand has a reference to the
io_service.

I would have expected this to lead to a crash or similar and this is indeed
the case if I attach a debugger to the program and step through it. But if I
just run the program without the debugger attached, the io_service
destructor just never completes.

I believe that a variation of the error in the code above is what caused the
problems for me and I assume that this should be written off as more or less
undefined behavior caused by badly managed object lifetimes.

Thank you all who responded and thank you Sergei for pointing out that there
is a specific asio mailing list.

Cheers,
Ragnar



Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net