MPI Scatter:散布一个double

时间:2016-04-19 14:26:30

标签: c++ mpi

我有一个double类型的指针指向12个double类型的元素,我可以像这样打印它们。

void printArray(double *array, int size) {
    int i;
    for (i = 0; i < size; i++) {
        printf("%f\n", array[i]);
    }
}

然后我通过printArray(X,12)打印我的代码中的值,显示:

-1.000000
-0.909091
1.000000
-1.000000
-0.909091
1.000000
-1.000000
-0.909091
1.000000
-1.000000
-0.909091
1.000000

我正在尝试将这些元素分散为每个进程4个元素,总共3个进程,例如将进程0作为值:

-1.000000
-0.909091
1.000000
-1.000000 

流程2有:

 -0.909091
1.000000
-1.000000
-0.909091

等然后对这些子矩阵进行一些处理,然后将它们乘以2,然后将结果返回到根进程。为此,我尝试研究以下Scatter a Matrix - MPIHow are MPI_Scatter and MPI_Gather used from C?。我尝试按如下方式实现它:

int count = 4; //number of rows for submatrix
int blocklength = 1; //number of columns for submatrix
int stride = 4; //width of the submatrix

double *Adata = X;
double *localdata;
int size, rank;
int strip_size, A_row, A_col;
double *strip_A = NULL; //used to store all the 
                        //results from gather operation size 12
double *stripdata; // used to store submatrices 
                   //   or vectors of size 4 x 1
MPI_Datatype strip;
int i, j;

MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);

A_row = 4;
A_col = 1;
strip_size = 4; // total no. of elements should be divided based on no of processes.
                //For this example it is 4 (number of elements(12) / processes(3).

if (rank == 0) {
    printf("Processor %d has data: \n", rank);
    printArray(Adata, 12);
}

/* Broadcasting the  strip size*/
MPI_Bcast(&strip_size, 1, MPI_INT, 0, MPI_COMM_WORLD);

/* defining a datatype for sub-matrix */
/*MPI_Type_vector(int count = 3,
 int blocklength = 1,
 int stride = 3,
 MPI_Datatype oldtype = MPI_DOUBLE ,
 MPI_Datatype *newtype)*/

MPI_Type_vector(count, blocklength, stride, MPI_DOUBLE, &strip);
MPI_Type_commit(&strip);

 //4 rows 1 column .
 //Assign sufficient memory for vectors.
 stripdata = (double *) malloc(sizeof(double) * A_row * A_col);

// assign suffiecient memory to hold end data
strip_A = (double *) malloc(size * sizeof(double) * 12); 

//localdata at each node 4 rows 1 column
localdata = (double *) malloc(sizeof(double) * 4 *1); 

/*int MPI_Scatter(const void *sendbuf = Adata, int sendcount = 1, MPI_Datatype sendtype = strip,
 void *recvbuf = strip_A, int recvcount = 1, MPI_Datatype recvtype = strip, int root = 0,
 MPI_Comm comm = MPI_COMM_WORLD)
 * */

MPI_Scatter(Adata, 1, strip, &stripdata, 1, strip, 0, MPI_COMM_WORLD);

MPI_Type_free(&strip);
free(strip_A);
free(stripdata);
if (rank == 0) {
    free(Adata);
}

但是,如果我尝试使用mpirun -np 3 ./test来运行此操作,则会出现分段错误。我相信这是因为一些指针或者其他东西是不正确的。我是mpi的新手。有人可以帮助散布(double *)指针所指向的值,做一些简单的计算,然后用一个易于理解的例子将结果返回到root吗?

0 个答案:

没有答案