MPI_Barrier不在循环内工作

时间:2011-07-27 07:08:02

标签: c loops mpi barrier

我已经在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和循环之间是否存在冲突? (我只发现警告,以避免在不同任务中使用不同大小的循环死锁。) 如果有一个,在开始循环的新迭代之前,我该怎么做才能强制任务等待彼此? 如果没有,这段代码有什么问题?

谢谢!

1 个答案:

答案 0 :(得分:3)

它与你的循环无关。 MPI隐含的IO没有顺序化。如果你需要打印出来的顺序,你必须明确地将它们发送到一个等级,并在那里打印出来。