MPI Scatter/Gather Lab - Kays Solution

From Education

Jump to: navigation, search
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>

#define SERVER 0

int main(int argc, char ** argv) {
  
 FILE *filePtr;
 int rank, size, data_size;
 MPI_Status status;
 int temp, max;
 int *allValues, *values, *results;

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

 if (rank == SERVER) {

   int const LINE_LENGTH = 15;
   char charNum[LINE_LENGTH];
   int numValues, x;

   // Create the array to hold the results from the scatter
   results = (int*)malloc(size * sizeof(int));

   filePtr = fopen(argv[1], "r");

   // Find out the number of values and set up variables accordingly
   fgets(charNum, LINE_LENGTH, filePtr);
   numValues = atoi(charNum);
   allValues = (int*)malloc(numValues * sizeof(int));

   // Read in values from the file
   for (x = 0; x < numValues; x++) {
     fgets(charNum, LINE_LENGTH, filePtr);
     allValues[x] = atoi(charNum);
   }

   fclose(filePtr);

   // Calculate the size that each process will receive   
   data_size = numValues / size;
}

 // Send everyone the size they need to allocate - they all store 
 //	data_size like the server after this call
 MPI_Bcast(&data_size, 1, MPI_INT, SERVER, MPI_COMM_WORLD);

 // Create the array to hold the data
 values = (int*)malloc(data_size * sizeof(int));

 // Server process sends each process its chunk of the data
 MPI_Scatter (allValues, data_size, MPI_INT, values, data_size,
		MPI_INT, SERVER, MPI_COMM_WORLD);

 // Find the lowest value in the local array
 max = values[0];
 for (temp = 1; temp < data_size; temp++)
   if (values[temp] > max) max = values[temp];

 printf("Process %d - my local maximum is %d\n", rank, max);
 
 // The server gathers up all of the values from the workers (and itself)
 MPI_Gather(&max, 1, MPI_INT, results, 1, MPI_INT, SERVER,
		MPI_COMM_WORLD);

 if (rank == SERVER) {
 // The server finds the maximum of the local maximums
 max = results[0];
 for (temp = 1; temp < size; temp++)
   if (results[temp] > max) max = results[temp];  
   printf("The grand max is %d\n", max);
 }

 MPI_Finalize();
}
Personal tools
SC Education sites