'n'提升:线程实例执行'm'作业

'n' boost::thread instances doing 'm' jobs

本文关键字:执行 作业 实例 提升 线程      更新时间:2023-10-16

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

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

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

蒂亚问候尼基尔

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