首页 > 解决方案 > 正确使用 MPI_Send 和 MPI_Recv

问题描述

我正在使用 C++ 编写一个简单的程序,该程序使用 MPI 在两个进程之间进行通信。如果我想将一个数组发送到另一个进程,MPI_SendandMPI_Recv函数需要一个指向所述数组的指针:

int MPI_Send(void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
int MPI_Recv(void *buf, int count, MPI_Datatype datatype, int source, int tag, MPI_Comm comm, MPI_Status *status);

在一个在线教程中,我看到了 MPI_Send 和 MPI_Recv 的以下用法:

int values[5] = {1, 2, 3, 4, 5};
MPI_Send(values, 5, MPI_INT, 1, 0, MPI_COMM_WORLD);

int values[10];
MPI_Recv(&values, 10, MPI_INT, 3, MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUS_IGNORE);

为什么本教程仅在一种情况下使用,values而在另一种情况下还使用地址运算符&values

我编写了一个程序来在两个进程之间发送和接收数组,它似乎可以使用和不使用地址运算符。为什么会这样?我的想法肯定是错误的。你能帮我找出我的错误吗?

这是我的代码:

#include <iostream>
#include <mpi.h>

int main(int argc, char** argv) {
    MPI_Init(&argc, &argv);

    // Reading size and rank
    int size, rank;
    MPI_Comm_size(MPI_COMM_WORLD, &size);
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);

    // For every process create array 
    double array[2];
    if (rank == 0) {
        array[0] = 0.1;
        array[1] = 0.2;
    } else {
        if (rank == 1) {
            array[0] = 1.1;
            array[1] = 1.2;
        }
    }

    // Send and receive
    double other_array[2];
    if (rank == 0) {
        MPI_Send(&array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD);
        MPI_Recv(&other_array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        // OR
        // MPI_Send(array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD);
        // MPI_Recv(other_array, 2, MPI_DOUBLE, 1, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        std::cout << rank << " " << other_array[0] << " " << other_array[1] << std::endl;
    } else {
        MPI_Recv(&other_array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Send(&array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD);
        // OR
        // MPI_Recv(other_array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        // MPI_Send(array, 2, MPI_DOUBLE, 0, 99, MPI_COMM_WORLD);
        std::cout << rank << " " << other_array[0] << " " << other_array[1] << std::endl;
    }

    // Finalisation
    int MPI_Finalize(); 

    return 0;
}

我编译并运行程序使用

mpic++ -O -Wall main.cpp -o main mpirun -np 2 ./main

标签: c++mpi

解决方案


推荐阅读