【问题标题】:Calling boost asio io_service.run from multiple threads or one thread when queuing requests in handlers在处理程序中排队请求时从多个线程或一个线程调用 boost asio io_service.run
【发布时间】:2020-02-21 13:34:37
【问题描述】:

当仅在处理程序中排队请求而不立即在处理程序中处理请求时,我认为从多个线程调用 io_service.run() 没有任何好处。

Server 类中,我从多个线程调用 m_ios.run():

const unsigned int threadPoolSize = std::thread::hardware_concurrency() * 2;
for (unsigned int i = 0; i < threadPoolSize; i++)
{
    std::unique_ptr<std::thread> th(new std::thread([this]() { m_ios.run(); }));
    m_threadPool.push_back(std::move(th));
}

在由处理异步读取的服务器管理的 Service 类中:

void handleNextRequest()
{
    m_connection->async_read(m_request, m_connection->getStrand().wrap(boost::bind(&Service::onRequestRecieved, this, boost::asio::placeholders::error)));
}

void onRequestRecieved(const boost::system::error_code& ec)
{
    if (!ec)
    {
        addServerRequest(m_request); // Adds request to a thread-safe queue
        handleNextRequest();
    }
    else
    {
        stop();
    }
}

在我的情况下,从多个线程运行 io_service.run() 有什么好处吗?

【问题讨论】:

    标签: c++ multithreading boost boost-asio


    【解决方案1】:
    void first(){
    // do your things
    }
    void second(){
    // do your things
    }
    void allthings(){
        thread t1(first);
        thread t2(second);
        t1.join();
        t2.join();
    }
    
    int main() {
    
        allthings();
    
        return 0;
    }
    

    【讨论】:

    • 对不起,您的回答与我的问题无关。您从 2 个线程调用 2 个函数,而您的答案中没有任何与 boost asio 相关的内容。
    【解决方案2】:

    经过几次基准测试后,很明显在我的示例中,在一个线程上调用 io_service.run() 与在多个线程上运行 io_service.run() 一样快。再加上多线程的使用更多的内存。

    因此,如果您不处理读取处理程序本身中的任何内容(实际的请求处理代码需要时间来运行),那么使用多线程您将不会获得任何好处。

    【讨论】:

      猜你喜欢
      • 2021-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多