scatter in mpi [a very simple code]

2019-02-20 23:10发布

问题:

Here is code of mpi scatter:

#include <stdio.h>
#include <mpi.h>       

int a[10]={1,2,3,4,5,6,7,8,9,10};
int b[1];

int main(int argc, char *argv[])  {
    int rank;       

    MPI_Init(&argc, &argv);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    MPI_Barrier(MPI_COMM_WORLD);

    if(rank ==0){
        MPI_Scatter(a,1,MPI_INT,b,1,MPI_INT,0,MPI_COMM_WORLD);
    }

    MPI_Barrier(MPI_COMM_WORLD);
    printf("\n%d from rank=%d\n",b[0],rank);

    MPI_Finalize();
    return 0;
}

I want output as follows:

1 from rank 0
2 from rank 1
3 from rank 2
...

But I am getting

1 from rank 0
0 from rank 1
0 from rank 2
0 from rank 3
0 from rank 4
...

回答1:

MPI_Scatter() is a collective operation, and hence it must be called by all the ranks of the communicator.

get rid of the if (rank == 0) and you will be fine.

Note that in your example, the a send buffer is small enough and does not cause any hang.



标签: c mpi