// Starting code for the MPI coursework.
// First make sure mpicc is available (‘module load mpi/mpich-x86_64’ on school machines),
// then compile with:
// mpicc -Wall -o cwk2 cwk2.c
// or use the provided makefile. “-Wall” turns on all warnings (optional but recommended).
// You can also add “-stc=c99” if you like.
// Includes
#include
#include
#include
// Some extra routines for this coursework. DO NOT MODIFY OR REPLACE THESE ROUTINES,
// as this file will be replaced with a different version for assessment.
#include “cwk2_extra.h”
int main( int argc, char **argv )
// Initialise MPI and get the rank and no. of processes.
int rank, numProcs;
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &numProcs );
MPI_Comm_rank( MPI_COMM_WORLD, &rank );
// Read in the image file to rank 0.
int *image = NULL, maxValue, pixelsPerProc, dataSize;
if( rank==0 )
// Read in the file and extract the maximum grey scale value and the data size (including padding bytes).
// Defined in cwk2_extras.h; do not change, although feel free to inspect.
image = readImage( “image.pgm”, &maxValue, &dataSize, numProcs );
if( image==NULL )
MPI_Finalize();
return EXIT_FAILURE;
// The image size has already been rounded up to a multiple of numProcs by “readImage()”.
pixelsPerProc = dataSize / numProcs;
printf( “Rank 0: Read in PGM image array of size %d (%d per process), with max value %d.\n”, dataSize, pixelsPerProc, maxValue );
// Allocate memory for the final histogram on rank 0.
int *combinedHist = NULL;
if( rank==0 )
combinedHist = (int*) malloc( (maxValue+1)*sizeof(int) ); // Note ‘maxValue+1’, as range is 0 to maxValue inclusive.
if( !combinedHist ) return allocateFail( “global histogram”, rank );
for( i=0; i
// Display the histgram.
for( i=0; i