Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.46 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <mpi.h>
  4.  
  5. int random_dec(int current)
  6. {
  7. int retVal = current - random()%10;
  8. return (retVal > 0) ? retVal : 0;
  9. }
  10.  
  11. int main(int argc, char **argv)
  12. {
  13. int myRank, numProcs,bomb, recvBomb;
  14. bomb = 10;
  15. // TODO: Initialize MPI and obtain process identity
  16. MPI_Init(&argc, &argv);
  17. MPI_Comm_rank(MPI_COMM_WORLD, &myRank);
  18. MPI_Comm_size(MPI_COMM_WORLD, &numProcs);
  19. // Rank-specific initialization of the random number generator
  20. srandom(MPI_Wtime() + myRank*100);
  21.  
  22. int nextRank = (myRank + 1) % numProcs;
  23. int looserRank = -1;
  24.  
  25. int countDownCounter = 50;
  26.  
  27. // Rank 0 reads the initial timer value and starts the bomb
  28. if (myRank == 0)
  29. {
  30. if (argc > 1)
  31. {
  32. countDownCounter = atoi(argv[1]);
  33. if (countDownCounter <= 0) exit(1);
  34. }
  35. printf("Counting down from %i\n", countDownCounter);
  36. printf("Next Rank is %i\n", nextRank);
  37. MPI_Send(&bomb,1,MPI_INT,nextRank,0,MPI_COMM_WORLD);
  38. // TODO: Throw the bomb in
  39. }
  40. else
  41. {
  42. int count = 0;
  43. int data;
  44.  
  45. // TODO: Implement a loop that runs until the counter hits 0
  46. while(countDownCounter > 0){
  47. // TODO: Get the data from previous rank
  48. printf("Current Rank is %i\n", myRank);
  49.  
  50. if(myRank == 1 && count !=0)
  51. {
  52. MPI_Recv(&recvBomb,1,MPI_INT,(numProcs-1) ,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  53. }
  54. else if(myRank == 1 && count == 0)
  55. {
  56. MPI_Recv(&recvBomb,1,MPI_INT,myRank-1,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  57. count = count + 1;
  58. }
  59. else
  60. {
  61. MPI_Recv(&recvBomb,1,MPI_INT,myRank-1,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
  62. }
  63.  
  64.  
  65. // TODO: Decrement the counter
  66. countDownCounter = random_dec(countDownCounter);
  67. if (countDownCounter > 0)
  68. {
  69. printf("Process %i has received the bomb (%i on the clock)"
  70. " and is still alive!\n", (myRank) , countDownCounter);
  71. // TODO: Pass the bomb on
  72. if(nextRank == 0)
  73. {
  74. nextRank = nextRank + 1;
  75. }
  76. MPI_Send(&recvBomb,1,MPI_INT,nextRank,0,MPI_COMM_WORLD);
  77. printf("Process %i has sent the bomb to %i "
  78. "\n", (myRank) , nextRank);
  79. }
  80. else
  81. {
  82. printf("Process %i lost\n", myRank);
  83. // TODO: Notify all processes of who the looser is
  84. }
  85. }
  86. looserRank = myRank - 1;
  87. printf("I am process %i and %i is the looser\n", myRank, looserRank);
  88.  
  89. // TODO: Finalize MPI
  90. MPI_Finalize();
  91. return 0;
  92. }
  93.  
  94. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement