int MPI_Send(const void *buf, int count, MPI_Datatype datatype, int dest, int tag, MPI_Comm comm)
OpenMPI will send count * sizeof(datatype)
contiguous bytes starting at buf
to allow sending things like int arrays. For example, if you declare a 10 int array int arr[10]
, you can send with
MPI_Send(arr, 10, MPI_INT, 1, 0, MPI_COMM_WORLD);
and receive similarly. Since buf
is a void pointer we can abuse this to send structs by sending sizeof(my_struct)
bytes and casting back as struct on the receiving end. Here is an example:
#include "mpi.h"
#include <stdio.h>
typedef struct
{
char a;
int b;
short c;
} my_struct;
int main (int argc, char *argv[])
{
int numtasks, taskid;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &taskid);
MPI_Comm_size(MPI_COMM_WORLD, &numtasks);
if (taskid == 0)
{
my_struct m;
m.a = '!';
m.b = 1234;
m.c = 5678;
MPI_Send(&m, sizeof(my_struct), MPI_CHAR, 1, 0, MPI_COMM_WORLD);
}
else
{
my_struct m;
MPI_Recv(&m, sizeof(my_struct), MPI_CHAR, 0, 0, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
printf("%c %d %d\n", m.a, m.b, m.c);
}
MPI_Finalize();
}
Since C arrays store data contiguously, we can even send arrays of structs similarly to how we malloc an array of structs. So if you had a my_struct m_array[10]
you would send (and receive similarly) with
MPI_Send(m_array, sizeof(my_struct) * 10, MPI_CHAR, 1, 0, MPI_COMM_WORLD);