我正在尝试使用 MPI 集体通信 MPI_Scatter 和 MPI_Gather 在C语言中将两个矩阵相乘。 / p>
我的代码以正确的结果执行,但是当我在MPI_Scatter之后测试进程 时,我在每个进程上得到零。
因此,我认为 MPI_Scatter 和 MPI_Gather 中的 sendcount 和 recevecount 参数存在问题功能。
感谢您的帮助:)
// matrix multiplication using MPI_Scatter/MPI_Gather
#include <stdio.h>
#include <stdlib.h>
#include "mpi.h"
#define N 10
int main(int argc, char *argv[])
{
int a[N][N], b[N][N], c[N][N], r1, c1, r2, c2, i, j, k, rank, size;
MPI_Init (&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
// min number of processes must be 2
if(size < 2){
fprintf(stderr, "Number of processes must be min 2 for %s\n", argv[0]);
MPI_Abort(MPI_COMM_WORLD, 1);
}
// if rank of process is zero, initialize matrix a and b
if(rank == 0){
printf("Insert number of rows and columns for matrix a: ");
scanf("%d %d", &r1, &c1);
printf("Insert number of rows and columns for matrix b: ");
scanf("%d %d",&r2, &c2);
// If the number of columns of matrix a isn't equal to the number of rows of matrix b
// ask user to insert again number of rows and columns
while (c1!=r2){
printf("Error! number of columns of matrix a isn't equal to number of rows of matrix b\n\n");
printf("Enter rows and column for matrix a: ");
scanf("%d %d", &r1, &c1);
printf("Enter rows and column for matrix b: ");
scanf("%d %d",&r2, &c2);
}
// Enter elements of matrix a
printf("\nEnter elements of matrix a:\n");
for(i = 0; i < r1; ++i){
for(j = 0; j < c1; ++j){
printf("Enter elements of matrix a%d%d: ",i+1, j+1);
scanf("%d", &a[i][j]);
}
}
// Enter elements of matrix b
printf("\nEnter elements of matrix b:\n");
for(i = 0; i < r2; ++i){
for(j = 0; j < c2; ++j){
printf("Enter elements of matrix b%d%d: ",i+1, j+1);
scanf("%d",&b[i][j]);
}
}
}
// send one row of matrix a to every process in the group
MPI_Scatter(a, N*N/size, MPI_INT, a, N*N/size, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Bcast(b, N*N, MPI_INT, 0, MPI_COMM_WORLD);
for(i=0; i<r1; ++i){
for(j=0; j<c2; ++j){
// initialization of matrix c(result matrix)
c[i][j]=0;
for(k=0; k<c1; ++k)
c[i][j]+= a[i][k]*b[k][j]; // multiplication of matrix a and matrix b, save result in matrix c
}
}
MPI_Gather(c, N*N/size, MPI_INT, c, N*N/size, MPI_INT, 0, MPI_COMM_WORLD);
// print result
if(rank == 0){
printf("\nResult of matrix multiplication:\n");
for(i = 0; i < r1; ++i){
for(j = 0; j < c2; ++j){
printf("%d ", c[i][j]);
if(j == c2-1){
printf("\n\n");
}
}
}
}
MPI_Finalize();
}