MPI_Gatherv:根的数组中收到的垃圾值 [英] MPI_Gatherv: Garbage values received in root's array
本文介绍了MPI_Gatherv:根的数组中收到的垃圾值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试在C中实现MPI_Gatherv函数。
根据我的程序,每个进程(包括根进程)都应该创建一个大小等于(进程‘ranch+1)的本地数组,该数组将在所有单元格中保存进程的排名。
然后将此本地数组收集到根的rcv_array中。
不知何故,我得到了垃圾值。 谁能告诉我我做错了什么? 另外,我是MPI新手,很难理解MPI_Gatherv的显示和RCV_Count。
我的代码:
#include<stdio.h>
#include<mpi.h>
#include<stdlib.h>
int sum(int);
int main(int argc, char **argv){
int proc_count, proc_rank, root = 0;
int *localdata = NULL;
int *rcv_array = NULL;
int *disp = NULL;
int *rcv_count = NULL;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &proc_count);
MPI_Comm_rank(MPI_COMM_WORLD, &proc_rank);
if(proc_rank == root){
rcv_array = malloc((sum(proc_count)+1) * sizeof(int));
rcv_count = malloc(proc_count * sizeof(int));
disp = malloc(proc_count * sizeof(int));
rcv_count[0] = 1;
disp[0] = 0;
for(int i=1; i<proc_count; i++){
rcv_count[i] = i+1;
disp[i] = rcv_count[i-1] + disp[i-1];
}
}
localdata = malloc(proc_rank * sizeof(int));
for(int i=0; i<=proc_rank; i++)
localdata[i]=proc_rank;
MPI_Gatherv(&localdata, proc_rank+1, MPI_INT, rcv_array, rcv_count, disp, MPI_INT, root, MPI_COMM_WORLD);
if(proc_rank == root){
printf("Elements gathered from each process rank wise:
");
for(int i=0; i<sum(proc_count)+1; i++){
printf("-%d-", rcv_array[i]);
}
printf("
");
}
MPI_Finalize();
return 0;
}
int sum(int n){
int total = 0;
for(int i=1; i<=n; i++)
total+=i;
return total;
}
推荐答案
三个小问题:
您说要创建一个大小等于(process‘ranch+1)的本地数组,但您只做了
localdata = malloc(proc_rank * sizeof(int));
只需malloc((proc_rank + 1) * sizeof(int));
即可。作为
MPI_Gatherv
的第一个参数,您使用&localdata
。这是指针的地址,请改用指针本身localdata
。sum(proc_count)+1
(用于打印和分配),实际上多了一个。
否则你就可以走了。特别是,复杂的位移/偏移计算看起来还不错。
这篇关于MPI_Gatherv:根的数组中收到的垃圾值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文