【发布时间】:2021-02-01 13:54:36
【问题描述】:
该程序应采用两个命令行参数,N = 每个工作人员应生成的项目数,H = 每个工作人员生成的随机数范围内的最大值。每个工作人员都会列出这些随机值,然后 BigList 是我试图将它们全部收集回的地方,但 BigList 的数组中没有显示任何内容。例如: 运行 mpirun -np 3 a.out 4 20 得到:
RANK: 1 --- NUM: 18
RANK: 1 --- NUM: 6
RANK: 1 --- NUM: 12
RANK: 1 --- NUM: 10
RANK: 2 --- NUM: 9
RANK: 2 --- NUM: 3
RANK: 2 --- NUM: 6
RANK: 2 --- NUM: 5
当我希望 BigList 由上面列出的每个 num 组成时,它是空的。
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(int argc, char* argv[]){
double t1, t2;
MPI_Init(&argc, &argv);
int rank;
int wsize;
int N = 10, H = 5;
int num, k, i;
int locarr[25];
int bigList[300];
srand(time(NULL));
if(argc > 1){
N = atoi(argv[1]);
H = atoi(argv[2]);
}
t1 = MPI_Wtime();
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &wsize);
if( rank == 0){
MPI_Bcast(&N, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(&H, 1, MPI_INT, 0, MPI_COMM_WORLD);
}
else{
for(i = 0; i < N; i++){
locarr[i] = (((rand() % H) + 1) / rank);
printf("RANK: %d --- NUM: %d\n", rank, locarr[i]);
}
}
MPI_Gather(&locarr, N, MPI_INT, bigList, N, MPI_INT, 0, MPI_COMM_WORLD);
if( rank == 0){
printf("BigList: ");
for(k = 0; k < (rank * N); k++){
printf(" %d", bigList[k]);
}
printf("\n");
}
t2 = MPI_Wtime();
// printf("\nMPI_Wtime(): %f\n", t2 - t1);
MPI_Finalize();
return 0;
}
【问题讨论】:
-
所有队伍需要拨打
MPI_Bcast()。很可能已收集到数据,因为for循环条件中的错误,您根本不打印它。 -
只是吹毛求疵,但在对
MPI_Gather的调用中,您不需要在locarr之前使用&。它适用于堆栈数组,但如果您将locarr设为指向动态分配数组的指针,则会中断。