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_cyclic_shift.cpp (1712B)


      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         if (0 == rank % 2) { // even ranks send first
     22             MPI_Send(send.data(),
     23                      send.size(),
     24                      MPI_DOUBLE,
     25                      right,
     26                      123,
     27                      MPI_COMM_WORLD);
     28             MPI_Recv(recv.data(),
     29                      recv.size(),
     30                      MPI_DOUBLE,
     31                      left,
     32                      123,
     33                      MPI_COMM_WORLD,
     34                      MPI_STATUS_IGNORE);
     35         } else {
     36             MPI_Recv(recv.data(),
     37                      recv.size(),
     38                      MPI_DOUBLE,
     39                      left,
     40                      123,
     41                      MPI_COMM_WORLD,
     42                      MPI_STATUS_IGNORE);
     43             MPI_Send(send.data(),
     44                      send.size(),
     45                      MPI_DOUBLE,
     46                      right,
     47                      123,
     48                      MPI_COMM_WORLD);
     49         }
     50         out << "Rank " << rank << ": sent right 100x " << send[0]
     51             << ", received left 100x " << recv[0] << '\n';
     52         send.swap(recv);
     53     }
     54 
     55     std::cout << out.str();
     56 
     57     MPI_Finalize();
     58     return 0;
     59 }