MPI Barrier 不在循环中工作

MPI Barrier not working in loops

我目前正在使用 MPI C 库,但是使用 C++ 编码,我知道 MPI_Barrier(MPI_COMM_WORLD) 函数 会阻止调用者,直到通信器中的所有进程都调用它,如 documentation。这是我的代码,运行 4 个进程。

int WORLD_SIZE = 0;
int WORLD_RANK = 0;
{
    MPI_Init(&argc, &argv);
    MPI_Comm_size(MPI_COMM_WORLD, &WORLD_SIZE);
    MPI_Comm_rank(MPI_COMM_WORLD, &WORLD_RANK);
    MPI_Barrier(MPI_COMM_WORLD);
}
// everything works up till here
// WORLD_SIZE is 4, WORLD_RANK is the current process rank
{
    int j = 1;
    while (j <= log2(WORLD_SIZE)) {
        printf("rank%d at iteration %d\n", WORLD_RANK, j);
        MPI_Barrier(MPI_COMM_WORLD);
        j++;
    }
}
{
    MPI_Finalize();
}

程序给了我输出。

rank0 at iteration 1
rank0 at iteration 2
rank1 at iteration 1
rank1 at iteration 2
rank2 at iteration 1
rank2 at iteration 2
rank3 at iteration 1
rank3 at iteration 2

由于障碍,我期待以下内容。

rank0 at iteration 1
rank1 at iteration 1
rank2 at iteration 1
rank3 at iteration 1
rank0 at iteration 2
rank1 at iteration 2
rank2 at iteration 2
rank3 at iteration 2

感谢任何帮助。如果需要,我可以 post 更多代码。

当前的程序执行顺序真的和当前的std输出一致吗?如果没有,我怎么知道真正的执行顺序?如果是,那么我该如何正确使用屏障?

默认情况下,MPI 不会正确排序您的输出。 Barrier 语句可能工作正常,只是为每个进程而不是所有进程排序打印。