gpt4 book ai didi

c++ - MPI C 逐行发送矩阵到所有进程子进程 (MPI_COMM_SPAWN)

转载 作者:行者123 更新时间:2023-11-30 16:34:34 31 4
gpt4 key购买 nike

我有一个父进程和一个矩阵,我想为每一行创建一个子进程并向其发送相应的进程行。

父进程代码:

int tag = 0;
MPI_Status status;

int random(int n) {
return rand() % n;
}

float** generate_matrix(int n, int m) {
int i, j;
float **x;
x = (float **) malloc(m * sizeof(float));
for (i = 0; i < m; i++) {
x[i] = (float *) malloc(n * sizeof(float));
}
for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
x[i][j] = random(100);
}
}
return x;
}
int main(int argc, char** argv) {

int my_rank;
int num_procs;
MPI_Comm workercomm;
int n = 4, m = 5;
float**matrix = generate_matrix(n, m);

MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &my_rank);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

MPI_Comm_spawn("C:/Users/colegnou/workspace/worker/Debug/worker.exe",
MPI_ARGV_NULL, m,
MPI_INFO_NULL, 0, MPI_COMM_SELF, &workercomm, MPI_ERRCODES_IGNORE);

for (int i = 0; i < m; i++) {
MPI_Bcast(matrix[i], n, MPI_FLOAT, MPI_ROOT, workercomm);
}
MPI_Finalize();
return 0;
}

worker 代码:

int tag = 0;
MPI_Status status;

int main(int argc, char** argv) {

MPI_Init(&argc, &argv);
MPI_Comm parent;
MPI_Comm_get_parent(&parent);
int myid;
MPI_Comm_rank(MPI_COMM_WORLD, &myid);

int n = 4;
float*vector = (float *) malloc(n * sizeof(float));

if (parent != MPI_COMM_NULL) {
MPI_Bcast(vector, n, MPI_FLOAT, MPI_ROOT, parent);
}
printf("%d ->", myid);
for (int i = 0; i < n; i++) {
printf("%f ", vector[i]);
}
printf("\n");

MPI_Comm_free(&parent);
free(vector);
MPI_Finalize();
return 0;
}

但我希望每个子进程在矩阵中逐行打印对应的行,而不是输出是:...................................................... ......................................

  4 ->0.000000 0.000000 0.000000 0.000000
1 ->0.000000 0.000000 0.000000 0.000000
3 ->0.000000 0.000000 0.000000 0.000000
0 ->0.000000 0.000000 0.000000 0.000000
2 ->0.000000 0.000000 0.000000 0.000000

谢谢!!

最佳答案

在工作线程代码中,您应该使用 root=0 而不是 MPI_ROOT

当使用内部通信器时,请随意重新阅读MPI_Bcast()的定义 https://www.open-mpi.org/doc/v2.1/man3/MPI_Bcast.3.php

请注意,矩阵的分配不正确,您应该改为malloc(m * sizeof(float *))

您还应该在工作线程中执行m广播,除非您正在寻找MPI_Scatter()(在这种情况下,您应该分配一个连续的2D矩阵)

关于c++ - MPI C 逐行发送矩阵到所有进程子进程 (MPI_COMM_SPAWN),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49316741/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com