Hello all,
I have the following simple MPI code. I was wondering if there was a
workaround for sending a dynamically allocated 2-D matrix? Currently I can
send the matrix row-by-row, however, since rows are not contiguous I cannot
send the entire matrix at once. I realize one option is to change the malloc
to act as one contiguous block but can I keep the matrix definition as below
and still send the entire matrix in one go?
Code :-
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <math.h>
void alloc_matrix(double ***x, int r, int c)
{
int i,j,n;
if ( ( *x = (double **)malloc((r)*sizeof(**x)) ) == NULL ) {
printf("memory not
allocd\n"); exit(1);
}
for(n = 0; n < r; n++) {
if ( ( (*x)[n] = (double *)malloc(c * sizeof(***x))) ==
NULL) {
printf("memory not allocd");
exit(1);
}
}
}
void clean(double ***x, int r)
{
int n;
for (n = 0; n < r; n++)
{
free((*x)[n]);
(*x)[n] = NULL;
}
free(**x);
**x = NULL;
}
int main (int argc, char **argv) {
int myrank,i, j;
FILE *f;
char name[20];
MPI_Status status;
double **a, **b;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &myrank);
if( myrank == 0 )
{
alloc_matrix(&a,3,3);
for (i=0;i<3;i++) {
for (j=0; j<3; j++)
a[i][j]=i*0.01 + j*0.01;
MPI_Send((a[i]), 3, MPI_DOUBLE, 1, 17, MPI_COMM_WORLD );
}
}
else if( myrank == 1 )
{
alloc_matrix(&b,3,3);
for (i=0;i<3;i++){
for (j=0; j<3; j++)
b[i][j]=0;
MPI_Recv((b[i]), 3 , MPI_DOUBLE, 0, 17, MPI_COMM_WORLD,
&status );
}
sprintf(name,"proc.%d",myrank);
f = fopen(name,"w");
if (myrank == 1)
{
for (i=0; i<3; i++)
for (j=0; j<3; j++)
{
fprintf(f,"%f\n", b[i][j]);
}
clean(&b,3);
}
else if( myrank == 0 ) {
clean(&a,3);
}
fclose(f);
MPI_Finalize();
}
|