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_get_count.cpp (913B)


      1 #include <cassert>
      2 #include <iostream>
      3 #include <mpi.h>
      4 #include <string>
      5 
      6 int main(int argc, char* argv[])
      7 {
      8     assert(argc == 2); // pass some string as argument
      9     int rank;
     10     MPI_Init(&argc, &argv);
     11     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
     12 
     13     if (0 == rank) {
     14         char message[1024];
     15         MPI_Status status;
     16         MPI_Recv(message, 1024, MPI_CHAR, 1, 99, MPI_COMM_WORLD, &status);
     17 
     18         // get the count of characters
     19         int count;
     20         MPI_Get_count(&status, MPI_CHAR, &count);
     21         assert(count < 1024);
     22         message[count + 1] = '\0'; // terminating null
     23         std::cout << "Rank " << rank << " received: " << message << " ("
     24                   << count << " characters)\n";
     25     } else {
     26         const std::string message(argv[1]);
     27         MPI_Send(
     28             message.c_str(), message.size(), MPI_CHAR, 0, 99, MPI_COMM_WORLD);
     29     }
     30 
     31     MPI_Finalize();
     32     return 0;
     33 }