MPI C逐行向所有进程子节点发送矩阵(MPI_COMM_SPAWN)

时间:2018-03-16 09:04:58

标签: c++ c algorithm parallel-processing mpi

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

父流程代码:

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;
}

工人代码:

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

Thnaks !!

1 个答案:

答案 0 :(得分:0)

在工作人员代码中,您应使用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矩阵)