首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用线程池进行模拟: boost-thread和boost-asio

使用线程池进行模拟: boost-thread和boost-asio
EN

Stack Overflow用户
提问于 2012-06-12 23:52:39
回答 1查看 2.1K关注 0票数 4

我想使用boost::asio来设置一个线程池。我的问题是:如何将特定数据附加到创建的每个线程,以及如何管理单独的输出?

更具体地说,我编写了一个Simulation类,它通过在输入中接受一些参数的方法来执行模拟。该类包含计算所需的所有数据。由于数据不是太大,我想复制它,以便在池的每个线程中使用类Simulation的不同实例。

我想做这样的事情:(设置线程池在这里解释:SOAsio recipes)

代码语言:javascript
复制
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)不适合我的问题。你有什么建议吗?谢谢。

EN

回答 1

Stack Overflow用户

发布于 2012-06-13 03:24:50

这对于您的应用程序来说应该可以很好地工作。当您调用io_service.post时,您将传入以inputs[i]作为参数的模拟函数。在该函数(假设是Simulation成员函数)中,只需将计算结果存储在Simulation对象中,然后在联接线程以收集输出之后遍历对象。

如果需要识别执行此工作的特定线程,也可以将i作为参数传递。这假设在模拟完成后收集输出是正常的。

如果需要在运行时访问输出,只需让函数根据需要将输出任务postio_service即可。确保使用互斥锁保护任何共享数据结构!

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11000258

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档