我试图了解发送数组的工作原理。我写了一个简单的程序,但效果不好,因为它通常会在分段错误时崩溃。我的计划有论据:
mpirun -np 2 sendTest
以下是代码:
#include <mpi.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int cpuNum;
int myId;
MPI_Status mpiStatus;
MPI_Init(&argc,&argv);
MPI_Comm_size(MPI_COMM_WORLD,&cpuNum);
MPI_Comm_rank(MPI_COMM_WORLD,&myId);
int *myNumbs=(int*)malloc(2*(sizeof(int)));
int *neighNumbs=(int*)malloc(2*(sizeof(int)));
if(myId==0){
myNumbs[0]=0;
myNumbs[1]=0;
MPI_Send(&myNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Recv(&neighNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &mpiStatus);
cout<<"this is cpu 0, neigh myNumbs=";
for (int i = 0; i < 2; ++i){
printf("%d,",neighNumbs[i]);
}
cout<<endl;
}
else{
myNumbs[0]=1;
myNumbs[1]=1;
MPI_Recv(&neighNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &mpiStatus);
MPI_Send(&myNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
cout<<"this is cpu 1, neigh myNumbs=";
for (int i = 0; i < 2; ++i){
printf("%d,",neighNumbs[i]);
}
cout<<endl;
}
MPI_Finalize();
return 0;
}
正如我所说的,它通常会因此错误而崩溃:*** Process received signal *** Signal: Segmentation fault (11) Signal code: Address not mapped (1)
。但有时一个或另一个进程会收到数据。
答案 0 :(得分:3)
您必须传递已分配数组的地址,而不是指向已分配数组的指针的地址。
在指针变量之前删除两个&
:尝试
MPI_Send(myNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Recv(neighNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &mpiStatus);
而不是
MPI_Send(&myNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Recv(&neighNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &mpiStatus);
和
MPI_Recv(neighNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &mpiStatus);
MPI_Send(myNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
而不是
MPI_Recv(&neighNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &mpiStatus);
MPI_Send(&myNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);