MPI聚合通信之MPI_Barrier函数

MPI_Barrier函数 用于一个通信子中所有进程的同步,调用函数时进程将处于等待状态,直到通信子中所有进程 都调用了该函数后才继续执行。

如:

#include "stdio.h"
#include "string.h"
#include "mpi.h"

int main(int agc,char *agv[])
{

	
	int comm_size;
	int my_rank;

	MPI_Init(&agc,&agv);
	MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
	for(int i=0;i<5;i++)
		printf("process %d: %d\n",my_rank,i);
	printf("waiting.....\n");
	//MPI_Barrier(MPI_COMM_WORLD);
	for(int i=5;i<10;i++)
		printf("process %d: %d\n",my_rank,i);
	
	MPI_Finalize();
	return 0;
}

编译运行结果为:

process 3: 0
process 3: 1
process 3: 2
process 3: 3
process 3: 4
waiting.....
process 3: 5
process 3: 6
process 3: 7
process 3: 8
process 3: 9
process 0: 0
process 0: 1
process 0: 2
process 0: 3
process 0: 4
waiting.....
process 0: 5
process 0: 6
process 0: 7
process 0: 8
process 0: 9
process 1: 0
process 1: 1
process 1: 2
process 1: 3
process 1: 4
waiting.....
process 1: 5
process 1: 6
process 1: 7
process 1: 8
process 1: 9
process 2: 0
process 2: 1
process 2: 2
process 2: 3
process 2: 4
waiting.....
process 2: 5
process 2: 6
process 2: 7
process 2: 8
process 2: 9

可以看到进程直接将0-9打印出来,中间并没有等待。现在将MPI_Barrier的注释去掉,即:

#include "stdio.h"
#include "string.h"
#include "mpi.h"

int main(int agc,char *agv[])
{

	
	int comm_size;
	int my_rank;

	MPI_Init(&agc,&agv);
	MPI_Comm_size(MPI_COMM_WORLD,&comm_size);
	MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);
	for(int i=0;i<5;i++)
		printf("process %d: %d\n",my_rank,i);
	printf("waiting.....\n");
	MPI_Barrier(MPI_COMM_WORLD);
	for(int i=5;i<10;i++)
		printf("process %d: %d\n",my_rank,i);
	
	MPI_Finalize();
	return 0;
}

打印输出如下:

process 3: 0
process 3: 1
process 3: 2
process 3: 3
process 3: 4
waiting.....
process 0: 0
process 0: 1
process 0: 2
process 0: 3
process 0: 4
waiting.....
process 1: 0
process 1: 1
process 1: 2
process 1: 3
process 1: 4
waiting.....
process 2: 0
process 2: 1
process 2: 2
process 2: 3
process 2: 4
waiting.....
process 1: 5
process 1: 6
process 1: 7
process 1: 8
process 1: 9
process 3: 5
process 3: 6
process 3: 7
process 3: 8
process 3: 9
process 0: 5
process 0: 6
process 0: 7
process 0: 8
process 0: 9
process 2: 5
process 2: 6
process 2: 7
process 2: 8
process 2: 9

可以看出来进程在输出0-4之后等待其它进程完成打印0-4操作之后,再打印5-9.

你可能感兴趣的:(并行计算)