我成功地测试了一个关于 boost io_service 的例子:
for(x = 0; x < loops; x++)
{
// Add work to ioService.
for (i = 0; i < number_of_threads; i++)
{
ioService.post(boost::bind(worker_task, data, pre_data[i]));
}
// Now that the ioService has work, use a pool of threads to service it.
for (i = 0; i < number_of_threads; i++)
{
threadpool.create_thread(boost::bind(
&boost::asio::io_service::run, &ioService));
}
// threads in the threadpool will be completed and can be joined.
threadpool.join_all();
}
这将循环多次并且需要一点时间,因为每次都会为每个循环创建线程。
有没有办法创建所有需要的线程。 然后在循环中发布每个线程的工作。 工作完成后需要等待所有线程完成工作!
像这样:
// start/create threads
for (i = 0; i < number_of_threads; i++)
{
threadpool.create_thread(boost::bind(
&boost::asio::io_service::run, &ioService));
}
for(x = 0; x < loops; x++)
{
// Add work to ioService.
for (i = 0; i < number_of_threads; i++)
{
ioService.post(boost::bind(worker_task, data, pre_data[i]));
}
// threads in the threadpool will be completed and can be joined.
threadpool.join_all();
}
最佳答案
这里的问题是您的工作线程将在创建后立即完成,因为没有工作要做。 io_service::run()
将立即返回,因此除非您设法在所有工作线程有机会调用 run()
之前潜入其中一个后调用, 他们都会马上结束。
解决这个问题的两种方法:
- 使用 barrier阻止 worker 调用
run()
马上。只有在作品发布后才取消阻止。 - 使用
io_service::work
要防止的对象run
从返回。您可以在发布所有内容后销毁工作对象(并且必须在再次尝试join
工作人员之前这样做)。
关于c++ - Boost,在io_service.post之前创建线程池,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34337690/