1

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

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

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

TIA 问候, Nikhil

4

1 回答 1

0

我不确定适应度函数返回什么,更不用说,但一个想法是围绕它编写一个包装函数,将其称为“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 函数调用语法是否正确,但它足够接近。希望这会有所帮助。

于 2012-04-20T03:21:55.970 回答