我环顾了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调用处理程序后立即返回,因此不确定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();

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

10-10 12:46