Advertisement
Guest User

lab 5.2 Gather not working

a guest
Dec 12th, 2019
124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <mpi.h>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. typedef struct three_args_struct {
  8.     int first;
  9.     int second;
  10.     int third;
  11. } triplet;
  12.  
  13. void buildDerivedType(MPI_Datatype* mpi_triplet_type) {
  14.     int nitems = 3;
  15.     int block_lengths[3] = { 1, 1, 1 };
  16.     MPI_Aint offsets[3];
  17.     MPI_Datatype typelist[3] = { MPI_INT, MPI_INT, MPI_INT };
  18.  
  19.     offsets[0] = offsetof(triplet, first);
  20.     offsets[1] = offsetof(triplet, second);
  21.     offsets[2] = offsetof(triplet, third);
  22.  
  23.     MPI_Type_create_struct(nitems, block_lengths, offsets, typelist, mpi_triplet_type);
  24.     MPI_Type_commit(mpi_triplet_type);
  25. }
  26.  
  27. void initializeTriplet(triplet* triplet, int rank) {
  28.     triplet->first = rank;
  29.     triplet->second = rank * rank;
  30.     triplet->third = rank * rank * rank;
  31. }
  32.  
  33. int main(int argc, char* argv[]) {
  34.     MPI_Init(&argc, &argv);
  35.     double startTime = MPI_Wtime();
  36.  
  37.     int rank;
  38.     int threads_count;
  39.  
  40.     MPI_Comm_size(MPI_COMM_WORLD, &threads_count);
  41.     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  42.     int side_threads_count = threads_count - 1;
  43.  
  44.     MPI_Comm newcomm;
  45.     int color;
  46.     color = rank % 3;
  47.     MPI_Comm_split(MPI_COMM_WORLD, color, rank, &newcomm);
  48.     int newsize;
  49.     MPI_Comm_size(newcomm, &newsize);
  50.     //cout << "newSize = " << newsize << endl;
  51.  
  52.     if (rank % 3 == 0) {
  53.         triplet sendBuf;
  54.         initializeTriplet(&sendBuf, rank);
  55.         cout << rank << ". first = " << sendBuf.first << ", second = " << sendBuf.second << ", third = " << sendBuf.third << endl;
  56.        
  57.         MPI_Datatype* mpi_newtype = new MPI_Datatype;
  58.         buildDerivedType(mpi_newtype);
  59.  
  60.         triplet* recvBuf = new triplet[newsize];
  61.         MPI_Gather(&sendBuf, 1, *mpi_newtype, recvBuf, newsize, *mpi_newtype, 0, newcomm);
  62.  
  63.         if (rank == 0) {
  64.             cout << "Printing received array: " << endl;
  65.             for (int i = 0; i < newsize; i++) {
  66.                 cout << i * 3 << " structure: first = " << recvBuf[i].first << ", second = " << recvBuf[i].second << ", third = " << recvBuf[i].third << endl;
  67.             }
  68.         }
  69.     }
  70.  
  71.     double endTime = MPI_Wtime();
  72.     double elapsed = endTime - startTime;
  73.     //cout << "Program runtime: " << elapsed << endl;
  74.     MPI_Finalize();
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement