/* use csbackup.joensuu.fi instead of cs.joensuu.fi compile: /usr/local/mpich-1.2.0/bin/mpicc ds.ex2.6-7.example.c run : /usr/local/mpich-1.2.0/bin/mpirun -np 5 a.out for nice printing: /usr/local/mpich-1.2.0/bin/mpirun -np 5 a.out | sort To understand the program, draw the processors and slowly draw each message. 6) Write an algorithm (a working C-program) for counting and distributing a sum. At the beginning, there is an integer on each process. At the end, each process will have a copy of the sum of all integers. What is the time complexity of your answer? */ #include #include #include /* a variable needeed for call, result not used */ static MPI_Status tmpstat; /* logical directions */ #define Left (PID-1) #define Right (PID+1) #define Any MPI_ANY_SOURCE /* Send and Receive operations DEST & SOURCE can be Left/Right or a PID (int 0..P-1) SOURCE can be Any */ /* Send the value of an int _variable_ VAR to destination process DEST */ #define Send(DEST, VAR) MPI_Send(&VAR, 1, MPI_INT, DEST, 0, MPI_COMM_WORLD) /* Receive an integer to an int variable VAR from destination process SOURCE */ #define Receive(SOURCE, VAR) MPI_Recv(&VAR, 1, MPI_INT, SOURCE, 0, MPI_COMM_WORLD, &tmpstat) int main(int argc, char **argv) { int PID, /* process-ID */ P; /* number of processes */ /* own variables */ int sum, mess, rnd; /* keep these 3 calls */ MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &PID); MPI_Comm_size(MPI_COMM_WORLD, &P); /* actual code */ srand(PID); rnd = rand() % 10; /* All print just for debugging */ printf("0Proc: %d, rnd: %d \n", PID, rnd); /* Receive from left, except 0 just assign sum */ if (PID != 0) { Receive(Left, mess); sum = rnd + mess; } else { sum = rnd; } /* send sum right, except P-1 */ /* receive final sum from right */ if (PID != P-1) { /* |-> */ Send(Right, sum); /* |<- */ Receive(Right, sum); } /* All print just for debugging */ printf("1Proc: %d, sum: %d \n", PID, sum); /* send final sum to left */ if (PID != 0) { /* <-| */ Send(Left, sum); } /* keep this call */ MPI_Finalize(); exit(0); }