gpt4 book ai didi

c++ - 'n' boost::thread 实例执行 'm' 个作业

转载 作者:太空宇宙 更新时间:2023-11-04 14:17:15 25 4
gpt4 key购买 nike

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

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

任何人都可以使用 boost::thread_group 给我一个简单但有效的方法吗?我对太多新概念(回调等)有点困惑。所以一个简单的 C++ 片段将不胜感激 :)

TIA问候,尼克尔

最佳答案

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

关于c++ - 'n' boost::thread 实例执行 'm' 个作业,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10238862/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com