Skip to content

Instantly share code, notes, and snippets.

@lazarljubenovic
Created June 17, 2017 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazarljubenovic/31253c5f4cd7a3c7e7200ae182eca684 to your computer and use it in GitHub Desktop.
Save lazarljubenovic/31253c5f4cd7a3c7e7200ae182eca684 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <mpi.h>
#define W MPI_COMM_WORLD
#define n 4
void printArray(int size, int array[size], int rank) {
for (int i = 0; i < size; i++) {
if (rank == -1) printf("%02d ", array[i]);
else printf("{%d}%02d ", rank, array[i]);
}
printf("\n");
}
void printMatrix(int rows, int cols, int matrix[rows][cols], int rank) {
for (int i = 0; i < rows; i++) {
printArray(cols, matrix[i], rank);
}
}
int main(int argc, char** argv) {
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_rank(W, &rank);
MPI_Comm_size(W, &size);
int A[n][n], B[n][n] = {0};
// Inicijalizacija
if (rank == 0) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
A[i][j] = 10 * (i + 1) + j + 1;
}
}
}
// Nizovi [1, ..., n] i [n, ..., 1]
// za duzine blokova matrica
int bLensUpper[n], bLensLower[n];
for (int i = 0; i < n; bLensLower[i++] = i);
for (int i = 0; i < n; bLensUpper[i++] = n + 1 - i);
// Nizovi za rastuci i opadajuci displacement
int disUpper[n], disLower[n];
for (int i = 0, j = 0; i < n; disLower[i++] = j++ * n);
for (int i = 0, j = 0; i < n; disUpper[i++] = j++ * (n + 1));
// Tipovi
MPI_Datatype MPI_UPPER, MPI_LOWER;
MPI_Type_indexed(n, bLensUpper, disUpper, MPI_INT, &MPI_UPPER);
MPI_Type_indexed(n, bLensLower, disLower, MPI_INT, &MPI_LOWER);
MPI_Type_commit(&MPI_UPPER);
MPI_Type_commit(&MPI_LOWER);
if (rank == 0) {
MPI_Send(A, 1, MPI_UPPER, 1, 0, W);
} else {
MPI_Recv(B, 1, MPI_LOWER, 0, 0, W, MPI_STATUS_IGNORE);
}
if (rank == 0) {
printf("\nA\n");
printMatrix(n, n, A, -1);
}
MPI_Barrier(W);
if (rank == 1) {
printf("\nB\n");
printMatrix(n, n, B, -1);
}
MPI_Finalize();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment