MPI及其全局变量

时间:2016-07-30 05:53:31

标签: c mpi

我试图重现此post中提出的问题。以下是我的代码。根据答案,由于每个进程独立运行,因此进程1中global_variable应该为0。但是,进程1也打印1000.所以在我的理解中,进程是在MPI_Init中生成的,所以如果全局变量是在MPI_Init之前定义,创建的进程将获得相同的值,对吧?我误解了这个帖子吗?

#include <stdio.h>
#include <mpi.h>

static int global_variable;

main(int argc, char **argv)
{
    int ierr, num_procs, my_id;

    global_variable = 1000;

    ierr = MPI_Init(&argc, &argv);

    /* find out MY process ID, and how many processes were started. */

    ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

    if( my_id == 0 ) {
        printf("%d\n", global_variable);
    }
    else if( my_id == 1 ) {
        printf("%d\n", global_variable);
    }

    ierr = MPI_Finalize();
}

1 个答案:

答案 0 :(得分:1)

这就是独立意味着:

#include <stdio.h>
#include <mpi.h>

static int global_variable;

int main(int argc, char **argv)
{
    int ierr, num_procs, my_id;
    ierr = MPI_Init(&argc, &argv);

    ierr = MPI_Comm_rank(MPI_COMM_WORLD, &my_id);
    ierr = MPI_Comm_size(MPI_COMM_WORLD, &num_procs);

    if (my_id == 0) {
        global_variable = 1000;
    }
    MPI_Barrier(MPI_COMM_WORLD);
    printf("%d\n", global_variable);

    ierr = MPI_Finalize();
}

此处,只有进程0更改global_variable。在您的示例中,global_variable = 1000;行不是特定于任何一个进程的,并且所有进程都将执行它。