Aurus
Aurus

Reputation: 705

Boost::Asio Threaded Server Asynchroun Problem. Nothing happen

I´m making a Server with the BoostLib, and so i am using the asio lib.

I made an Server class.

Server::Server(unsigned short port)
 : m_IOService(),
   m_Socket(m_IOService),
   m_Endpoint(boost::asio::ip::tcp::v4(), port),
   m_Acceptor(m_IOService)
{
 m_Port = port;

 m_Acceptor.open(m_Endpoint.protocol());
 m_Acceptor.bind(m_Endpoint);
}

And the Start Function:

void Server::Run()
{
 // Threading
 //////////////////////////////////////////////////////
   std::vector<boost::shared_ptr<boost::thread> > threads;
   for (std::size_t i = 0; i < THREAD_POOL_SIZE; ++i)
   {
  boost::shared_ptr<boost::thread> thread(new boost::thread(
     boost::bind(&boost::asio::io_service::run, &m_IOService)));
  threads.push_back(thread);
   }

   // Wait for all threads in the pool to exit.
   for (std::size_t i = 0; i < threads.size(); ++i)
  threads[i]->join();



 // Begin Client accepting
 //////////////////////////////////////////////////////

 m_Acceptor.listen();
 m_Acceptor.async_accept(
  m_FreeClient->GetSocket(),
  boost::bind(&Server::OnConnection, this, boost::asio::placeholders::error));
}

m_FreeClient is a Pointer to the Client Class.

GetSocket Defination: `boost::asio::ip::tcp::socket& GetSocket();´

I compiled & started this Code, and connected with a little TestClient. Connection is there, but Server::OnConnection never will be called. I debugged, and set a breakpoint, but it never breaks there.

So what is wrong. THREAD_POOL_SIZE is 25.

Upvotes: 0

Views: 461

Answers (2)

Steve Townsend
Steve Townsend

Reputation: 54148

Perhaps this code is not the full version but it's not clear why you waiting for all your threads to exit (using join) before opening up the socket. I would think you need to move this:

   // Wait for all threads in the pool to exit.
   for (std::size_t i = 0; i < threads.size(); ++i)
  threads[i]->join();

to be the last thing you do before process exit, or at least after this:

 // Begin Client accepting
 //////////////////////////////////////////////////////

 m_Acceptor.listen();
 m_Acceptor.async_accept(
  m_FreeClient->GetSocket(),
  boost::bind(&Server::OnConnection, this, boost::asio::placeholders::error));

Otherwise your thread pool will never get any work to do.

Upvotes: 3

Sam Miller
Sam Miller

Reputation: 24174

You should get the single threaded version working prior to jumping into multiple threads. At first glance, it looks like you should invoke ip::tcp::acceptor::listen() and ip::tcp::acceptor::async_accept() prior to invoking io_service::run().

Upvotes: 0

Related Questions