Advertisement
kingstertime

task6.cpp

Oct 12th, 2020
1,985
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. #include <iostream>
  2. #include "mpi.h"
  3.  
  4. int main(int argc, char** argv) {
  5.     MPI_Status status;
  6.     int rank, size, message_size;
  7.     int const count = 18;
  8.     MPI_Init(&argc, &argv);
  9.     MPI_Comm_size(MPI_COMM_WORLD, &size);
  10.     MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  11.     if (rank == 0) {
  12.         int x[count], y[count];
  13.         printf("Vector\nx y\n");
  14.         for (int i = 0; i < count; i++) {
  15.             x[i] = rand() % 100;
  16.             printf("%d ", x[i]);
  17.             y[i] = rand() % 100;
  18.             printf("%d\n", y[i]);
  19.         }
  20.         for (int i = 1; i < size; i++) {
  21.             MPI_Send(x + (i - 1) * count / (size - 1), count / (size - 1), MPI_INT, i, 1, MPI_COMM_WORLD);
  22.             MPI_Send(y + (i - 1) * count / (size - 1), count / (size - 1), MPI_INT, i, 2, MPI_COMM_WORLD);
  23.         }
  24.     } else {
  25.         MPI_Probe(0, 1, MPI_COMM_WORLD, &status);
  26.         MPI_Get_count(&status, MPI_INT, &message_size);
  27.         int* recv_x = (int*)malloc(sizeof(int) * message_size);
  28.         MPI_Recv(recv_x, message_size, MPI_INT, 0, 1, MPI_COMM_WORLD, &status);
  29.  
  30.         MPI_Probe(0, 2, MPI_COMM_WORLD, &status);
  31.         MPI_Get_count(&status, MPI_INT, &message_size);
  32.         int* recv_y = (int*)malloc(sizeof(int) * message_size);
  33.         MPI_Recv(recv_y, message_size, MPI_INT, 0, 2, MPI_COMM_WORLD, &status);
  34.  
  35.         int* z = (int*)malloc(sizeof(int) * message_size);
  36.         for (int i = 0; i < message_size; i++) {
  37.             z[i] = recv_x[i] + recv_y[i];
  38.         }
  39.         MPI_Send(z, message_size, MPI_INT, 0, 0, MPI_COMM_WORLD);
  40.     }
  41.  
  42.     if (rank == 0) {
  43.         int result[count];
  44.         int pointer = 0;
  45.  
  46.         for (int i = 1; i < size; i++) {
  47.             MPI_Probe(i, 0, MPI_COMM_WORLD, &status);
  48.             MPI_Get_count(&status, MPI_INT, &message_size);
  49.             int* z = (int*)malloc(sizeof(int) * message_size);
  50.             MPI_Recv(z, message_size, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
  51.             for (int j = 0; j < message_size; j++) {
  52.                 result[pointer] = z[j];
  53.                 pointer++;
  54.             }
  55.         }
  56.  
  57.         printf("Result z vector is : \n");
  58.         for (int i = 0; i < count; i++) {
  59.             printf("%d ", result[i]);
  60.         }
  61.         printf("\n");
  62.     }
  63.  
  64.     MPI_Finalize();
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement