考虑这样的事情:
typedef struct TS {
double a,b,c;
} S;
...
S x,y;
...
MPI_Allreduce(&x, &y, 3, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
上面的代码是否完全可移植(不使用MPI_Type_struct和all;结构中的所有变量都假定属于同一类型)?在使用各种节点上的不同硬件时也是如此?
提前致谢, JAC
答案 0 :(得分:1)
这种情况下的可移植性取决于三个double
元素的结构是否与三个double
元素的数组相当。我想说对于大多数C编译器来说可能都是这样,但如果它是C标准的一部分则不会打赌。
MPI实现对MPI_DOUBLE
类型的转换将保证异构情况下的可移植性。
答案 1 :(得分:1)
Hristo Iliev完全正确; C标准允许字段之间的任意填充。因此,不能保证这是与三个双精度数组相同的内存布局,并且你的reduce可能会给你带来垃圾。
所以你可以采取两种不同的方法。一个是忽略这个问题,因为大多数C编译器可能会将其视为三个连续双精度数组。我通常不会提到这个甚至是一个选项,除了在这种情况下它很容易测试假设;在您的代码中,您可以拥有
assert ( offsetof(S,b) == sizeof(double) );
assert ( offsetof(S,c) == 2*sizeof(double) );
如果你的代码继续通过断言你就是好的。 (注意,这仍然不能保证这些结构中的两个的数组相当于6个连续双精度数组......)
第二种方法是创建结构并自行减少操作以确保安全。实际上,它并不太难,然后你知道它会起作用,所以这真的是要走的路;然后你可以安全地使用该类型进行任何其他操作:
#include <stdio.h>
#include <stddef.h>
#include <mpi.h>
typedef struct TS {
double a,b,c;
} S;
/* our reduction operation */
void sum_struct_ts(void *in, void *inout, int *len, MPI_Datatype *type){
/* ignore type, just trust that it's our struct type */
S *invals = in;
S *inoutvals = inout;
for (int i=0; i<*len; i++) {
inoutvals[i].a += invals[i].a;
inoutvals[i].b += invals[i].b;
inoutvals[i].c += invals[i].c;
}
return;
}
void defineStruct(MPI_Datatype *tstype) {
const int count = 3;
int blocklens[count];
MPI_Datatype types[count];
MPI_Aint disps[count];
for (int i=0; i < count; i++) {
types[i] = MPI_DOUBLE;
blocklens[i] = 1;
}
disps[0] = offsetof(S,a);
disps[1] = offsetof(S,b);
disps[2] = offsetof(S,c);
MPI_Type_create_struct(count, blocklens, disps, types, tstype);
MPI_Type_commit(tstype);
}
int main (int argc, char **argv) {
int rank, size;
MPI_Datatype structtype;
MPI_Op sumstruct;
S local, global;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
defineStruct(&structtype);
MPI_Op_create(sum_struct_ts, 1, &sumstruct);
local.a = rank;
local.b = 2*rank;
local.c = 3*rank;
MPI_Reduce(&local, &global, 1, structtype, sumstruct, 0, MPI_COMM_WORLD);
if (rank == 0) {
printf("global.a = %lf; expected %lf\n", global.a, 1.*size*(size-1)/2);
printf("global.b = %lf; expected %lf\n", global.b, 2.*size*(size-1)/2);
printf("global.c = %lf; expected %lf\n", global.c, 3.*size*(size-1)/2);
}
MPI_Finalize();
return 0;
}
跑步给出
$ mpicc -o foo foo.c -std=c99
$ mpirun -np 1 ./foo
global.a = 0.000000; expected 0.000000
global.b = 0.000000; expected 0.000000
global.c = 0.000000; expected 0.000000
$ mpirun -np 2 ./foo
global.a = 1.000000; expected 1.000000
global.b = 2.000000; expected 2.000000
global.c = 3.000000; expected 3.000000
$ mpirun -np 3 ./foo
global.a = 3.000000; expected 3.000000
global.b = 6.000000; expected 6.000000
global.c = 9.000000; expected 9.000000
$ mpirun -np 12 ./foo
global.a = 66.000000; expected 66.000000
global.b = 132.000000; expected 132.000000
global.c = 198.000000; expected 198.000000