c++ - 在处理程序中排队请求时,从多个线程或一个线程调用boost asio io_service.run

标签 c++ multithreading boost boost-asio

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

服务器类中,我从多个线程调用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));
}

在由处理异步读取的服务器管理的服务类中:
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()有什么好处?

最佳答案

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

关于c++ - 在处理程序中排队请求时,从多个线程或一个线程调用boost asio io_service.run,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58554445/

相关文章:

c++ - 如何在 C++ 中比较并提取两个文件中最接近的数字

c++ - while (数组末尾) - 如何识别

android - JNI-SIGSEGV信号SIGSEGV : invalid address when in worker thread

c++ - 基于Boost foreach实现enumerate_foreach

c++ - 检索函数内用 operator new 分配的类指针对象成员的值的问题

c++ - 重构所有类通用的方法

c++ - 如何确保始终有给定数量的线程? (另外,这是线程的一个很好的用法吗?)

java - Hands ProcessBuilder 在java中 Unix操作系统中的多线程

c++ - 如何在GCC编译器中启用最高警告级别(Boost被大量使用)

c++ - boost::iostreams::filtering_istream 是否允许搜索?