MPI_Comm_split 进程分通讯域,实现各个通讯域内数据传输(N*N进程,主对角线进程的进程号的循环传送)

代码如下,前两个函数没用

#include <mpi.h>
#include<stdio.h>
#include<math.h>

int index_to_rank(int row, int col,int N) {
	return row * N + col;
}
void rank_to_index(int rank, int* row, int* col,int N) {
	*row = rank / N;
	*col = rank % N;
}
int main(int* argc, char** argv) {
	int rank, size, color, key;
	MPI_Init(&argc, &argv);
	MPI_Comm_rank(MPI_COMM_WORLD, &rank);
	MPI_Comm_size(MPI_COMM_WORLD, &size);
	MPI_Status status;
	MPI_Comm split_world;
	int row=0, col=0;
	rank_to_index(rank, &row, &col, sqrt(size));
	color = row - col;
	key = row >= col ? col : row;
	MPI_Comm_split(MPI_COMM_WORLD, color, key, &split_world);
	int buffer = rank, temp = 0;
	int diagsize=0;
	MPI_Comm_size(split_world, &diagsize);

	if (color == 0) {
		if (key == 0) {
			printf("color=%d\n", color);
			fflush(stdout);
		}
		MPI_Sendrecv(&buffer, 1, MPI_INT, (key + 1) % diagsize, 0,
			&temp, 1, MPI_INT, (key + diagsize - 1) % diagsize, 0, split_world, &status);//接收要使用key+diagsize-1,不能用key-1,否则进程号不对,会阻塞
		buffer = temp;
		printf("rank= %d, row= %d, col= %d, key= %d, buffer= %d", rank, row, col, key, buffer);
	}

	MPI_Finalize();
	return 0;
}

运行结果如下:在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

字江慕

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值