Advertisement
Guest User

Untitled

a guest
Feb 14th, 2020
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.63 KB | None | 0 0
  1. /*
  2. * Copyright (c) 2004-2006 The Trustees of Indiana University and Indiana
  3. * University Research and Technology
  4. * Corporation. All rights reserved.
  5. * Copyright (c) 2006 Cisco Systems, Inc. All rights reserved.
  6. *
  7. * Simple ring test program in C.
  8. */
  9.  
  10. #include <stdio.h>
  11. #include "mpi.h"
  12.  
  13. int main(int argc, char *argv[])
  14. {
  15. int rank, size, next, prev, message, tag = 201;
  16.  
  17. /* Start up MPI */
  18.  
  19. MPI_Init(&argc, &argv);
  20. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  21. MPI_Comm_size(MPI_COMM_WORLD, &size);
  22.  
  23. /* Calculate the rank of the next process in the ring. Use the
  24. modulus operator so that the last process "wraps around" to
  25. rank zero. */
  26.  
  27. next = (rank + 1) % size;
  28. prev = (rank + size - 1) % size;
  29.  
  30. /* If we are the "master" process (i.e., MPI_COMM_WORLD rank 0),
  31. put the number of times to go around the ring in the
  32. message. */
  33.  
  34. if (0 == rank) {
  35. message = 10;
  36.  
  37. printf("Process 0 sending %d to %d, tag %d (%d processes in ring)\n",
  38. message, next, tag, size);
  39. MPI_Send(&message, 1, MPI_INT, next, tag, MPI_COMM_WORLD);
  40. printf("Process 0 sent to %d\n", next);
  41. }
  42.  
  43. /* Pass the message around the ring. The exit mechanism works as
  44. follows: the message (a positive integer) is passed around the
  45. ring. Each time it passes rank 0, it is decremented. When
  46. each processes receives a message containing a 0 value, it
  47. passes the message on to the next process and then quits. By
  48. passing the 0 message first, every process gets the 0 message
  49. and can quit normally. */
  50.  
  51. while (1) {
  52. MPI_Recv(&message, 1, MPI_INT, prev, tag, MPI_COMM_WORLD,
  53. MPI_STATUS_IGNORE);
  54. rank = next;
  55. next = (rank + 1) % size;
  56. prev = (rank + size - 1) % size;
  57.  
  58. while (message!=0) {
  59. MPI_Send(&message, 1, MPI_INT, next, tag, MPI_COMM_WORLD);
  60. printf("Process %d sending %d to %d, tag %d (%d processes in ring)\n", rank, message, next, tag, size);
  61. --message;
  62. printf("Process %d decremented value: %d\n", rank, message);
  63. }
  64.  
  65. if (0 == message) {
  66. printf("Process %d exiting\n", rank);
  67. break;
  68. }
  69. }
  70.  
  71. /* The last process does one extra send to process 0, which needs
  72. to be received before the program can exit */
  73.  
  74. if (0 == rank) {
  75. MPI_Recv(&message, 1, MPI_INT, prev, tag, MPI_COMM_WORLD,
  76. MPI_STATUS_IGNORE);
  77. }
  78.  
  79. /* All done */
  80.  
  81. MPI_Finalize();
  82. return 0;
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement