mercredi 29 juin 2016

Transfer ownership of boost::asio::socket stack variable

I'm writing a simple tcp socket server capable of handling multiple concurrent connections. The idea is that the main listening thread will do a blocking accept and offload socket handles to a worker thread (in a thread pool) to handle the communication asynchronously from there.

void server::run() {
  {
    io_service::work work(io_service);

    for (std::size_t i = 0; i < pool_size; i++)
      thread_pool.push_back(std::thread([&] { io_service.run(); }));

    boost::asio::io_service listener;
    boost::asio::ip::tcp::acceptor acceptor(listener, ip::tcp::endpoint(ip::tcp::v4(), port));

    while (listening) {
      boost::asio::ip::tcp::socket socket(listener);
      acceptor.accept(socket);
      io_service.post([&] {callback(std::move(socket));});
    }
  }

  for (ThreadPool::iterator it = thread_pool.begin(); it != thread_pool.end(); it++)
    it->join();
}

I'm creating socket on the stack because I don't want to have to repeatedly allocate memory inside the while(listening) loop.

The callback function callback has the following prototype:

void callback(boost::asio::socket socket);

It is my understanding that calling callback(std::move(socket)) will transfer ownership of socket to callback. However when I attempt to call socket.receive() from inside callback, I get a Bad file descriptor error, so I assume something is wrong here.

How can I transfer ownership of socket to the callback function, ideally without having to create sockets on the heap?

Aucun commentaire:

Enregistrer un commentaire