【问题标题】:Boost::Asio Threaded Server Asynchroun Problem. Nothing happenBoost::Asio 线程服务器异步问题。什么都没发生
【发布时间】:2010-11-01 16:23:38
【问题描述】:

我正在使用 BoostLib 制作服务器,因此我正在使用 asio lib。

我创建了一个服务器类。

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);
}

还有启动函数:

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 是一个指向客户端类的指针。

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

我编译并启动了这段代码,并连接了一个小 TestClient。 Connection 存在,但永远不会调用 Server::OnConnection。我调试并设置了一个断点,但它永远不会在那里中断。

那么有什么问题。 THREAD_POOL_SIZE 为 25。

【问题讨论】:

    标签: c++ multithreading sockets boost boost-asio


    【解决方案1】:

    也许这段代码不是完整版本,但不清楚为什么在打开套接字之前等待所有线程退出(使用join)。我认为你需要移动这个:

       // 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));
    

    否则您的线程池将永远无法完成任何工作。

    【讨论】:

    • 非常感谢,我的问题现在已经解决了 :)
    【解决方案2】:

    在跳入多线程之前,您应该让单线程版本正常工作。乍一看,您应该在调用 io_service::run() 之前调用 ip::tcp::acceptor::listen()ip::tcp::acceptor::async_accept()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-27
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多