rendered paste body#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <mpi.h>
#define MASTER 0
#define IS_MASTER my_id==0
typedef struct {
int cols;
int rows;
float *data;
} MATRIX;
MATRIX create_matrix(int rows, int cols) {
MATRIX m;
m.rows = rows;
m.cols = cols;
m.data = ( float * ) malloc( sizeof( float ) * rows * cols );
return m;
}
void read_matrix( char *path, MATRIX *mat ) {
int i, j;
char aux_string[50];
char rows_string[10], cols_string[10];
FILE *input_file = fopen( path, "r" );
fgets( aux_string, 50, input_file );
printf( "Leyendo la matriz: %s", aux_string );
fgets( aux_string, 50, input_file );
sscanf( aux_string, "%s %s", rows_string, cols_string );
printf( "dimensiones: %s x %s\n\n", rows_string, cols_string );
*mat = create_matrix( atoi( rows_string ), atoi( cols_string ) );
for( i = 0; i < mat->rows; i++ )
for( j = 0; j < mat->cols; j++ )
fscanf( input_file, "%f", &mat->data[i * mat->cols + j] );
}
void broadcast_matrix(MATRIX *m, int my_id) {
int rows, cols;
rows = m->rows;
cols = m->cols;
MPI_Bcast( &rows, 1, MPI_INT, MASTER, MPI_COMM_WORLD );
MPI_Bcast( &cols, 1, MPI_INT, MASTER, MPI_COMM_WORLD );
if(IS_MASTER)
MPI_Bcast( m->data, rows * cols, MPI_FLOAT, MASTER, MPI_COMM_WORLD );
else {
*m = create_matrix( rows, cols );
MPI_Bcast( m->data, rows * cols, MPI_FLOAT, MASTER, MPI_COMM_WORLD );
}
}
int main( int argc, char *argv[] ) {
MATRIX mat1, mat2;
MPI_Status status;
int total_procs, my_id;
int i, j;
/*
if(argc != 3) {
printf("Uso del programa: nombre_del_ejecutable 1ra_matriz 2da_matriz\n");
return 1;
}*/
MPI_Init( &argc, &argv );
MPI_Comm_size( MPI_COMM_WORLD, &total_procs );
MPI_Comm_rank( MPI_COMM_WORLD, &my_id );
if(IS_MASTER) {
read_matrix( "mat1", &mat1 );
read_matrix( "mat2", &mat2 );
// SHOW LA 1ra MATRIZ
for(i = 0; i < mat1.rows; i++) {
for(j = 0; j < mat1.cols; j++)
printf("%f ", mat1.data[i * mat1.cols + j]);
printf("\n");
}
printf("\n");
// SHOW LA 2da MATRIZ
for(i = 0; i < mat2.rows; i++) {
for(j = 0; j < mat2.cols; j++)
printf("%f ", mat2.data[i * mat2.cols + j]);
printf("\n");
}
}
broadcast_matrix( &mat2, my_id );
MPI_Finalize();
return 0;
}