boost::asio::async_read 100% CPU usage on simple example

Viewed 2640

In boost::asio standard examples after async_accept() the socket object is moving to the session object (which handles all async_read() calls) by initializing it as following:

std::make_shared<session>(std::move(socket_))->start();

And when constructing a session it's moving again (isn't it reduntantly?):

session(tcp::socket socket)
  : socket_(std::move(socket))

Then reading from a client is done as following:

boost::asio::async_read(socket_, ...

And all goes well. But when I trying to make async_read() not from the session object but directly from the async_accept() and use it's socket object, CPU is raising to 100% immediately after client connects. Why?

#include <boost/asio.hpp>
using boost::asio::ip::tcp;

class Server
{
public:
  Server(boost::asio::io_service& io_service,
         const tcp::endpoint& endpoint)    
    : acceptor_(io_service, endpoint),
      socket_(io_service)
  {
    do_accept();
  }

private:
  void do_accept()
  {
    acceptor_.async_accept(socket_,
       [this](boost::system::error_code ec)
       {
         if (!ec) {
           char* buf = new char[5];
           boost::asio::async_read(socket_,
              boost::asio::buffer(buf, 5),
              [this, buf](boost::system::error_code ec, std::size_t)
              {
                if (!ec) {
                  std::cout.write(buf, 5);
                  std::cout << std::endl;
                }
                delete[] buf;
              });
         }
         do_accept();
       });
  }

  tcp::acceptor acceptor_;
  tcp::socket socket_;
};

int main(int argc, char* argv[])
{
  int port = 22222;
  boost::asio::io_service io_service;
  tcp::endpoint endpoint(tcp::v4(), port);
  new Server(io_service, endpoint);
  io_service.run();
}

Boost 1.49

EDIT

Thanks for the answers! I ended up by moving socket_ before using it:

tcp::socket *socket = new tcp::socket(std::move(socket_));

Also the same problem is discussed at Repeated std::move on an boost::asio socket object in C++11

2 Answers
Related