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_sendrecv.cpp (1168B)


      1 #include <iostream>
      2 #include <mpi.h>
      3 #include <sstream>
      4 #include <vector>
      5 
      6 int main(int argc, char *argv[])
      7 {
      8     int rank, size;
      9     MPI_Init(&argc, &argv);
     10     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     11     MPI_Comm_size(MPI_COMM_WORLD, &size);
     12 
     13     // source and destination (periodic boundaries)
     14     const int left = (rank + size - 1) % size;
     15     const int right = (rank + size + 1) % size;
     16 
     17     std::ostringstream out;
     18     std::vector<double> send(100, rank), recv(100);
     19     for (int cycle = 0; cycle < 3; ++cycle) {
     20         out << "Cycle " << cycle << ": ";
     21         MPI_Sendrecv(send.data(),
     22                      send.size(),
     23                      MPI_DOUBLE,
     24                      right,
     25                      123,
     26                      recv.data(),
     27                      recv.size(),
     28                      MPI_DOUBLE,
     29                      left,
     30                      123,
     31                      MPI_COMM_WORLD,
     32                      MPI_STATUS_IGNORE);
     33         out << "Rank " << rank << ": sent right 100x " << send[0]
     34             << ", received left 100x " << recv[0] << '\n';
     35         send.swap(recv);
     36     }
     37 
     38     std::cout << out.str();
     39 
     40     MPI_Finalize();
     41     return 0;
     42 }