Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <mpi.h>
- #include <omp.h>
- #define N 3
- int main(int argc, char *argv[]){
- int size, rank, sum = 0, result = 0, i, j, cij, recv_rank;
- int row[N], col[N];
- int a [N][N] = {1,2,3,
- 4,5,6,
- 7,8,9};
- int b [N][N] = {1,2,3,
- 4,5,6,
- 7,8,9};
- int c [N][N]; //Result {30,36,42,66,81,96,102,126,150}
- MPI_Datatype mytype;
- MPI_Status status;
- MPI_Init(NULL, NULL);
- MPI_Comm_size(MPI_COMM_WORLD, &size);
- MPI_Comm_rank(MPI_COMM_WORLD, &rank);
- if(size != (N*N)){
- printf("Número de processos diferente da ordem da matriz!!!\n");
- exit(0);
- }
- if(rank == 0){
- printf("\nMatriz A\n");
- for(i = 0; i < N; i++){
- for(j = 0; j < N; j++){
- printf("[%d]\t", a[i][j]);
- }
- printf("\n");
- }
- printf("\nMatriz B\n");
- for(i = 0; i < N; i++){
- for(j = 0; j < N; j++){
- printf("[%d]\t", b[i][j]);
- }
- printf("\n");
- }
- int _ij;
- MPI_Type_vector(N, 1, N, MPI_INT, &mytype);
- MPI_Type_commit(&mytype);
- for(i = 0; i < N; i++){
- for(j = 0; j < N; j++){
- _ij = i*N+j;
- if((_ij)!=0){
- MPI_Send(&a[i][0], N, MPI_INT, _ij, 0, MPI_COMM_WORLD);
- MPI_Send(&b[0][j], 1, mytype, _ij, 0, MPI_COMM_WORLD);
- }
- }
- col[i] = b[0][i];
- row[i] = a[i][0];
- }
- /*for(i = 0; i < N; i++){
- printf("r = [%d]\n", row[i]);
- printf("c = [%d]\n", col[i]);
- }*/
- //Recv 1 to n-1 processos
- for (i = 1; i < size; i++){
- MPI_Recv(&cij, 1, MPI_INT, i, 0, MPI_COMM_WORLD, &status);
- c[(i/N)][(i%N)] = cij;
- }
- #pragma omp parallel reduction (+: sum) num_threads(N)
- {
- int thread_number = omp_get_thread_num();
- sum = (row[thread_number] * col[thread_number]);
- }
- c[0][0] = sum;
- printf("\nResult: \n");
- for(i = 0; i < N; i++){
- for(j = 0; j < N; j++){
- printf("[%d]\t", c[i][j]);
- }
- printf("\n");
- }
- printf("\n");
- } else {
- // 1 até n-1 processos
- //printf("My Rank %d\n",rank);
- MPI_Recv(&row, N, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
- MPI_Recv(&col, N, MPI_INT, 0, 0, MPI_COMM_WORLD, &status);
- /*for(i = 0; i < N; i++){
- printf("My Rank %d r = [%d]\n", rank, row[i]);
- }
- for(i = 0; i < N; i++){
- printf("My Rank %d c = [%d]\n", rank, col[i]);
- }*/
- #pragma omp parallel reduction (+: sum) num_threads(N)
- {
- int thread_number = omp_get_thread_num();
- sum = (row[thread_number] * col[thread_number]);
- }
- //printf("From Rank %d c[%d][%d] = %d\n", rank, (rank/N),(rank%N), sum);
- MPI_Send(&sum, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
- }
- MPI_Finalize();
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement