当从线程池调用时,boost 的io_service是否共享请求的线程?

Is boost's io_service share threads for request when called from thread pool?

本文关键字:线程 service 是否 共享 请求 io boost 调用      更新时间:2023-10-16

我的问题是关于提升asio的io_service。当我用该方法调用它时:

int main()
{
  try
  {
    boost::asio::io_service io_service;
    Server server(io_service);
    std::vector<boost::shared_ptr<boost::thread> > threads;
    for (std::size_t i = 0; i < 16; ++i)
    {
        boost::shared_ptr<boost::thread> thread(new boost::thread(boost::bind(&boost::asio::io_service::run, &io_service)));
        threads.push_back(thread);
    }
    for (std::size_t i = 0; i < threads.size(); ++i)
    threads[i]->join();
  }
  catch (std::exception& e)
  {
    std::cerr << e.what() << std::endl;
  }
  return 0;
}

它会动态共享请求的线程,还是只为连接组提供一个线程?谢谢。

asio::io_service有一个共享事件队列。这些事件由当前调用 io_service::run() 的线程处理。所以是的,可能会从不同的线程调用处理程序。

我不建议您为服务器运行 16 个线程,因为它会降低您的速度(由于上下文切换和 boost::asio 瓶颈)。如果你真的需要这么多线程,那么更喜欢使用"每个线程io_service"的习惯用法。