main.cc 2.2 KB

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