刚接触学习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