我想使用boost::asio来设置一个线程池。我的问题是:如何将特定数据附加到创建的每个线程,以及如何管理单独的输出?
更具体地说,我编写了一个Simulation类,它通过在输入中接受一些参数的方法来执行模拟。该类包含计算所需的所有数据。由于数据不是太大,我想复制它,以便在池的每个线程中使用类Simulation的不同实例。
我想做这样的事情:(设置线程池在这里解释:SO和Asio recipes)
class ParallelSimulation
{
public:
static const std::size_t N = 10;
protected:
std::vector< boost::shared_ptr<Simulation> > simuInst; // N copy of a reference instance.
public:
...
// Simulation with a large (>>N) number of inputs
void eval( std::vector< SimulationInput > inputs )
{
// Creation of the pool using N threads
asio::io_service io_service;
asio::io_service::work work(io_service);
boost::thread_group threads;
for (std::size_t i = 0; i < N; ++i)
threads.create_thread(boost::bind(&asio::io_service::run, &io_service));
// Here ? Attaching the duplicates instances of class Simulation ?
// Adding tasks
for( std::size_t i = 0, i_end = inputs.size(); i<i_end; ++i)
io_service.post(...); // add simulation with inputs[i] to the queue
// How to deal with outputs ?
// End of the tasks
io_service.stop();
threads.join_all();
}
};也许用来设置线程池的技术(使用boost::asio)不适合我的问题。你有什么建议吗?谢谢。
发布于 2012-06-13 03:24:50
这对于您的应用程序来说应该可以很好地工作。当您调用io_service.post时,您将传入以inputs[i]作为参数的模拟函数。在该函数(假设是Simulation成员函数)中,只需将计算结果存储在Simulation对象中,然后在联接线程以收集输出之后遍历对象。
如果需要识别执行此工作的特定线程,也可以将i作为参数传递。这假设在模拟完成后收集输出是正常的。
如果需要在运行时访问输出,只需让函数根据需要将输出任务post到io_service即可。确保使用互斥锁保护任何共享数据结构!
https://stackoverflow.com/questions/11000258
复制相似问题