我有一个“主要”功能,每个时间步执行许多小的独立任务。但是,在每个时间步之后,我必须等待所有任务完成才能继续前进。
我想让程序多线程。我已经尝试过使用 boost-offshoot 线程池的实现,我尝试过使用(共享指针)线程的向量,我已经尝试过 asio 线程池的想法(使用 io_service,建立一些工作,然后将运行分发到线程和向 io_service 发布处理程序)。
所有这些似乎都有很多开销为我的“许多小任务”创建和销毁线程,我想要一种方法,最好使用 asio 工具,实例化一个 io_service,一个 thread_group,将处理程序发布到 io_service,然后等待在发布更多任务之前完成单个时间步的工作。有没有好的方法来做到这一点?这是我现在工作的(精简)代码:
boost::asio::io_service io_service;
for(int theTime = 0; theTime != totalTime; ++theTime)
{
io_service.reset();
boost::thread_group threads;
// scoping to destroy the work object after work is finished being assigned
{
boost::asio::io_service::work work(io_service);
for (int i = 0; i < maxNumThreads; ++i)
{
threads.create_thread(boost::bind(&boost::asio::io_service::run,
&io_service));
}
for(int i = 0; i < numSmallTasks; ++i)
{
io_service.post(boost::bind(&process_data, i, theTime));
}
}
threads.join_all();
}
这是我宁愿拥有的(但不知道如何实现):
boost::asio::io_service io_service;
boost::thread_group threads;
boost::asio::io_service::work work(io_service);
for (int i = 0; i < maxNumThreads; ++i)
{
threads.create_thread(boost::bind(&boost::asio::io_service::run,
&io_service));
}
for(int theTime = 0; theTime != totalTime; ++theTime)
{
for(int i = 0; i < numSmallTasks; ++i)
{
io_service.post(boost::bind(&process_data, i, theTime));
}
// wait here until all of these tasks are finished before looping
// **** how do I do this? *****
}
// destroy work later and join all threads later...