MPI的MPI_Barrier()和MPI_Finalize()函数的正确使用方法?
//代码和注释都来自网上,所以注释的内容并不一定正确!
#include "mpi.h"
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]){
int myid; // 当前进程的编号
int numprocs; // 当前进程的名称
int namelen;
char processor_name[MPI_MAX_PROCESSOR_NAME];
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&myid);
MPI_Get_processor_name(processor_name,&namelen);
int i;
for(i=0; i<4; ++i){
printf("I'm %d, sending %d\n",myid,i);
if(1 == myid && 0 == i){
MPI_Barrier(MPI_COMM_WORLD); //进程0将一直等待,直到其他并行进程执行结束
}
}
printf("I'm %d, I am waiting.\n",myid);
MPI_Finalize(); //由于未执行MPI_Finalize,进程0无法感知到其他进程已退出
printf("I'm %d, I finished here.\n",myid);
return 0;
}
运行时会停在这里MPI_Finalize()之前?
air:~ wkl$ mpirun -np 3 ./a.out
I'm 0, sending 0
I'm 0, sending 1
I'm 0, sending 2
I'm 0, sending 3
I'm 0, I am waiting.
I'm 1, sending 0
I'm 2, sending 0
I'm 2, sending 1
I'm 2, sending 2
I'm 2, sending 3
I'm 2, I am waiting.
如果删除中间的循环则会正常结束所有进程退出,如下:
air:~ wkl$ mpirun -np 3 ./a.out
I'm 0, I am waiting.
I'm 2, I am waiting.
I'm 1, I am waiting.
I'm 2, I finished here.
I'm 0, I finished here.
I'm 1, I finished here.
air:~ wkl$
关于
MPI_Finalize()
,它到底做了什么,
MPI_COMM_WORLD
中只要有进程没有执行到这里,它就会阻止所有相关的进程的退出? 还有即使
MPI_Finalize()
执行后,进程似乎并没有真正结束,它后面的
printf
语句还在每个进程中执行,为什么?
悲鸣de哀嚎
9 years, 9 months ago