【发布时间】:2015-11-17 15:17:32
【问题描述】:
如代码所示,我在 c 中有两个结构。经过一些输入读取和initialize_pop(parent_pop),生成了包含4个个体的parent_pop。然后我必须将每个个体发送到每个进程(4个进程)以评估并在每个进程上生成新的个体(总共还是4个个体),然后接收这 4 个新个体在主进程中形成一个名为 child_pop 的新群体。这是我的伪程序。感谢任何帮助。提前致谢。
typedef struct{
double *xreal;
int **gene;
double crowd_dist;
}
individual;
typedef struct
{
individual *ind;
}
population;
Here is the main program:
int main (int argc, char **argv)
{
population *parent_pop;
int i, my_id, num_procs;
MPI_Init(&argc, &argv);
// Find out process ID and process number //
MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
input_read();/*read input*/
initialize_pop (parent_pop);/*generate 4 individuals to form the parent_pop*/
MPI_Datatype MPI_individual;
int count = 3;
int blocklens[] = { 1, 1, 1 };
MPI_Aint disps[3];
MPI_Datatype old_types[] = { MPI_int, MPI_double, MPI_double };
disps[0] = offsetof(individual, *xreal);
disps[1] = offsetof(individual, **gene);
disps[2] = offsetof(individual, crowd_dist);
MPI_Type_struct(count, blocklens, disps, old_types, &MPI_individual);
MPI_Type_commit(&MPI_individual);
*********Part need help****************************
send each individual to each process;
*********Part need help****************************
evaluate(parent_pop);/*evaluate each individual in each process*/
genearte_new_pop(child_pop);/*generate 4 new individuals to form the child_pop*/
*********Part need help****************************
receive each individual information from the slave processes to get the child_pop in the master process
*********Part need help****************************
}
【问题讨论】:
-
我看到了一些错误:(1) 发送
int **gene并不简单,因为在分配此内存时,它不会是连续的——只有每一行在内存中是连续的。 (2) 您的类型与您的individual结构本身不匹配。应该是{MPI_double, MPI_int, MPI_double}。 (3) 您的计数不正确,因为它们必须反映数组xreal和gene中元素的实际数量(数据类型必须再次连续才能正确)。要回答您的实际问题:使用此数据类型的MPI_Send和MPI_Recv应该可以工作。 -
非常感谢。我是一个编程初学者。如果可能,请您详细说明这些(1)由于该程序中的其他功能,我必须使用**gene,那么我应该如何发送**gene? (2)计数不是派生类型的元素块数吗?它应该等于blocklens数组的大小吗? (3) 再次感谢您的回答!
-
(1) 当你第一次分配你的
gene数组时,你必须将它分配在连续的内存中(通常通过制作一维数组来完成)。如果您真的想保持程序的其余部分相同,那么最初将geneTemp分配为一维数组,并将二维数组gene的每个指针设置为对应于一维数组geneTemp的内存位置。不漂亮,但这意味着您不必更改程序的任何其他部分。 (2) 是的,通过 MPI 发送的计数应该是数组的大小。 -
谢谢!如果可能的话,请告诉我分配geneTemp和gene的基本代码。另外,*xreal怎么样,如何将这个指针指向的数组传递给其他进程?