#include "mpi.h" #define N 64 main( argc, argv ) int argc; char **argv; { int myrank; int a[N], local_a[N]; int sum; int i; int p; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &myrank ); MPI_Comm_size( MPI_COMM_WORLD, &p ); for (i=0; i<(N/p); i++){ local_a[i] = i+1+(N/p)*myrank; } MPI_Gather(local_a, N/p, MPI_INT, a, N/p, MPI_INT, 0, MPI_COMM_WORLD); if (myrank == 0){ sum = 0; for (i=0; i<N; i++){ sum = sum + a[i]; } printf("sum of each process's local_array=%d\n", sum); } MPI_Finalize(); }
% cc -64 gather.c -lmpi % mpirun -np 4 ./a.out
int MPI_Gather ( void *sendbuf, // starting address of send buffer (choice) int sendcnt, // number of elements in send buffer (integer) MPI_Datatype sendtype,// data type of send buffer elements (handle) void *recvbuf, int recvcount, // number of elements for any single receive // (integer, significant only at root) MPI_Datatype recvtype,// data type of recv buffer elements // (significant only at root) (handle) int root, // rank of receiving process (integer) MPI_Comm comm //communicator (handle )
集める側の配列aに対し,その個数をNではなくN/pとなっていることに注意.