Advertisement
Guest User

Untitled

a guest
Feb 19th, 2019
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. #include <mpi.h>
  2. #include <thread>
  3. #include <chrono>
  4. #include <stdlib.h>
  5. #include <iostream>
  6. #include <time.h>
  7.  
  8.  
  9. using namespace std;
  10.  
  11. int main(int argc, char** argv) {
  12.  
  13. MPI_Init(NULL, NULL);
  14.  
  15. int rank;
  16. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  17.  
  18. srand (time(NULL)+rank);
  19. int wt = rand() % 5 + 1;
  20. cout <<"rank: "<< rank<< " sleep: "<< wt<<endl;
  21.  
  22.  
  23.  
  24. //here is the magic...
  25.  
  26. int * flag;
  27. MPI_Win window;
  28. int master;
  29. MPI_Win_allocate(sizeof(int), sizeof(int),MPI_INFO_NULL, MPI_COMM_WORLD, &flag, &window );
  30.  
  31.  
  32. *flag = -1;
  33. this_thread::sleep_for(chrono::seconds(wt));
  34.  
  35.  
  36. MPI_Win_lock (MPI_LOCK_EXCLUSIVE, 0, 0, window);
  37. if(rank==0)
  38. {
  39. master = *flag;
  40. }
  41. else
  42. {
  43. MPI_Get(&master, 1, MPI_INT, 0, 0, 1, MPI_INT, window);
  44. }
  45.  
  46. if(master == -1)
  47. {
  48. master = rank;
  49. MPI_Put(&rank,1,MPI_INT,0,0,1,MPI_INT,window);
  50. }
  51. MPI_Win_unlock (0, window);
  52.  
  53.  
  54. if(master == rank)
  55. {
  56. cout<< "rank: "<<rank<<". I am the master"<<endl;
  57. }
  58. else
  59. {
  60. cout<< "rank: "<<rank<<". I am the slave of "<<master<<endl;
  61. }
  62.  
  63.  
  64. MPI_Win_free( &window );
  65. MPI_Finalize();
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement