我正在尝试发送/接收C++如下所示的数据结构:
/* PSEUDOCODE */
const int N = getN(); // not available at compile time
const int M = getM();
struct package{
int foo;
double bar;
/* I know array members do not work this way,
this is pseudocode. */
int flop[N];
double blep[M];
};
由于M
和N
在运行时是恒定的,因此我可以做MPI_Type_create_struct()
并且新的数据类型 woule 始终都很好。
我的问题是如何实现上述数据结构。
std::vector<>
不起作用,因为它不是串行的。
像[]
或[0]
这样的灵活数组成员在 C++ 中是未定义的行为,它不适用于M
和N
中的两个。
所以相反,我必须使用malloc()
:
class Package {
public:
// in buffer[]: bar, blep[], foo, flop[]
// in that order and one directly follows another.
Package():
buffer((double*) malloc((M + 1) * sizeof(double) +
(N + 1) * sizeof(int))),
bar(buffer), blep(buffer + 1),
foo((int*) (blep + M)),
flop(foo + 1) {}
~Package(){
free(buffer);
}
// construct / free the derived datatype
static void initialize(unsigned inN, unsigned inM) {
N = inN;
M = inM;
MPI_Aint offsets[2] = {0, (int)(sizeof(double)) * (M + 1)};
int blocks[2] = {M + 1, N + 1};
MPI_Datatype types[2] = {MPI_DOUBLE, MPI_INT};
MPI_Type_create_struct(2, blocks, offsets, types, &packageType);
MPI_Type_commit(&packageType);
}
static void finalize() {
MPI_Type_free(&packageType);
}
int send(int rank, int tag) {
return MPI_Send(buffer, 1, packageType,
rank, tag, MPI_COMM_WORLD);
}
int recv(int rank, int tag) {
return MPI_Recv(buffer, 1, packageType,
rank, tag, MPI_COMM_WORLD,
MPI_STATUS_IGNORE);
}
private:
double * buffer;
static int M;
static int N;
static MPI_Datatype packageType;
public:
// interface variables
double * const bar;
double * const blep;
int * const foo;
int * const flop;
};
int Package::N = 0;
int Package::M = 0;
MPI_Datatype Package::packageType = MPI_CHAR;
我测试了上面的代码,它似乎工作正常,但我不确定我是否在做一些实际上是未定义行为的事情。具体说来:
可以使用sizeof()
进行MPI_Type_create_struct()
吗?我发现一些例子使用MPI_Type_get_extent()
,我不知道有什么区别。我不确定将新数据类型存储在
static
成员中是否是个好主意。相反,我找到的例子将其作为论据传递。这样做有什么具体的原因吗?如果这种方法是可移植的,我也很困惑。我希望它应该像基于
struct
的方法一样便携,但也许我错过了一些东西?
如果此方法是可移植的,我也很困惑。我希望它应该像基于结构的方法一样可移植,但也许我错过了一些东西?
1.假设您有一些类型A
和B
而不是double
和int
。然后可能会发生类型B
的对象,您在A
秒后立即为其分配空间,未对齐。在某些体系结构上,尝试访问此类对象(例如,在 (4N + 2)字节边界处int
)将导致总线错误。因此,在一般情况下,您必须确保在第一个B
对象之前正确填充。当您使用struct
编译器会为您执行此操作。
2. 您访问buffer
的方式是 UB。本质上,您正在这样做:
double* buffer = reinterpret_cast<double*>(malloc(...));
double* bar = buffer;
int* foo = reinterpret_cast<int*>(buffer + 1);
do_something(buffer);
double bar_value = *bar; // This is UB
int foo_value = *foo; // This is UB, too
这里的问题是没有double
和int
类型的对象*bar
和*foo
.您可以使用放置new
创建它们:
char* buffer = reinterpret_cast<char*>(malloc(...));
double* bar = new(buffer) double;
int* foo = new(buffer + sizeof(double)) int;
请参考这个问题。
对于数组,您可以使用在给定范围内构造对象的std::uninitialized_default_construct
。
我不确定将新数据类型存储在静态成员中是否是一个好主意。相反,我找到的例子将其作为论据传递。这样做有什么具体的原因吗?
如果N
和M
是静态的,那么packageType
也是静态的似乎没问题。如果您只有一种具有固定N
和M
的Package
,您可能希望避免每次构造Package
以创建基本相同的 MPI 数据类型时调用MPI_Type_create_struct
。
但是这种设计看起来并不好:人们应该在第一次施工之前打电话给initialize()
。也许你可以创建一个工厂,首先创建 MPI 数据类型,然后根据用户请求构造Package
,类似Package make_package()
.然后每个工厂都可以有自己的非静态N
和M
。