我刚刚并行化了一段代码,但有一些问题。我使用mpi-allreduce。我将一个一维区间放在N个子区间中。每个处理器对每个bin执行一定数量的求和。我使用MP_allreduce对每个处理器的每个子间隔进行求和。代码似乎混合了子区间,因此在一些子区间中,处理器将它们的值贡献给不同的子区间。这是mpi_Allreduce的一个常见问题吗?如何解决它?谢谢
发布于 2015-09-09 21:49:27
如果不看你的代码,就很难解释你的错误到底是什么。但是,根据我对您问题的理解,您将一个元素数组划分为多个间隔,然后为每个进程分配一个间隔。然后,每个进程都会计算其部分和。现在,为了总结所有元素,我们使用了MPI_Allreduce()函数。因此,这里是上述场景的一个简单实现。
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
#include <assert.h>
int *create_rand_nums(int num_elements) {
int *rand_nums = (int *)malloc(sizeof(int) * num_elements);
assert(rand_nums != NULL);
int i;
for (i = 0; i < num_elements; i++) {
rand_nums[i] = rand()%100;
}
return rand_nums;
}
int main(int argc, char** argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s num_elements_per_proc\n",argv[0]);
exit(1);
}
int num_elements_per_proc = atoi(argv[1]);
MPI_Init(NULL, NULL);
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
int *rand_nums, *local_nums;
if(world_rank == 0)
{
srand(time(NULL)*world_rank);
rand_nums = create_rand_nums(world_size*num_elements_per_proc);
}
local_nums = (int*)malloc(sizeof(int)*num_elements_per_proc);
MPI_Scatter(rand_nums,num_elements_per_proc,MPI_INT,local_nums,num_elements_per_proc,MPI_INT,0,MPI_COMM_WORLD);
int local_sum = 0;
int i;
for (i = 0; i < num_elements_per_proc; i++)
{
local_sum += local_nums[i];
}
int global_sum;
MPI_Allreduce(&local_sum, &global_sum, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
printf("World Rank: %d \t Global Sum: %d \n",world_rank,global_sum);
if(world_rank == 0)
free(rand_nums);
free(local_nums);
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
}下面是程序中发生的事情
根进程( MPI_Scatter().
world_rank 0)生成大小由程序参数确定的随机数。根进程使用MPI_Allreduce()调用计算。https://stackoverflow.com/questions/32472475
复制相似问题