gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 23:17:34 26 4
gpt4 key购买 nike

我正在学习 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com