c - MPI:使用 MPI_Isend 发送消息并使用 C 中的 MPI_Irecv 接收消息

标签 c mpi openmpi

我正在学习 c 中的 mpi 通信。我在尝试使用 MPI_Isend 从一个节点发送消息并使用 MPI_Irecv 在另一个节点上接收它时遇到问题。这是代码:

#include <stdlib.h>
#include <stdio.h>
#include <mpi.h>
#include <string.h>

#define TAG 3
#define ROOT 0

int main (int argc, char ** argv){
    int number_of_proc = 0;
    int rank = 0;
    // initialize mpi environment
    MPI_Init(NULL, NULL);
    // get the number of processes
    MPI_Comm_size(MPI_COMM_WORLD, &number_of_proc);
    // get the rank of this process
    MPI_Comm_rank(MPI_COMM_WORLD, &rank);
    if (rank == 1){
        // the message i want to send to the other node
        int message = 123;
        MPI_Request success_send = MPI_REQUEST_NULL;
        // send message to the root node
        MPI_Isend(&message, 1, MPI_INT, ROOT, TAG, MPI_COMM_WORLD, &success_send);
        // to check if the node keeps running after sending the message
        printf("Node 1 still working\n");
    } else if (rank == ROOT){
        printf("Node 0:%10d Nodes total\n", number_of_proc);
        int message = 0;
        MPI_Request success_received = MPI_REQUEST_NULL;
        // receive the message from node 1
        MPI_Irecv(&message, 1, MPI_INT, MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, &success_received);
        printf("Node 0: greetings from node 1: %10d\n", message);
    }
    MPI_Finalize();
    return EXIT_SUCCESS;
} 

该文件名为 mpitest.c。我用 mpicc -pedantic -Wall -std=c99 -o mpitest mpitest.c 编译它并用 mpirun -c 2 ./mpitest 启动它。

预期的输出是

Node 1 still working
Node 0:         2 Nodes total
Node 0: greetings from node 1:          123

但是我得到了

Node 1 still working
Node 0:         2 Nodes total
Node 0: greetings from node 1:            0

我做错了什么?

最佳答案

试试这个。您正在使用非阻塞通信,因此您必须等待接收操作结束。

MPI_Irecv(&message, 1, MPI_INT, MPI_ANY_SOURCE, TAG, MPI_COMM_WORLD, &success_received);
MPI_Status status;
MPI_Wait(&success_received,  &status);

关于c - MPI:使用 MPI_Isend 发送消息并使用 C 中的 MPI_Irecv 接收消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30681797/

相关文章:

mpi - openMPI 中的处理器/套接字关联?

gcc - 如何更改 OpenMPI 的编译器

c 宏重复参数

c - 为什么我的文件的相对路径不能被我的应用程序识别?

r - 如何在Windows R上设置和使用MPI

python - 通过(非 MPI)python 脚本与 MPI 二进制文件交互

c - 用 C 语言编写一个程序,打印 1 到 10000 之间的阿姆斯特朗数

c - 为什么 GCC 不优化对 printf 的调用?

synchronization - 与 MPI_BCAST 隐式同步发送方和接收方?

c - 强制 MPI_Send 使用 eager 或 rendezvouz 协议(protocol)