Advertisement
Guest User

Untitled

a guest
Jan 19th, 2017
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. #include <mpi.h>
  2. #include <math.h>
  3. #include <time.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6.  
  7. #define TOL 1E-10
  8. #define WIDTH 10
  9.  
  10. #define FMIN 5000.0
  11. #define FMAX 9999.0
  12.  
  13. int main(int argc, char** argv) {
  14. double A, diff, prev, temp;
  15. int world_rank, world_size, row, col, neighbors[4], lflag, gflag, i;
  16.  
  17. srand(time(NULL));
  18.  
  19. diff = 0;
  20. lflag = 0;
  21. gflag = 0;
  22. A = 999999.99;
  23. // A = FMIN + ((double) rand() / RAND_MAX) * (FMAX - FMIN);
  24.  
  25. MPI_Init(NULL, NULL);
  26. MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
  27. MPI_Comm_size(MPI_COMM_WORLD, &world_size);
  28.  
  29. row = world_rank / WIDTH;
  30. col = world_rank % WIDTH;
  31.  
  32. neighbors[0] = (row == 0) ? -1 : (row - 1) * WIDTH + col; // North
  33. neighbors[1] = (col == 0) ? -1 : row * WIDTH + (col - 1); // West
  34. neighbors[2] = (col == (WIDTH - 1)) ? -1 : row * WIDTH + (col + 1); // East
  35. neighbors[3] = (row == (WIDTH - 1)) ? -1 : (row + 1) * WIDTH + col; // South
  36.  
  37. MPI_Barrier(MPI_COMM_WORLD);
  38.  
  39. while (1) {
  40. prev = A;
  41.  
  42. for (i = 0; i < 4; ++i) {
  43. if (neighbors[i] >= 0) {
  44. MPI_Send(&A, 1, MPI_DOUBLE, neighbors[i], 0, MPI_COMM_WORLD);
  45. }
  46. }
  47.  
  48. for (i = 0; i < 4; ++i) {
  49. if (neighbors[i] >= 0) {
  50. MPI_Recv(&temp, 1, MPI_DOUBLE, neighbors[i], 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  51. A += temp;
  52. }
  53. }
  54.  
  55. A *= 0.2;
  56. diff = fabs(A - prev);
  57. lflag = (diff < TOL);
  58.  
  59. MPI_Barrier(MPI_COMM_WORLD);
  60. MPI_Allreduce(&lflag, &gflag, 1, MPI_INT, MPI_SUM, MPI_COMM_WORLD);
  61. MPI_Barrier(MPI_COMM_WORLD);
  62.  
  63. if (gflag > 0) {
  64. break;
  65. }
  66. }
  67.  
  68. printf("diff at A[%d, %d] = %.32f\n", row, col, diff);
  69.  
  70. MPI_Barrier(MPI_COMM_WORLD);
  71. MPI_Finalize();
  72.  
  73. return EXIT_SUCCESS;
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement