fork download
  1. #include <mpi.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5.  
  6. // size of array
  7. #define n 10
  8.  
  9. int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
  10.  
  11. // Temporary array for slave process
  12. int a2[1000];
  13.  
  14. int main(int argc, char* argv[])
  15. {
  16.  
  17. int pid, np,elements_per_process,n_elements_recieved;
  18. // np -> no. of processes
  19. // pid -> process id
  20.  
  21. MPI_Status status;
  22.  
  23. // Creation of parallel processes
  24. MPI_Init(&argc, &argv);
  25.  
  26. // find out process ID,
  27. // and how many processes were started
  28. MPI_Comm_rank(MPI_COMM_WORLD, &pid);
  29. MPI_Comm_size(MPI_COMM_WORLD, &np);
  30.  
  31. // master process
  32. if (pid == 0)
  33. {
  34. int index,i;
  35. elements_per_process = n / np;
  36.  
  37. // check if more than 1 processes are run
  38. if (np > 1)
  39. {
  40. // distributes the portion of array
  41. // to child processes to calculate
  42. // their partial sums
  43. for (i = 1; i < np - 1; i++)
  44. {
  45. index = i * elements_per_process;
  46.  
  47. MPI_Send(&elements_per_process,1, MPI_INT, i, 0,MPI_COMM_WORLD);
  48. MPI_Send(&a[index],elements_per_process,MPI_INT, i, 0,MPI_COMM_WORLD);
  49. }
  50.  
  51. // last process adds remaining elements
  52. index = i * elements_per_process;
  53. int elements_left = n - index;
  54.  
  55. MPI_Send(&elements_left,1, MPI_INT,i, 0,MPI_COMM_WORLD);
  56. MPI_Send(&a[index],elements_left,MPI_INT, i, 0,MPI_COMM_WORLD);
  57. }
  58.  
  59. // master process add its own sub array
  60. int sum = 0;
  61.  
  62. for (i = 0; i < elements_per_process; i++)
  63. sum += a[i];
  64.  
  65. // collects partial sums from other processes
  66. int tmp;
  67.  
  68. for (i = 1; i < np; i++)
  69. {
  70. MPI_Recv(&tmp, 1, MPI_INT,MPI_ANY_SOURCE, 0,MPI_COMM_WORLD,&status);
  71.  
  72. int sender = status.MPI_SOURCE;
  73. sum += tmp;
  74. }
  75.  
  76. // prints the final sum of array
  77. printf("Sum of array is : %d\n", sum);
  78. }
  79.  
  80. // slave processes
  81. else
  82. {
  83. MPI_Recv(&n_elements_recieved,1, MPI_INT, 0, 0,MPI_COMM_WORLD,&status);
  84.  
  85. // stores the received array segment
  86. // in local array a2
  87. MPI_Recv(&a2, n_elements_recieved,MPI_INT, 0, 0,MPI_COMM_WORLD,&status);
  88.  
  89. // calculates its partial sum
  90. int partial_sum = 0;
  91.  
  92. for (int i = 0; i < n_elements_recieved; i++)
  93. partial_sum += a2[i];
  94.  
  95. // sends the partial sum to the root process
  96. MPI_Send(&partial_sum, 1, MPI_INT,0, 0, MPI_COMM_WORLD);
  97. }
  98.  
  99. // cleans up all MPI state before exit of process
  100. MPI_Finalize();
  101.  
  102. return 0;
  103. }
  104.  
Success #stdin #stdout #stderr 0.28s 40692KB
stdin
Standard input is empty
stdout
Standard output is empty
stderr
Error: unexpected '/' in "/"
Execution halted