如果我想定义自己的类型,并将其用作 MPI_Send
的数据类型以仅从矩阵中获取偶数行,是否必须静态分配该矩阵(发送缓冲区)?
我动态分配的时候好像有问题。这是因为地址需要连续才能发送数据吗?
最佳答案
不,使用 MPI_Send
发送的内存不必静态分配。
要发送数组子集,您可能需要使用 MPI_Type_indexed
。这是来自 mpi.deino.net article on MPI_Type_indexed
的示例的略微修改版本,我已经替换了静态分配的缓冲区
int buffer[27];
到一个动态分配的缓冲区
int* buffer = (int*)malloc(27 * sizeof(int));
希望对您有所帮助:
#include <mpi.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
int rank, size, i;
MPI_Datatype type, type2;
int blocklen[3] = { 2, 3, 1 };
int displacement[3] = { 0, 3, 8 };
int* buffer = (int*)malloc(27 * sizeof(int)); //int buffer[27];
MPI_Status status;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size < 2)
{
printf("Please run with 2 processes.\n");
MPI_Finalize();
return 1;
}
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Type_contiguous(3, MPI_INT, &type2);
MPI_Type_commit(&type2);
MPI_Type_indexed(3, blocklen, displacement, type2, &type);
MPI_Type_commit(&type);
if (rank == 0)
{
for (i=0; i<27; i++)
buffer[i] = i;
MPI_Send(buffer, 1, type, 1, 123, MPI_COMM_WORLD);
}
if (rank == 1)
{
for (i=0; i<27; i++)
buffer[i] = -1;
MPI_Recv(buffer, 1, type, 0, 123, MPI_COMM_WORLD, &status);
for (i=0; i<27; i++)
printf("buffer[%d] = %d\n", i, buffer[i]);
fflush(stdout);
}
MPI_Finalize();
free(buffer);
return 0;
}
关于c - MPI_Send 仅适用于静态分配的缓冲区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23552968/