/* * mpich7.c * $Id$ * * Copyright (C) 2007 Andrew Smirnoff * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * */ #include #include #include #include #include #include "mpi.h" int main(int argc, char* argv[]) { int myrank; int **a, **b; int *veca, *vecb; int *buf; int i,j,k; int n; int next; int prev; int min = 2147483647; int res; MPI_Status status; MPI_Init(&argc,&argv); MPI_Comm_rank(MPI_COMM_WORLD,&myrank); MPI_Comm_size(MPI_COMM_WORLD,&n); veca = (int *) malloc(sizeof(int) * n); buf = (int *) malloc(sizeof(int) * n); vecb = (int *) malloc(sizeof(int) * n); if (myrank == 0) { a = (int **) malloc(sizeof(int *) * n); b = (int **) malloc(sizeof(int *) * n); srand(time(0)); for (i = 0; i < n; i++) { a[i] = (int *) malloc(sizeof(int) * n); b[i] = (int *) malloc(sizeof(int) * n); for (j = 0; j < n; j++) { a[i][j] = rand() % 10; b[i][j] = rand() % 10; } } printf("a = \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("%2d ", a[i][j]); printf("\n"); } printf("b = \n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) printf("%2d ", b[i][j]); printf("\n"); } printf("Sending to processes...\n"); fflush(stdout); for (i = 1; i < n; i++) { for (j = 0; j < n; j++) { veca[j] = a[i][j]; vecb[j] = b[j][i]; } MPI_Send(veca, n, MPI_INT, i, 0, MPI_COMM_WORLD); MPI_Send(vecb, n, MPI_INT, i, 0, MPI_COMM_WORLD); } printf("Sended!\n"); fflush(stdout); for (j = 0; j < n; j++) { veca[j] = a[0][j]; vecb[j] = b[j][0]; } } else { MPI_Recv(veca, 2 * n, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); MPI_Recv(vecb, 2 * n, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); } next = myrank + 1; prev = myrank - 1; if (myrank == 0) prev = n - 1; if (myrank == n-1) next = 0; for (i = 0; i < n; i++) { res = 0; for (j = 0; j < n; j++) res += veca[j] * vecb[j] * j; if (res < min) min = res; if (i < n) { MPI_Sendrecv (vecb, n, MPI_INT, next, 0, buf, n, MPI_INT, prev, 0, MPI_COMM_WORLD, &status); for (j = 0; j < n; j++) vecb[j] = buf[j]; } } if (myrank != 0) MPI_Send(&min, 1, MPI_INT, 0, 0, MPI_COMM_WORLD); else { veca[0] = min; for (i = 1; i < n; i++) MPI_Recv(&(veca[i]), 1, MPI_INT, i, 0, MPI_COMM_WORLD, &status); printf("Result: "); for (i = 0; i < n; i++) printf("%d ", veca[i]); printf("\n"); } MPI_Finalize(); free(veca); free(buf); }