【问题标题】:'n' boost::thread instances doing 'm' jobs'n' boost::thread 实例做 'm' 个工作
【发布时间】:2012-04-20 00:52:34
【问题描述】:

我正在编写一个进化代码,其中每一代都有(比如说)100 个生物体,每个生物体的适应度计算是一个易于并行化的过程。现在,我不想完全创建 100 个独立线程,而是想根据硬件并发性来决定这个(同时运行的线程)数量(我们暂时假设这个数量为 8)。

我想象的标准是我必须在 100 个生物体上运行一个函数(适应度函数),并同时运行 8 个线程。

谁能给我一个简单但有效的方法,使用 boost::thread_group?我对太多新概念(回调等)感到有些困惑。所以一个简单的 c++ sn-p 将不胜感激:)

TIA 问候, 尼基尔

【问题讨论】:

    标签: c++ boost-thread


    【解决方案1】:

    我不确定适应度函数返回什么,更不用说,但一个想法是围绕它编写一个包装函数,将其称为“m”次——在本例中为 100/8 或 12 次。然后创建一个循环“n”次的循环,每次调用thread_group::add_thread,它会产生一个调用包装函数的新线程。

    基本的想法是这样的:

    /* ??? */ fitness_calculation(organism& o){
        //...
    }
    
    // wrapper function
    void calc(std::vector<organism>& v, int idx, int loops){
        for(int i = 0; i < loops; i++)
            fitness_calculation(v[idx + i]);    
    
    }
    
    int main(){
        int num_organisms = 100;
        std::vector<organism> v(num_organisms); // some array with the organisms
    
        int threads = 8;
        boost::thread_group g;
        int organisms_per_thread = num_organisms / threads;
    
        int i = 0, idx = 0;
        for (  ; i < threads; ++i, idx += organisms_per_thread )
            g.add_thread(calc, v, idx, organisms_per_thread);
    
        // finish up remainder in this thread
        calc(v, idx, num_organisms % threads);
        g.join_all();
    }
    

    我不确定我的 thread_group 函数调用语法是否正确,但它足够接近。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2011-12-08
      • 1970-01-01
      • 1970-01-01
      • 2021-04-27
      • 2012-09-16
      • 2013-02-21
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多