c - MPI_Send 仅适用于静态分配的缓冲区

标签 c mpi

如果我想定义自己的类型,并将其用作 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/

相关文章:

c++ - 创建链接到 Rust dylib 的共享 C 对象以在 R 中使用

python - 尽管 MPICC 安装正确且有效,但安装 mpi4py 时出现 MPICC 错误

python - 无法使用 intel MKL ScaLapack 和 Blacs 编译包

c - 如何编写用于分析的 MPI 库

c - ncurses 菜单 - 不会显示我的用户输入的字符串

c - 使用C使用TCP连接到端口

memory - MPI Fortran 代码 : how to share data on node via openMP?

使用 MPI 连接文本文件

c - 使用指针添加时出现 glibc 错误

c++ - 为什么在函数参数中使用静态变量声明函数在 Windows 中不是错误?