Search code examples
cparallel-processingmpiwritetofile

MPI_Gatherv is not collecting data correctly


I'm trying to gather different size arrays using MPI_Gatherv, but for some reason, it's only gathering the first object in the first processor. When I do the above for loop, I get the correct values from xPos and yPos, but when I gather the data to the xFinal and yFinal array and print out the values, I'm only getting the first x and y. So basically the first object has an (x,y) of (0,0) and I have 10 objects, and all the objects only print out (0,0) when the actual object it should be referencing has a different (x,y)

Just in case to say, the counts[rank] and displs are definitely right because I used them to scatterv previously.

Am I using gatherrv incorrectly? Or am I printing incorrectly?

for ( a = 0; a < size; a++) {
    if (rank == a) {
        for ( i = 0 ; i < counts[rank]; i++) {
            printf("from procs %d: %lE %lE\n", rank, xPos[i], yPos[i]);
        }
    }
}


MPI_Gatherv(&xPos, counts[rank], MPI_DOUBLE, &xFinal, counts, displs, MPI_DOUBLE,0, MPI_COMM_WORLD);
MPI_Gatherv(&yPos, counts[rank], MPI_DOUBLE, &yFinal, counts, displs, MPI_DOUBLE,0, MPI_COMM_WORLD);


MPI_Finalize();

FILE* f = fopen("universe.out", "wt");
for (i = 0; i < N; i++)
    fprintf(f, "%lE %lE\n", xFinal[i], yFinal[i]);
fclose(f);

Solution

  • It seems that you are writing the file from all ranks simultaneously. You should put the file writing code within if (rank == 0) { ... } to only let rank 0 write:

    if (rank == 0)
    {
        FILE* f = fopen("universe.out", "wt");
        for (i = 0; i < N; i++)
            fprintf(f, "%lE %lE\n", xFinal[i], yFinal[i]);
        fclose(f);
    }
    

    Otherwise the content of the file could be anything.