I am trying to understand how sending an array works. I wrote a simple program but with not good results, as it usually crashes on segmentation fault. There are arguments for my program:
mpirun -np 2 sendTest
Here is the code:
#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;
}
As I said it usually crashes with error like this: *** Process received signal *** Signal: Segmentation fault (11) Signal code: Address not mapped (1)
. But sometimes one or the other process receives the data.
You must pass the address of the allocated arrays, not the address of the pointers who points to the allocated arrays.
Remove the two &
before the pointer variables: try
MPI_Send(myNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Recv(neighNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &mpiStatus);
instead of
MPI_Send(&myNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Recv(&neighNumbs, 2, MPI_INT, 1, 0, MPI_COMM_WORLD, &mpiStatus);
and
MPI_Recv(neighNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &mpiStatus);
MPI_Send(myNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
instead of
MPI_Recv(&neighNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD, &mpiStatus);
MPI_Send(&myNumbs, 2, MPI_INT, 0, 0, MPI_COMM_WORLD);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.