我对 MPI 函数进行了一些测试,以了解它是如何工作的,并且使用 MPI_Barrier 得到了一个奇怪的结果:如果我在类似的代码中使用它,它会达到每个人所期望的效果
int main(int argc, char *argv[])
{
<some code>
MPI_Barrier(MPI_COMM_WORLD);
<more code>
MPI_Barrier(MPI_COMM_WORLD);
<...>
}
但是当我从循环内部调用它时,我得到随机结果。具体来说,我有以下测试代码:
#include "mpi.h"
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, rb, rank, nprocs;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&nprocs);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
i=0;
while(i<5)
{
rb=MPI_Barrier(MPI_COMM_WORLD);
printf("Itartion %d. I am %d of %d. MPIBarrierRes: %d\n", i, rank, nprocs, rb);
i++;
}
MPI_Finalize();
return 0;
}
当我运行 3 个任务时,我随机得到:
Itartion 0. I am 0 of 3. MPIBarrierRes: 0
Itartion 0. I am 2 of 3. MPIBarrierRes: 0
Itartion 0. I am 1 of 3. MPIBarrierRes: 0
Itartion 1. I am 0 of 3. MPIBarrierRes: 0
Itartion 1. I am 1 of 3. MPIBarrierRes: 0
Itartion 1. I am 2 of 3. MPIBarrierRes: 0
Itartion 2. I am 0 of 3. MPIBarrierRes: 0
Itartion 2. I am 1 of 3. MPIBarrierRes: 0
Itartion 2. I am 2 of 3. MPIBarrierRes: 0
Itartion 3. I am 0 of 3. MPIBarrierRes: 0
Itartion 3. I am 1 of 3. MPIBarrierRes: 0
Itartion 3. I am 2 of 3. MPIBarrierRes: 0
Itartion 4. I am 0 of 3. MPIBarrierRes: 0
Itartion 4. I am 1 of 3. MPIBarrierRes: 0
Itartion 4. I am 2 of 3. MPIBarrierRes: 0
这是我所期望的,或者恰恰相反:
Itartion 0. I am 2 of 3. MPIBarrierRes: 0
Itartion 1. I am 2 of 3. MPIBarrierRes: 0
Itartion 2. I am 2 of 3. MPIBarrierRes: 0
Itartion 3. I am 2 of 3. MPIBarrierRes: 0
Itartion 4. I am 2 of 3. MPIBarrierRes: 0
Itartion 0. I am 0 of 3. MPIBarrierRes: 0
Itartion 1. I am 0 of 3. MPIBarrierRes: 0
Itartion 2. I am 0 of 3. MPIBarrierRes: 0
Itartion 3. I am 0 of 3. MPIBarrierRes: 0
Itartion 4. I am 0 of 3. MPIBarrierRes: 0
Itartion 0. I am 1 of 3. MPIBarrierRes: 0
Itartion 1. I am 1 of 3. MPIBarrierRes: 0
Itartion 2. I am 1 of 3. MPIBarrierRes: 0
Itartion 3. I am 1 of 3. MPIBarrierRes: 0
Itartion 4. I am 1 of 3. MPIBarrierRes: 0
或者介于两者之间的东西,比如
Itartion 0. I am 1 of 3. MPIBarrierRes: 0
Itartion 0. I am 0 of 3. MPIBarrierRes: 0
Itartion 1. I am 0 of 3. MPIBarrierRes: 0
Itartion 0. I am 2 of 3. MPIBarrierRes: 0
Itartion 1. I am 1 of 3. MPIBarrierRes: 0
Itartion 2. I am 0 of 3. MPIBarrierRes: 0
Itartion 1. I am 2 of 3. MPIBarrierRes: 0
Itartion 2. I am 1 of 3. MPIBarrierRes: 0
Itartion 3. I am 0 of 3. MPIBarrierRes: 0
Itartion 2. I am 2 of 3. MPIBarrierRes: 0
Itartion 3. I am 1 of 3. MPIBarrierRes: 0
Itartion 4. I am 0 of 3. MPIBarrierRes: 0
Itartion 3. I am 2 of 3. MPIBarrierRes: 0
Itartion 4. I am 1 of 3. MPIBarrierRes: 0
Itartion 4. I am 2 of 3. MPIBarrierRes: 0
谁能告诉我 MPI_Barrier 和循环之间是否存在冲突? (我只发现在不同任务中使用不同大小的循环来避免死锁的警告。) 如果有的话,我该怎么做才能强制任务在开始新的循环迭代之前相互等待? 如果没有,这段代码有什么问题?
谢谢!
最佳答案
这与你的循环无关。 MPI 没有暗示 IO 的顺序。如果您需要按顺序打印,则必须明确将它们发送到一个级别,然后将它们全部打印在那里。
关于c - MPI_Barrier 不在循环内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6840625/