Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
7 views2 pages

Program 8

This document provides a demonstration of an MPI program that utilizes MPI_Scatter and MPI_Gather functions. It initializes an array of data in the root process, scatters the data to all processes, modifies the received values, and then gathers the modified values back to the root process for display. The document also includes instructions for compiling and executing the program using MPI commands.

Uploaded by

shivakumar31855
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views2 pages

Program 8

This document provides a demonstration of an MPI program that utilizes MPI_Scatter and MPI_Gather functions. It initializes an array of data in the root process, scatters the data to all processes, modifies the received values, and then gathers the modified values back to the root process for display. The document also includes instructions for compiling and executing the program using MPI commands.

Uploaded by

shivakumar31855
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like