Shadark
Shadark

Reputation: 489

MPI_Finalize() doesn't finalize

#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();
}

I run this program with number of processes = 10 and after typing 0 in scanf("%d", &n); the program doesn't seem to finalize and I have to close it with Ctrl+C.

10 total processes killed (some possibly by mpirun during cleanup) mpirun: clean termination accomplished

Appears in console after killing process.

Upvotes: 4

Views: 2958

Answers (2)

yyfn
yyfn

Reputation: 767

you have a endless while loop, so MPI_Finalize() can't execute.

Upvotes: 0

Jonathan Dursi
Jonathan Dursi

Reputation: 50927

Well, sure. Look at what's going on here:

        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);

If you enter '0' on rank 0, then rank 0 breaks, but all the other ranks have whatever they had in n last time around (or, in the case of the first iteration, whatever random stuff was in that memory location). So ranks 1-(N-1) enter the MPI_Bcast, patiently waiting to participate in a broadcast to find out what n is, and meanwhile rank 0 has exited the loop and is sitting at MPI_Finalize wondering where everyone else is.

You just need to flip those lines:

        MPI_Bcast(&n, 1, MPI_INT, 0, MPI_COMM_WORLD);
        if (n == 0) break;

Now everyone decides whether or not to break out of the loop at the same time.

Upvotes: 6

Related Questions