问题
I have simple program, where I want to scatter structs across several computers, but it seems I have defined datatype incorrectly even though program compiles fine. I have following code.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct small_pixel_s {
double red;
double green;
double blue;
} SMALL_PIXEL;
int main(int argc, char **argv) {
int size, rank;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
SMALL_PIXEL global[8];
SMALL_PIXEL local[2];
const int root = 0;
MPI_Status status;
MPI_Datatype small_pixel_type;
MPI_Datatype type[3] = { MPI_DOUBLE, MPI_DOUBLE, MPI_DOUBLE };
int blocklen[3] = { 1, 1, 1 };
MPI_Aint offsets[3];
offsets[0] = offsetof(SMALL_PIXEL, red);
offsets[1] = offsetof(SMALL_PIXEL, green);
offsets[2] = offsetof(SMALL_PIXEL, blue);
MPI_Type_create_struct(8, blocklen, offsets, type, &small_pixel_type);
MPI_Type_commit(&small_pixel_type);
if (rank == root) {
for (int i=0; i<7; i++) {
global[i].red = i;
global[i].green = i;
global[i].blue = i;
}
}
MPI_Scatter(global, 2, small_pixel_type, /* send everyone 2 ints from global */
local, 2, small_pixel_type, /* each proc receives 2 ints into local */
root, MPI_COMM_WORLD); /* sending process is root, all procs in */
/* MPI_COMM_WORLD participate */
for (int i=0; i<2; i++) {
local[i].red = local[i].red + 4;
local[i].green = local[i].green + 4;
local[i].blue = local[i].blue + 4;
}
MPI_Gather(local, 2, small_pixel_type, /* everyone sends 2 ints from local */
global, 2, small_pixel_type, /* root receives 2 ints each proc into global */
root, MPI_COMM_WORLD); /* recv'ing process is root, all procs in */
/* MPI_COMM_WORLD participate */
if (rank == 0) {
for (int i=0; i<7; i++) {
printf("%f\n", global[i].red);
}
}
MPI_Finalize();
return 0;
}
Any ideas why? How should I define struct that it can be scattered?
When I run program I get *** MPI_ERR_TYPE: invalid datatype
回答1:
In MPI_Type_create_struct, the first argument is count
:
number of blocks (integer) --- also number of entries in arrays array_of_types, array_of_displacements and array_of_blocklengths
In your case that would be 3, not 8. So change this line:
MPI_Type_create_struct(8, blocklen, offsets, type, &small_pixel_type);
to this:
MPI_Type_create_struct(3, blocklen, offsets, type, &small_pixel_type);
来源:https://stackoverflow.com/questions/43057222/invalid-datatype-when-running-mpirun