【发布时间】:2011-05-21 14:22:36
【问题描述】:
我正在尝试在 C 中使用 MPI 进行矩阵乘法。(c
我在 4 个节点上运行以下代码。所有矩阵的大小都是 8*8。
(num of rows in a matrix % num of nodes == 0)
矩阵 b[][] 被广播,因此所有节点都获得相同的副本。对于矩阵 a[][],我只想发送每个节点所需的行集,而不是广播。
但是当我运行以下代码并在 MPI_Recv() 工作节点打印 0 而不是在主节点中分配的值之后打印矩阵 a[][] 时。
你能指出我在这里做错了什么吗?
#include <stdio.h>
#include "mpi.h"
#include "matrix.c" // matrix definitions and matrix operation functions are here
int main(int argc, char *argv[])
{
MPI_Status status;
int num, rank, size, tag, high,low,i;
int offset, tmphigh,rows;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
rows=MAX/size; // MAX is the length(=height) of the matrices
tag = 201;
low=rank*rows;
high=low+rows;
if (rank == 0) {
fillMatrix(b,MAX);
fillMatrix(a,MAX);
}
MPI_Bcast(&b[0][0],MAX*MAX,MPI_INT,0,MPI_COMM_WORLD);
if(rank==0){
for(i=1;i<size;i++){
offset=i*rows;
MPI_Send(&a[offset][0],rows*MAX,MPI_INT,i,tag,MPI_COMM_WORLD);
}
}else{
MPI_Recv(&a[low][0],rows*MAX,MPI_INT,0,tag,MPI_COMM_WORLD,&status);
}
printMatrix(a,MAX);
MPI_Finalize();
return 0;
}
这是矩阵的创建方式
int a[MAX][MAX], b[MAX][MAX], c[MAX][MAX];
int len; //(edited after Jeremy W. Sherman's comment )
//this was the reason that caused this problem. changing this to int len=MAX; solved the problem
void fillMatrix(int (*matrix)[len], int len){
int i=0,j=0;
for(i=0;i<len;i++){
for(j=0;j<len;j++){
matrix[i][j]=j;
}
}
//printMatrix(matrix,len);
}
谢谢。
【问题讨论】:
-
b的广播是否按预期工作?您能告诉我们 a[][] 和 b[][] 是如何创建的吗?
-
是的 b 工作正常。我只是为所有矩阵分配了几个值