#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("%d", &n); 中键入 0 后运行该程序 该程序似乎没有完成,我必须用 Ctrl+C 关闭它。
总共有 10 个进程被杀死(有些可能是在清理过程中被 mpirun 杀死的) mpirun:完成了干净的终止
杀死进程后出现在控制台中。