c++ - 正确使用 MPI_Send 和 MPI_Recv
问题描述
我正在使用 C++ 编写一个简单的程序,该程序使用 MPI 在两个进程之间进行通信。如果我想将一个数组发送到另一个进程,MPI_Send
andMPI_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 - 如何在循环中添加scanf内的数字?
- javascript - 我如何读取嵌套属性并使用 javascript 推送到数组?
- identityserver4 - 如何配置在 .Net Framework 4.7.1 上运行的 mvc 客户端以使用在 .Net Core 上运行的 IdentityServer4 (3.1) 进行身份验证
- python - Seaborn Barplot 如何在一个栏中包含多个值
- python - txt文件字数限制
- angular - 材料输入作物输入顶部和底部
- javascript - three.js:将外部纹理应用到 glTF
- html - 我在 html 预览中看不到图像 (2021)
- c - 神秘双指针赋值的解释
- android - Android View Binding问题,公共类名和文件名不同