I have some particular problem: in a simple MPI_Send/MPI_Recv program, it is assumed that we know the type of message we are about to send, but at the receiving end we don’t know which type of data we will receive.
SO I try first attempt as follows:
#include "mpi.h"
#include <stdlib.h>
#include <stdio.h>
int main(int args, char** argv){
int rank, size;
MPI_Status status;
MPI_Init(&args,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
if(rank==0){
int x = 10;
MPI_Send(&x,4,MPI_BYTE,1,0,MPI_COMM_WORLD);
}
if(rank==1){
void* datax;
int count = sizeof(int);
datax = malloc(count);
MPI_Recv(datax,count,MPI_BYTE,0,0,MPI_COMM_WORLD,&status);
//Now check if the value is received correctly
int z = (int) datax;
printf("RCV: %d \n",z);
}
MPI_Finalize();
return 0;
}
the program compiles correctly and also run, but the received value is some memory garbage value not the correct one (10 in this case).
Any suggestion please?
thanks,
Although your comment addresses your programming mistake, there is a much better way to send and receive data of unknown types (and even unknown size) in MPI.
One common way to differentiate different message types is to use different tag numbers for each type. In your code, you are using a tag number of 0 in your
MPI_Sendcall. Use a tag number that describes the the type of message, and then useMPI_Probebefore yourMPI_Recvcall to find out what type of message you are about to receive. For example, your code could be modified like so:MPI_Probecan also be used to find out the size of a message before you receive a message, which allows you dynamically receive virtually any type of message. For a better explanation and illustration of usingMPI_Probefor this purpose, go to this tutorial.If you need to send widely-different types of data (too many to enumerate with tag numbers), pack your messages into a Google Protocol Buffer, receive it as an array of
MPI_BYTEs (as you do in your example), and then unpack it on the receiving side. A C implementation of Protocol Buffers is here.