7.6.1. Examples using MPI_SCATTER and MPI_SCATTERV

PreviousUpNext
Up: Scatter Next: All-Gather Previous: Scatter

The examples in this section use intra-communicators.


Example The reverse of Example Examples using MPI_GATHER and MPI_GATHERV. Scatter sets of 100 ints from the root to each MPI process in the group. See Figure 12.


MPI_Comm comm; 
int gsize,*sendbuf; 
int root, rbuf[100]; 
... 
MPI_Comm_size(comm, &gsize); 
sendbuf = (int *)malloc(gsize*100*sizeof(int)); 
... 
MPI_Scatter(sendbuf, 100, MPI_INT, rbuf, 100, MPI_INT, root, comm); 

Image file


Figure 12: The root scatters sets of 100 ints to each MPI process in the group


Example The reverse of Example Examples using MPI_GATHER and MPI_GATHERV. The root scatters sets of 100 ints to the other MPI processes, but the sets of 100 are stride ints apart in the sending buffer. Requires use of MPI_SCATTERV. Assume stride ≥ 100. See Figure 13.


MPI_Comm comm; 
int gsize,*sendbuf; 
int root, rbuf[100], i, *displs, *scounts; 
 
... 
 
MPI_Comm_size(comm, &gsize); 
sendbuf = (int *)malloc(gsize*stride*sizeof(int)); 
... 
displs = (int *)malloc(gsize*sizeof(int)); 
scounts = (int *)malloc(gsize*sizeof(int)); 
for (i=0; i<gsize; ++i) { 
    displs[i] = i*stride; 
    scounts[i] = 100; 
} 
MPI_Scatterv(sendbuf, scounts, displs, MPI_INT, rbuf, 100, MPI_INT, 
             root, comm); 

Image file


Figure 13: The root scatters sets of 100 ints, moving by stride ints from send to send in the scatter


Example The reverse of Example Examples using MPI_GATHER and MPI_GATHERV. We have a varying stride between blocks at sending (root) end, at the receiving end we receive into the i-th column of a 100×150 C array. See Figure 14.


MPI_Comm comm; 
int gsize,recvarray[100][150],*rptr; 
int root, *sendbuf, myrank, *stride; 
MPI_Datatype rtype; 
int i, *displs, *scounts, offset; 
... 
MPI_Comm_size(comm, &gsize); 
MPI_Comm_rank(comm, &myrank); 
 
stride = (int *)malloc(gsize*sizeof(int)); 
... 
/* stride[i] for i = 0 to gsize-1 is set somehow 
 * sendbuf comes from elsewhere 
 */ 
... 
displs = (int *)malloc(gsize*sizeof(int)); 
scounts = (int *)malloc(gsize*sizeof(int)); 
offset = 0; 
for (i=0; i<gsize; ++i) { 
    displs[i] = offset; 
    offset += stride[i]; 
    scounts[i] = 100 - i; 
} 
/* Create datatype for the column we are receiving 
 */ 
MPI_Type_vector(100-myrank, 1, 150, MPI_INT, &rtype); 
MPI_Type_commit(&rtype); 
rptr = &recvarray[0][myrank]; 
MPI_Scatterv(sendbuf, scounts, displs, MPI_INT, rptr, 1, rtype, 
             root, comm); 

Image file


Figure 14: The root scatters blocks of 100-i ints into column i of a 100$ x $150 C array. At the sending side, the blocks are stride[i] ints apart.


PreviousUpNext
Up: Scatter Next: All-Gather Previous: Scatter


Return to MPI-5.0 Standard Index
Return to MPI Forum Home Page

(Unofficial) MPI-5.0 of June 9, 2025
HTML Generated on March 2, 2025