MPI将动态2Darrays广播到其他处理器

我已经搜索了很多解释,但我想我无法弄清楚我是如何做到这种情况的。 我想做类似的事情:使用主处理器,我正在创建一个动态的2D数组。 然后我想;

1-将此arrays发送到其他处理器。 并且每个处理器打印该2Darrays2-将该arrays的一部分发送给其他人。 每个处理器将其部件打印到屏幕上。

例如; 我有2Darrays11 * 11和4个处理器。 等级0是主人。 其他人是奴隶。 对于第一种情况,我想将所有数组发送到排名1,排名2和排名3.而对于第二种情况,我想将行分享给从属。 11/3 = 3.因此,等级1需要3行,等级2需要3行,等级3需要5行。

这是我的代码:

int processorID; int numberOfProcessors; int main(int argc, char* argv[]){ MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD ,&numberOfProcessors); MPI_Comm_rank(MPI_COMM_WORLD ,&processorID); double **array; if(MASTER){ array = (double**) malloc(11*sizeof(double *)); for(i=0; i<11; i++){ array[i] = (double *) malloc(11*sizeof(double)); } for(i=0; i<11; i++){ for(j=0; j<11; j++){ array[i][j] = i*j; } } } MPI_Bcast(array, 11*11, MPI_DOUBLE, 0, MPI_COMM_WORLD); if(SLAVE){ for(i=0; i<11; i++){ for(j=0; j<11; j++){ printf("%f ", array[i][j]); } } } MPI_Finalize(); return 0; } 

根据这些链接; MPI_Bcast一个动态的2Darrays ; 我需要创建我的数组;

 if (MASTER){ array = (double**) malloc(121*sizeof(double)) for(i=0; i<11; i++){ for(j=0; j<11; j++){ array[i][j] = i*j; // this is not working. } } } 

但如果我这样做,我无法初始化数组中的每个成员。 内部循环不起作用。 我找不到任何方法来解决它。

对于我的第二个问题,我按照这个链接使用MPI在C中发送2D数组块 。 我想我需要改变if(SLAVE)的内部。 我应该为每个从处理器创建2D subArrays。 我需要使用MPI_Scatterv。 但我完全无法理解。

 int main() { ... ... MPI_Scatterv() // what must be here? if(SLAVE){ if(processorID = numberOfProcessor-1){ subArray = (double**) malloc(5*sizeof(double *)); // beacuse number of row for last processor is 5 for(i=0; i<11; i++){ array[i] = (double *) malloc(11*sizeof(double)); } } else { subArray = (double**) malloc(3*sizeof(double *)); for(i=0; i<11; i++){ array[i] = (double *) malloc(11*sizeof(double)); } } } } 

C实际上没有多维数组。 我建议将您的值存储在常规的1D缓冲区中,然后从1D值计算正确的索引。 像这样:

 double* data = (double*)malloc(sizeof(double)*11*11); // Now, to access data[i][j], simply do: data[j + i*11] = ...; // this "maps" 2D indices into 1D 

这将为您节省分层malloc -ing的所有麻烦,并且可以轻松地将其传递给MPI API。

您不能使用指针数组(您错误地调用“2D数组”),因为每个行指针都不可移植到另一个节点的地址空间。

您在线性内存分配中创建2D数组所引用的代码是完全正确的,您需要做的就是按行主顺序索引该内存,以便循环变为:

 double* array = (double*) malloc(121*sizeof(double)); if (MASTER){ for(i=0; i<11; i++){ for(j=0; j<11; j++){ array[j+i*11] = i*j; // row major indexing here } } } /* Scatter code follows */ 

您可以安全地将此类arrays分散到多个节点。