Write a MPI Program demonstration of MPI_Scatter and MPI_Gather
STEP1: Open terminal
Type
nano sg.c
type code as in below
#include <mpi.h>
#include <stdio.h>
int main(int argc, char** argv) {
int rank, size;
int data[100]; // Only used by root
int recv_value; // Value received by each process
int gathered[100]; // Only used by root
// Initialize MPI
MPI_Init(&argc, &argv);
// Get rank and size
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// Only rank 0 initializes data
if (rank == 0) {
for (int i = 0; i < size; i++) {
data[i] = i * 10;
}
printf("Process 0 initialized data: ");
for (int i = 0; i < size; i++) {
printf("%d ", data[i]);
}
printf("\n");
}
// SCATTER: One value from `data` array is sent to each process
MPI_Scatter(data, 1, MPI_INT, &recv_value, 1, MPI_INT, 0, MPI_COMM_WORLD);
printf("Process %d received value %d from Scatter\n", rank, recv_value);
// Each process modifies its value
recv_value += rank;
// GATHER: Each process sends modified value back to root
MPI_Gather(&recv_value, 1, MPI_INT, gathered, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Only rank 0 displays gathered results
if (rank == 0) {
printf("Process 0 gathered data: ");
for (int i = 0; i < size; i++) {
printf("%d ", gathered[i]);
}
printf("\n");
}
// Finalize
MPI_Finalize();
return 0;
}
Now For Compilation
mpicc sg.c -o sg
For execution
mpirun –oversubscribe --np 4 ./sg