'n'提升:线程实例执行'm'作业
'n' boost::thread instances doing 'm' jobs
我正在编写一个进化代码,其中每一代都有(比如)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函数调用语法,但它足够接近。 希望这有所帮助。
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- C++,系统无法执行指定的程序
- 使用C++中的模板和运算符重载执行矩阵运算
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 执行函数时导致崩溃的变量
- 无论条件是否为true,if总是在c++中执行
- 当函数模板参数是具有默认参数的类模板时,函数模板参数的推导如何执行
- 在C++中对T*类型执行std::move的意外行为
- 使用QProcess执行命令,并将结果存储在QStringList中
- 如何在没有信号的情况下从C++执行QML插槽
- 如何确认我的constexpr表达式实际上已经在编译时执行
- C++17中的并行执行策略
- QML按钮点击功能执行顺序
- 将执行、作业和WinAPI相乘
- 编写执行与set_symmetric_difference相同的作业的函数
- 执行异步作业的函数
- R6010 执行后出错.if 语句在 for 循环中.[作业][中止已解决,发现新问题]
- 'n'提升:线程实例执行'm'作业
- 通过GUI的作业进程在同一个虚拟处理器上执行,或者通过命令行使用任何空闲的虚拟处理器
- 所有作业在C COMPS执行中失败