MPI_Scatter-无法正常工作 [英] MPI_Scatter - not working as expected

查看:184
本文介绍了MPI_Scatter-无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MPI编写我的第一个程序,但是我很难尝试使用MPI_Scatter将数据正确发送到其他进程,对其进行修改并使用MPI_Gather接收值.代码如下:

I am writing my first program using MPI and I am having hard time trying to properly send data to other processes using MPI_Scatter, modify them and receive the values using MPI_Gather. The code is as follows:

int** matrix;
int m = 2, n = 2;
int status;

// could have been int matrix[2][2];

matrix = malloc(m*sizeof(int*));

for(i = 0; i < m; i++) {
  matrix[i] = malloc(n*sizeof(int));
}

matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[1][0] = 2;
matrix[1][1] = 3;

MPI_Init( &argc, &argv );
MPI_Comm_rank( MPI_COMM_WORLD, &rank ); 
MPI_Comm_size( MPI_COMM_WORLD, &size );

printf("My name is %d out of %d\n", rank, size);

MPI_Scatter(&matrix, 1, MPI_INT, &status, 1, MPI_INT, 0, MPI_COMM_WORLD);

printf("My name is %d and my status is %d\n", rank, status);

status += 1;

MPI_Gather(&status,1,MPI_INT,&matrix,1,MPI_INT,0,MPI_COMM_WORLD);

结果如下:

My name is 0 out of 4
My name is 1 out of 4
My name is 1 and my status is 0
My name is 2 out of 4
My name is 2 and my status is 120
My name is 0 and my status is 17773264
My name is 3 out of 4
My name is 3 and my status is 0

在MPI_Gather之后,当我尝试打印矩阵的内容时,出现了分割错误...

After MPI_Gather when I try to print the content of matrix I get segmentation fault...

这不是我所期望的...我怀疑问题是我有一个二维数组,想发送单个值.这是正确的吗?该如何纠正?

Which is not what I expect... I suspect that the problem is I have a 2d array and want to send single values. Is this right? How to correct this?

推荐答案

出现分段错误的原因是,您正在分配2D数组,但不能保证它使用连续的内存.因此,分配一维数组并分散/聚集它.这也解释了为什么某些节点获取错误数据的原因.

The reason for the segmentation fault is, that you're allocating a 2D array but there is no guarantee that it uses contiguous memory. So, allocate a 1D array and scatter/gather it. This also explains why some nodes get the wrong data.

您将接收变量命名为status,但我发现它具有误导性,因为它将保存接收到的值.因此,对于节点收到多于一个值的情况,您必须正确分配它.我也建议将其重命名为local_matrix或类似.

You named the receiving variable status which I find misleading, since it'll hold the received value(s). So you'll have to allocate it correctly for the case when a node receives more then one value. Also I'd suggest to rename it to e.g. local_matrix or similar.

侧节点:您可以在所有节点上分配matrix,但是您只能在单个节点上进行分配.这可以通过检查当前等级并在检查之后放置障碍来完成.此外,我假设您还在所有节点上打印,但是此代码不可见.与分配一样,打印也应该只在一个节点上完成.

Side node: You allocate matrix on all nodes, but you should only allocate on a single node. This can be done by checking the current rank and placing a barrier after the check. Furthermore, I assume that you also print on all nodes, but this code isn't visible. As with the allocation, print should done as well only on one node.

还请参阅 MPI_Scatter和C语言中使用的MPI_Gather?解释得很好.

Also have a look at How are MPI_Scatter and MPI_Gather used from C? which explains it pretty well.

这篇关于MPI_Scatter-无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆