main.cc 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include <iostream>
  2. #include <mpi.h>
  3. #define BUFFER_SIZE 1
  4. void my_MPI_Alltoall(int *sendbuf, int *recvbuf, int count, MPI_Comm comm,
  5. int rank) {
  6. for (int i = 0; i < count; ++i) {
  7. recvbuf[rank] = sendbuf[rank];
  8. if (i == rank) {
  9. // recv from other proc
  10. for (int j = 0; j < count; ++j) {
  11. if (j != rank) {
  12. MPI_Recv(recvbuf + j, 1, MPI_INT, j, j, MPI_COMM_WORLD,
  13. MPI_STATUS_IGNORE);
  14. }
  15. }
  16. } else {
  17. // send to one proc
  18. MPI_Send(sendbuf + i, 1, MPI_INT, i, rank, MPI_COMM_WORLD);
  19. }
  20. }
  21. }
  22. int main(int argc, char *argv[]) {
  23. int rank, size;
  24. int *send_buffer;
  25. int *recv_buffer_test;
  26. int *recv_buffer_val;
  27. // MPI init
  28. MPI_Init(&argc, &argv);
  29. MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  30. MPI_Comm_size(MPI_COMM_WORLD, &size);
  31. // end MPI init
  32. send_buffer = new int[BUFFER_SIZE * size];
  33. recv_buffer_test = new int[BUFFER_SIZE * size];
  34. recv_buffer_val = new int[BUFFER_SIZE * size];
  35. // init send_buffer
  36. for (int i = 0; i < size; ++i) {
  37. send_buffer[i] = rank + size * i;
  38. }
  39. // use my_MPI_Alltoall
  40. my_MPI_Alltoall(send_buffer, recv_buffer_test, size, MPI_COMM_WORLD, rank);
  41. // use MPI_Alltoall
  42. MPI_Alltoall(send_buffer, BUFFER_SIZE, MPI_INT, recv_buffer_val, BUFFER_SIZE,
  43. MPI_INT, MPI_COMM_WORLD);
  44. // validate data
  45. bool foundErr = false;
  46. for (int i = 0; i < size; ++i) {
  47. if (recv_buffer_test[i] != recv_buffer_val[i]) {
  48. std::cout << "proc" << rank << ": "
  49. << "test[" << i << "]:" << recv_buffer_test[i] << ", val[" << i
  50. << "]:" << recv_buffer_val[i] << std::endl;
  51. foundErr = true;
  52. }
  53. }
  54. if (!foundErr) {
  55. std::cout <<"proc" << rank << ": no err found" << std::endl;
  56. }
  57. delete[] send_buffer;
  58. delete[] recv_buffer_val;
  59. delete[] recv_buffer_test;
  60. MPI_Finalize();
  61. }