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_rsend.cpp (1072B)


      1 #include <iostream>
      2 #include <mpi.h>
      3 #include <numeric>
      4 #include <unistd.h>
      5 #include <vector>
      6 
      7 // DISCLAIMER: this code is not correct (the result of the receive is undefined)
      8 int main(int argc, char* argv[])
      9 {
     10     int rank;
     11     MPI_Init(&argc, &argv);
     12     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     13 
     14     // send/receive buffers
     15     constexpr int n = 1000000;
     16     std::vector<int> sendbuf(n, 1);
     17     std::vector<int> recvbuf(n);
     18 
     19     if (0 == rank) {
     20         MPI_Rsend(
     21             sendbuf.data(), sendbuf.size(), MPI_INT, 1, 98, MPI_COMM_WORLD);
     22     } else {
     23         // this should somewhat ensure that the receive is surely posted after
     24         // the send above
     25         sleep(10);
     26         MPI_Recv(recvbuf.data(),
     27                  recvbuf.size(),
     28                  MPI_INT,
     29                  0,
     30                  98,
     31                  MPI_COMM_WORLD,
     32                  MPI_STATUS_IGNORE);
     33     }
     34 
     35     std::cout << "Rank " << rank << ": result = "
     36               << std::accumulate(recvbuf.begin(), recvbuf.end(), 0)
     37               << std::endl;
     38 
     39     MPI_Finalize();
     40     return 0;
     41 }