您的位置:首页 > 其它

MPI通信域划分及新通信域各进程间的点对点阻塞式通信

2017-04-02 11:58 148 查看
/*
通信域划分及新通信域各进程间的点对点阻塞式通信
*/
#include <stdio.h>
#include <mpi.h>
#define MAX_STRING 100
main (int argc, char **argv)
{
int oldrank,oldsize;            //旧进程标识,旧通信域进程总数目
int newrank,newsize;            //新进程标识,新通信域进程总数目
MPI_Comm newcomm;               //新通信域
char greeting[MAX_STRING];      //消息缓存

MPI_Init(&argc, &argv);                     //初始化操作
MPI_Comm_rank(MPI_COMM_WORLD, &oldrank);    //获取旧进程标识
MPI_Comm_size(MPI_COMM_WORLD, &oldsize);    //获取旧进程总数目

/*---------------------------------------------MPI_Comm_split详解--------------------------------------------*/
//note:
//  1.Note that, for a fixed color, the keys need not be unique. It is MPI_COMM_SPLIT's responsibility
//  to sort processes in ascending order according to this key, and to break ties in a consistent way.
//  If all the keys are specified in the same way, then all the processes in a given color will have the
//  relative rank order as they did in their parent group. (In general, they will have different ranks.)
//
//  2.Essentially, making the key value zero for all processes of a given color means that one doesn't really
//  care about the rank-order of the processes in the new communicator.
//
//  copy from:http://mpi.deino.net/mpi_functions
//函数参数:
//  MPI_Comm_split(要划分的通信域,
//  color值[color值相同的会划分为同一个子集],
//  key值[控制rank的排序,按key值升序排序, 不要设置为MPI_UNDEFINE],
//  新通信域地址)
MPI_Comm_split(MPI_COMM_WORLD,oldrank%2, oldrank/2,&newcomm);       //划分通信域MPI_COMM_DWORD到新通信域newcomm

MPI_Comm_rank(newcomm, &newrank);       //获取新的进程标识到newrank
MPI_Comm_size(newcomm, &newsize);       //获取新的进程数目到newsize
printf("old rank = %d size = %d, color = %d, key=%d, new rank = %d size = %d\n\n", oldrank, oldsize, oldrank % 2, oldrank/2, newrank, newsize);

if(0==oldrank){
sprintf_s( greeting ,100, "oldrank = %d size = %d,newrank = %d size = %d\n" , oldrank , oldsize , newrank , newsize);
MPI_Send(greeting,strlen(greeting)+1,MPI_CHAR,1,0,newcomm); //newrank=0发送到newcomm组color=0的1号进程
}else if(1==oldrank){
sprintf_s(greeting, 100, "oldrank = %d size = %d,newrank = %d size = %d\n", oldrank, oldsize, newrank, newsize);
MPI_Send(greeting,strlen(greeting)+1,MPI_CHAR,1,0,newcomm);  //newrank=0发送到newcomm组color=1的1号进程
}else if(2==oldrank){
MPI_Recv(greeting,MAX_STRING,MPI_CHAR,0,0,newcomm,MPI_STATUS_IGNORE);  //newrank=1接收newcomm组color=0的0号进程的消息
printf("receive message from %s\n", greeting);
}else if (3 == oldrank) {
MPI_Recv(greeting,MAX_STRING,MPI_CHAR,0,0,newcomm,MPI_STATUS_IGNORE);  //newrank=1接收newcomm组color=1的0号进程的消息
printf("receive message from %s\n", greeting);
}

printf("-----------------------------------------------------------------\n");

MPI_Comm_free(&newcomm);    //释放newcomm数据缓存

MPI_Finalize();     //MPI结束标识
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息