这是我的代码计算素数,我想只使用这些过程之间的集体交流。但是,当我使用'MPI_Scatter'和'MPI_Gather'而不是MPI_Recv和MPI_Isend更改我的代码时出错。我应该改变什么呢?
这是我的原始代码:
MPI_Request req;
MPI_Status status;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD, &p);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
if( my_rank == 0){
printf("Input(50-1000) : ");
fflush(stdout);
scanf("%d",&w);
for(i=0; i<w; i++) data[i] = i+1;
}
MPI_Bcast(&w, 1, MPI_INT,0,MPI_COMM_WORLD);
MPI_Bcast(data, w, MPI_INT,0,MPI_COMM_WORLD);
if( my_rank != 0){
x = w/(p-1);
low = (my_rank-1)*x;
high = low+x-1;
for(num = data[low]; num <= data[high];num++){
result = 0;
t=1;
while(num>=t){
if(num%t==0)
result = result +1;
t += 1;
}
if(result==2) i += 1;
}
MPI_Isend(&i,1,MPI_INT,0,0,MPI_COMM_WORLD,&req);
}
if(my_rank == 0){
int j = 0;
for( j = 1; j < p; j++){
MPI_Recv(&i,1,MPI_DOUBLE,MPI_ANY_SOURCE,0,MPI_COMM_WORLD,&status);
printf("Process %d : There are %d prime numbers\n",status.MPI_SOURCE,i );
}
}
MPI_Finalize();
}
输出是:
Input(50-1000) : 50
Process 1 : There are 5 prime numbers
Process 2 : There are 4 prime numbers
Process 3 : There are 2 prime numbers
Process 4 : There are 4 prime numbers
以下是我更改代码的部分:
if( my_rank != 0){
x = w/(p-1);
low = (my_rank-1)*x;
high = low+x-1;
for(num = data_send[low]; num <= data[high];num++){
result = 0;
t=1;
while(num>=t){
if(num%t==0)
result = result +1;
t += 1;
}
if(result==2) i += 1;
}
MPI_Scatter(data_send,1,MPI_INT,data_recv,1,MPI_INT,0,MPI_COMM_WORLD);
}
答案 0 :(得分:1)
MPI_Scatter
是一项集体行动,需要所有职级召集。同样适用于MPI_Gather
。
表示:MPI_Scatter
调用应移至代码中的if
块之外(类似于MPI_Gather
)。
您可以找到示例here。
答案 1 :(得分:1)
以下是您如何使用MPI_Gather()
int * results;
if( my_rank != 0){
x = w/(p-1);
low = (my_rank-1)*x;
high = low+x-1;
for(num = data[low]; num <= data[high];num++){
result = 0;
t=1;
while(num>=t){
if(num%t==0)
result = result +1;
t += 1;
}
if(result==2) i += 1;
}
} else {
results = (int *)malloc(p * sizeof(int));
}
MPI_Gather(&i, 1, MPI_INT, results, 1, MPI_INT, 0, MPI_COMM_WORLD);
if(my_rank == 0){
int j = 0;
for( j = 1; j < p; j++){
printf("Process %d : There are %d prime numbers\n",j, results[j]);
}
free(results);
}
请注意,您可以安排此算法以便在0级进行计算,因此使用p
MPI任务而不是p-1