Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <mpi.h>
- int random_dec(int current)
- {
- int retVal = current - random()%10;
- return (retVal > 0) ? retVal : 0;
- }
- int main(int argc, char **argv)
- {
- int myRank, numProcs,bomb, recvBomb;
- bomb = 10;
- // TODO: Initialize MPI and obtain process identity
- MPI_Init(&argc, &argv);
- MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
- MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
- // Rank-specific initialization of the random number generator
- srandom(MPI_Wtime() + myRank*100);
- int nextRank = (myRank + 1) % numProcs;
- int looserRank = -1;
- int countDownCounter = 50;
- // Rank 0 reads the initial timer value and starts the bomb
- if (myRank == 0)
- {
- if (argc > 1)
- {
- countDownCounter = atoi(argv[1]);
- if (countDownCounter <= 0) exit(1);
- }
- printf("Counting down from %i\n", countDownCounter);
- printf("Next Rank is %i\n", nextRank);
- MPI_Send(&bomb,1,MPI_INT,nextRank,0,MPI_COMM_WORLD);
- // TODO: Throw the bomb in
- }
- else
- {
- int count = 0;
- int data;
- // TODO: Implement a loop that runs until the counter hits 0
- while(countDownCounter > 0){
- // TODO: Get the data from previous rank
- printf("Current Rank is %i\n", myRank);
- if(myRank == 1 && count !=0)
- {
- MPI_Recv(&recvBomb,1,MPI_INT,(numProcs-1) ,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
- }
- else if(myRank == 1 && count == 0)
- {
- MPI_Recv(&recvBomb,1,MPI_INT,myRank-1,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
- count = count + 1;
- }
- else
- {
- MPI_Recv(&recvBomb,1,MPI_INT,myRank-1,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
- }
- // TODO: Decrement the counter
- countDownCounter = random_dec(countDownCounter);
- if (countDownCounter > 0)
- {
- printf("Process %i has received the bomb (%i on the clock)"
- " and is still alive!\n", (myRank) , countDownCounter);
- // TODO: Pass the bomb on
- if(nextRank == 0)
- {
- nextRank = nextRank + 1;
- }
- MPI_Send(&recvBomb,1,MPI_INT,nextRank,0,MPI_COMM_WORLD);
- printf("Process %i has sent the bomb to %i "
- "\n", (myRank) , nextRank);
- }
- else
- {
- printf("Process %i lost\n", myRank);
- // TODO: Notify all processes of who the looser is
- }
- }
- looserRank = myRank - 1;
- printf("I am process %i and %i is the looser\n", myRank, looserRank);
- // TODO: Finalize MPI
- MPI_Finalize();
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement