Jeremiah ha ragione - MPI_Type_create_struct è il modo per andare qui.
È importante ricordare che MPI è una libreria, non integrata nella lingua; quindi non può "vedere" come appare una struttura per serializzarlo da solo. Pertanto, per inviare tipi di dati complessi, è necessario definirne esplicitamente il layout. In una lingua che ha il supporto nativo per la serializzazione, una serie di wrapper MPI può in qualche modo farne uso; mpi4py, ad esempio, utilizza python pickle per inviare in modo trasparente tipi di dati complessi; ma in C, devi rimboccarti le maniche e farlo da solo.
Per la vostra struttura, sembra che questo:
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include <stddef.h>
typedef struct car_s {
int shifts;
int topSpeed;
} car;
int main(int argc, char **argv) {
const int tag = 13;
int size, rank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size < 2) {
fprintf(stderr,"Requires at least two processes.\n");
exit(-1);
}
/* create a type for struct car */
const int nitems=2;
int blocklengths[2] = {1,1};
MPI_Datatype types[2] = {MPI_INT, MPI_INT};
MPI_Datatype mpi_car_type;
MPI_Aint offsets[2];
offsets[0] = offsetof(car, shifts);
offsets[1] = offsetof(car, topSpeed);
MPI_Type_create_struct(nitems, blocklengths, offsets, types, &mpi_car_type);
MPI_Type_commit(&mpi_car_type);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
car send;
send.shifts = 4;
send.topSpeed = 100;
const int dest = 1;
MPI_Send(&send, 1, mpi_car_type, dest, tag, MPI_COMM_WORLD);
printf("Rank %d: sent structure car\n", rank);
}
if (rank == 1) {
MPI_Status status;
const int src=0;
car recv;
MPI_Recv(&recv, 1, mpi_car_type, src, tag, MPI_COMM_WORLD, &status);
printf("Rank %d: Received: shifts = %d topSpeed = %d\n", rank,
recv.shifts, recv.topSpeed);
}
MPI_Type_free(&mpi_car_type);
MPI_Finalize();
return 0;
}
Grazie per la tua risposta completa e rapida. Lo apprezzo molto. Mi hai completamente coperto. (Comunque penso che ti sia dimenticato di includere in alto perché altrimenti il compilatore dà errori ..) –
kstratis
Hai ragione - serve per l'offset di(). Ho aggiornato il codice in modo appropriato. –