mpi-sum-reduce.c 976 B

1234567891011121314151617181920212223242526272829303132333435
  1. // Quelle: Klausur vom SS 2013 am KIT bei
  2. // Prof. Dr.-Ing. Gregor Snelting
  3. void my_int_sum_reduce(int *sendbuf,
  4. int *recvbuf, int count,
  5. int root, MPI_Comm comm)
  6. {
  7. int size, rank;
  8. MPI_Comm_size(comm, &size);
  9. MPI_Comm_rank(comm, &rank);
  10. if (rank == root) {
  11. /* Initialize recvbuf with our own values. */
  12. for (int i = 0; i < count; ++i) {
  13. recvbuf[i] = sendbuf[i];
  14. }
  15. /* Receive values from every other node
  16. and accumulate. */
  17. for (int i = 0; i < size; ++i) {
  18. if (i == root)
  19. continue;
  20. int other[count];
  21. MPI_Recv(other, count, MPI_INT,
  22. i, 0, comm, MPI_STATUS_IGNORE);
  23. for (int j = 0; j < count; ++j) {
  24. recvbuf[j] += other[j];
  25. }
  26. }
  27. } else {
  28. /* Send our values to root. */
  29. MPI_Send(sendbuf, count, MPI_INT,
  30. root, 0, comm);
  31. }
  32. }