Newer
Older
#include <cstdio>
#include <cstddef>
#include <vector>
class Car {
public:
int shifts;
int topSpeed;
double pos[3];
};
int main(int argc, char* argv[]) {
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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");
}
/* create a type for struct car */
const int nitems = 3;
int blocklengths[3] = {1, 1, 3};
MPI_Datatype types[3] = {MPI_INT, MPI_INT, MPI_DOUBLE};
MPI_Datatype mpi_car_type;
MPI_Aint offsets[3];
offsets[0] = offsetof(Car, shifts);
offsets[1] = offsetof(Car, topSpeed);
offsets[2] = offsetof(Car, pos);
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) {
vector<Car> send;
send.push_back(Car());
send.push_back(Car());
send[0].shifts = 4;
send[0].topSpeed = 100;
send[0].pos[0] = 0.5;
send[0].pos[1] = 0.6;
send[0].pos[2] = 0.7;
send[1].shifts = 5;
send[1].topSpeed = 200;
send[1].pos[0] = 1.5;
send[1].pos[1] = 1.6;
send[1].pos[2] = 1.7;
const int dest = 1;
MPI_Send(&send[0], 2, 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;
vector<Car> recv;
recv.reserve(2);
MPI_Recv(&recv[0], 2, mpi_car_type, src, tag, MPI_COMM_WORLD, &status);
printf("Rank %d: Received: shifts = %d topSpeed = %d | %f | %f | %f\n", rank,
recv[0].shifts, recv[0].topSpeed, recv[0].pos[0], recv[0].pos[1], recv[0].pos[2]);
printf("Rank %d: Received: shifts = %d topSpeed = %d | %f | %f | %f\n", rank,
recv[1].shifts, recv[1].topSpeed, recv[1].pos[0], recv[1].pos[1], recv[1].pos[2]);
}
MPI_Type_free(&mpi_car_type);
MPI_Finalize();