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;
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
从您提供的代码来看,您已经使用了 `MPI_Type_vector()` 函数来创建一个自定义的数据类型 `col_type` 和 `row_type`,用于将矩阵 `B` 的列和行发送到不同的进程中。但是,在使用 `MPI_Scatter()` 函数进行散播时,您似乎没有使用正确的参数传递自定义的数据类型。 在使用 `MPI_Scatter()` 函数时,第二个参数应该指定要发送的数据块的数量,而不是每个进程应该接收到的数据块的数量。因此,您应该将第二个参数设置为 `num_cols`,表示要发送的列数,而不是 `1`,表示每个进程应该接收到的列数。此外,您应该使用 `col_type` 而不是 `row_type` 来发送数据到列通信子中的进程。 以下是修改后的代码片段: ``` MPI_Comm_split(MPI_COMM_WORLD, col_color, col_key, &col_comm); MPI_Comm_split(MPI_COMM_WORLD, row_color, row_key, &row_comm); MPI_Type_vector(n, block_size, n, MPI_DOUBLE, &col_type); MPI_Type_commit(&col_type); MPI_Type_vector(block_size, n, n, MPI_DOUBLE, &row_type); MPI_Type_commit(&row_type); MPI_Scatter(&B[0][0], num_cols, col_type, &B_col[0][0], block_size * n, MPI_DOUBLE, 0, col_comm); ``` 请注意,这里的 `num_cols` 应该是矩阵 `B` 中列的数量,而不是在创建列通信子时指定的进程数。因此,您需要在代码中设置一个新的变量来存储矩阵 `B` 中的列数,并将其传递给 `MPI_Scatter()` 函数。 另外,如果您发现每个进程接收到的数据仍然不正确,那么您可能需要检查自定义数据类型的定义是否正确,并确保每个进程在接收数据时使用正确的数据类型。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

字江慕

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

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

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

打赏作者

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

抵扣说明:

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

余额充值