MPI初探

刚接触学习MPI,趁热打铁写了个小程序,目的是熟悉下基本操作。程序很简单,实现了进程间的通信,其中0进程负责接收其他进程发送过来的消息,其余进程负责向0进程发送消息。

程序如下:

#include "stdio.h"
#include "string.h"
#include "mpi.h"
const int MAX=100;
int main(int agc,char *agv[])
{

	char  str[MAX];
	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);
	int x;

	if(my_rank!=0)
	{
		x=my_rank;
		sprintf(str,"hello world from process %d of %d!",my_rank,comm_size);
		MPI_Send(&str,strlen(str)+1,MPI_CHAR,0,0,MPI_COMM_WORLD);
		printf("process %d of %d is running\n",my_rank,comm_size );
	}
	else
	{
		printf("process %d of %d is running\n",my_rank,comm_size );
		for (int i = comm_size -1; i >= 1; --i)
		{
			MPI_Recv(&str,MAX,MPI_CHAR,i,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
			printf("receive %s\n",str);
		}
		
	}
	MPI_Finalize();
	return 0;
}

当设置进程数为4时,运行结果如下:

process 3 of 4 is running
process 0 of 4 is running  
receive hello world from process 3 of 4!  
receive hello world from process 2 of 4!  
receive hello world from process 1 of 4!
process 1 of 4 is running
process 2 of 4 is running

当然我们也可以更改程序,使得每个进程向比自己高一位的进程发送消息,从比自己低一位的进程接收消息。


#include "stdio.h"
#include "string.h"
#include "mpi.h"
const int MAX=100;
int main(int agc,char *agv[])
{

	char  str[MAX];
	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);
	int x;
	x=my_rank;
		
	MPI_Send(&x,1,MPI_INT,(my_rank+1)%comm_size,0,MPI_COMM_WORLD);
	printf("process %d of %d is running",my_rank,comm_size );
	MPI_Recv(&x,1,MPI_INT,(my_rank-1)%comm_size,0,MPI_COMM_WORLD,MPI_STATUS_IGNORE);
	printf("  receive %d\n",x);
	MPI_Finalize();
	return 0;
}

当设置进程个数为8时,结果如下:

process 2 of 8 is running  receive 1
process 3 of 8 is running  receive 2
process 4 of 8 is running  receive 3
process 1 of 8 is running  receive 0
process 7 of 8 is running  receive 6
process 5 of 8 is running  receive 4
process 0 of 8 is running  receive 7
process 6 of 8 is running  receive 5



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值