cs205-lecture-examples

Example codes used during Harvard CS205 lectures
git clone https://git.0xfab.ch/cs205-lecture-examples.git
Log | Files | Refs | README | LICENSE

mpi_irsend.cpp (1186B)


      1 #include <iostream>
      2 #include <mpi.h>
      3 #include <numeric>
      4 #include <vector>
      5 
      6 int main(int argc, char* argv[])
      7 {
      8     int rank;
      9     MPI_Init(&argc, &argv);
     10     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     11 
     12     // send/receive buffers
     13     constexpr int n = 1000000;
     14     std::vector<int> sendbuf(n, 1);
     15     std::vector<int> recvbuf(n);
     16 
     17     // post non-blocking receive request first
     18     MPI_Request recv_req = MPI_REQUEST_NULL;
     19     if (1 == rank) {
     20         MPI_Irecv(recvbuf.data(),
     21                   recvbuf.size(),
     22                   MPI_INT,
     23                   0,
     24                   98,
     25                   MPI_COMM_WORLD,
     26                   &recv_req);
     27     }
     28 
     29     MPI_Barrier(MPI_COMM_WORLD); // synchronize all processes
     30 
     31     if (0 == rank) {
     32         MPI_Rsend(
     33             sendbuf.data(), sendbuf.size(), MPI_INT, 1, 98, MPI_COMM_WORLD);
     34     }
     35 
     36     // Rank 0 is OK to call this because its request is NULL, the other ranks
     37     // blocks until the receive has completed.
     38     MPI_Wait(&recv_req, MPI_STATUS_IGNORE);
     39 
     40     std::cout << "Rank " << rank << ": result = "
     41               << std::accumulate(recvbuf.begin(), recvbuf.end(), 0)
     42               << std::endl;
     43 
     44     MPI_Finalize();
     45     return 0;
     46 }