"Game of life" simulation programm
Parallel implementation
---------------------------------------
---------------------------------------
---------------------------------------
#include
#include "mpi.h"
#include
#include
#include
const int PX=4,PY=4;
int len,pid,pnr;
int ln,rn,un,dn;
MPI_Status status;
int a[5][5];
int b[5][5];
int k,i,j,st,st1,Imax,Jmax,Imin,Jmin,cycle;
FILE *file;
int proc1() //number of neigbors
{
int st=0;
if ((i+1)<=Imax)
if (a[i+1][j]==1) st++;
if ((i-1)>=Imin)
if (a[i-1][j]==1) st++;
if ((j+1)<=Jmax)
if (a[i][j+1]==1) st++;
if ((j-1)>=Jmin)
if (a[i][j-1]==1) st++;
if ( ( i+1<=Imax)&&( j+1<=Jmax) )
if (a[i+1][j+1]==1) st++;
if ( (i+1<=Imax)&&(j-1>=Jmin) )
if (a[i+1][j-1]==1) st++;
if ( (i-1>=Imin)&&(j+1<=Jmax) )
if (a[i-1][j+1]==1) st++;
if ( (i-1>=Imin)&&(j-1>=Jmin) )
if (a[i-1][j-1]==1) st++;
if (st==2) return 1;
if (st==3) return 2;
if (st==1) return 3;
if (st>4) return 4;
}
void processors_init()
{
if ( (pid % PX)==0 ) ln=20;
else ln=pid-1;
if ( ( (pid+1) % PX)==0 ) rn=20;
else rn=pid+1;
if ( pid < PX ) un=20;
else un=pid-PX;
if ( pid < (PX-1)*PY ) dn=pid+PX;
else dn=20;
}
int main(int argc, char **argv)
{
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&pnr);
MPI_Comm_rank(MPI_COMM_WORLD,&pid);
if (pid==0)
file = fopen("MPI.data","w");
processors_init();
Imax=Jmax=4;
Imin=Jmin=0;
if (ln==20) Jmax--;
if (rn==20) Jmax--;
if (un==20) Imax--;
if (dn==20) Imax--;
//init
for (i=0;i<4;i++)
for (j=0;j<4;j++)
{
k=rand()-1;
a[i][j] = k % 2;
}
for (cycle=0 ; cycle<500 ; cycle++)
{
if ( (pid>=0)&&(pid<=15) )
{
for (i=Imin;i<=Imax;i++)
{
if (rn != 20) MPI_Sendrecv(&a[i][Jmax-1], 1, MPI_INT, rn, 0, &a[i][Jmax], 1, MPI_INT, rn, 1, MPI_COMM_WORLD, &status );
if (ln != 20) MPI_Sendrecv(&a[i][Jmin+1], 1, MPI_INT, ln, 1, &a[i][Jmin], 1, MPI_INT, ln, 0, MPI_COMM_WORLD, &status );
}
for (j=Jmin;j<=Jmax;j++)
{
if (un != 20) MPI_Sendrecv(&a[Imin+1][j], 1, MPI_INT, un, 2, &a[Imin][j], 1, MPI_INT, un, 3, MPI_COMM_WORLD, &status );
if (dn != 20) MPI_Sendrecv(&a[Imax-1][j], 1, MPI_INT, dn, 3, &a[Imax][j], 1, MPI_INT, dn, 2, MPI_COMM_WORLD, &status );
}
for (i=0; i<5; i++)
for (j=0; j<5; j++)
b[i][j] = a[i][j];
for (i=Imin; i