c++ - 使用 Boost 线程和 io_service 创建线程池

标签 c++ boost boost-asio threadpool boost-thread

我查看了 Stack Overflow 并且有一些非常好的答案,(我的代码实际上是基于 this answer here )但出于某种原因我得到了奇怪的行为 - thread_func 应该被调用 ls1 次,但它只在线程退出前运行 0 到 2 次。似乎 ioService.stop() 在完成之前切断了排队的作业,但据我所知,这不应该发生。这是相关的代码片段:

boost::asio::io_service ioService;
boost::asio::io_service::work work(ioService);

boost::thread_group threadpool;

for (unsigned t = 0; t < num_threads; t++)
{   
    threadpool.create_thread(boost::bind(&boost::asio::io_service::run, &ioService));
}   

//Iterate over the dimensions of the matrices
for (unsigned i = 0; i < ls1; i++)
{   
    ioService.post(boost::bind(&thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}   

ioService.stop();
threadpool.join_all();

非常感谢任何帮助,谢谢!

最佳答案

io_service::stop() 使 run()run_one() 的所有调用尽快返回。它不会删除任何已排队进入 io_service 的未完成处理程序。当io_service::stop()被调用时,threadpool中的线程会尽快返回,导致每个线程执行完毕。

作为io_service::post()将在请求 io_service 调用处理程序后立即返回,在 io_service 之前,threadpool 中的线程将调用多少已发布的处理程序是不确定的 已停止。

如果您希望 thread_func 被调用 ls1 次,那么一个简单的替代方法是重新组织代码,以便将工作添加到 io_servicethreadpool 服务它之前,然后应用程序让 io_service 运行完成。

boost::asio::io_service ioService;

// Add work to ioService.
for (unsigned i = 0; i < ls1; i++)
{   
  ioService.post(boost::bind(
      &thread_func,i, rs1, rs2, ls2, arr, left_arr, &result));
}   

// Now that the ioService has work, use a pool of threads to service it.
boost::thread_group threadpool;    
for (unsigned t = 0; t < num_threads; t++)
{   
  threadpool.create_thread(boost::bind(
      &boost::asio::io_service::run, &ioService));
}   

// Once all work has been completed (thread_func invoked ls1 times), the
// threads in the threadpool will be completed and can be joined.
threadpool.join_all();

关于c++ - 使用 Boost 线程和 io_service 创建线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22495402/

相关文章:

c++ - boost asio : How to monitor that a tcp connection is alive

linux - Boost 找不到本地安装的 icu

c++ - 写入(提升 asio)TCP 套接字 : one by one or all at the same time

c++ - 如何在 vc++ 中使用samplegrabber?样本采集器未定义

c++ - float 学执行时间

c++ - directx C++ 第一人称相机

c++ - 什么会导致应用程序在工作几个小时后因 SIGABRT 获取锁而失败?

c++ - 如何将 boost 回调作为参数传递给方法?

boost-asio - 已弃用的 get_io_service() 的替代方法

c++ - 无法使用 boost 验证我的自签名证书