使用Boost线程和io_service创建线程池

Dan*_*Dan 2 c++ boost boost-thread boost-asio threadpool

我已经浏览了Stack Overflow并且已经有了一些非常好的答案,(我的代码实际上基于这里的答案)但是由于某种原因我得到了奇怪的行为 - 因为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();
Run Code Online (Sandbox Code Playgroud)

任何帮助将不胜感激,谢谢!

Tan*_*ury 5

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

正如io_service::post()在请求io_service调用处理程序之后立即返回的那样,在停止threadpool之前线程将调用多少个已发布的处理程序是不确定的io_service.

如果您希望thread_func被调用ls1次数,那么一个简单的替代方法是重新组织代码,以便将工作添加到服务io_service之前threadpool,然后应用程序让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();
Run Code Online (Sandbox Code Playgroud)