#include <stdio.h>
#include <math.h>
#include <mpi.h>
int main(int argc, char *argv[])
{
int i, done = 0, n;
double PI25DT = 3.141592653589793238462643;
double pi, tmp, h, sum, x;
int numprocs, rank;
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &numprocs);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (numprocs < 1)
printf("numprocs = %d, should be run with numprocs > 1\n", numprocs);
else {
while (!done)
{
if (rank == 0) {
printf("Enter the number of intervals: (0 quits) \n");
scanf("%d",&n);
}
if (n == 0) break;
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
h = 1.0 / (double) n;
sum = 0.0;
for (i = 1 + rank; i <= n; i+=numprocs) {
x = h * ((double)i - 0.5);
sum += 4.0 / (1.0 + x*x);
}
MPI_Reduce(&sum, &tmp, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD);
if (rank == 0) {
pi = h * tmp;
printf("pi is approximately %.16f, Error is %.16f\n", pi, fabs(pi - PI25DT));
}
}
}
MPI_Finalize();
}
我运行这个程序,进程数= 10,在scanf中键入0后(“%d”,& n);程序似乎没有完成,我必须用Ctrl C关闭它.
10 total processes killed (some possibly by mpirun during cleanup)
mpirun: clean termination accomplished
杀戮过程后出现在控制台中.
解决方法:
嗯,当然.看看这里发生了什么:
if (rank == 0) {
printf("Enter the number of intervals: (0 quits) \n");
scanf("%d",&n);
}
if (n == 0) break;
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
如果你在等级0上输入’0′,那么等级0就会中断,但所有其他等级都具有他们上次在n中所拥有的任何内容(或者,在第一次迭代的情况下,无论该内存位置是什么随机内容).因此排名1-(N-1)进入MPI_Bcast,耐心地等待参与广播以找出n是什么,同时排名0已退出循环并且坐在MPI_Finalize想知道其他人在哪里.
你只需要翻转这些行:
MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
if (n == 0) break;
现在每个人都决定是否同时突破循环.