代码如下,前两个函数没用
#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;
}
运行结果如下: