我正在努力学习使用MPI。下面是我测试MPI分散和收集的简单程序。我不明白它是如何工作的以及它产生结果的原因
1 2 3 4 4 5 6 7 8 9 10 11
而不是预期的
1 2 3 4 5 6 7 8 9 10 11 12
我可以找到的文档和所有示例都太复杂/措辞不好,让我无法理解。我只想在3个进程中分散一个数组,并在每个进程中为每个值添加一个。或者,我很高兴看到如何将2D数组逐行发送到每个进程,并简单地处理每一行。
int main(int argc, char **argv) {
int rank; // my process ID
int size = 3; // number of processes/nodes
MPI_Status status;
MPI_Init(&argc, &argv); // start MPI
MPI_Comm_size(MPI_COMM_WORLD, &size); // initialize MPI
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
unsigned char inData[12]; // data returned after being "processed"
unsigned char outData[12]; // buffer for receiving data
unsigned long datasize = 12; // size of data to process
unsigned char testData[12]; // data to be processed
if (rank == 0) {
// initialize data
for (int i = 0; i < datasize; i++) {
testData[i] = i;
outData[i] = 0;
inData[i] = 0;
}
}
// scatter the data to the processes
// I am not clear about the numbers sent in and out
MPI_Scatter(&testData, 12, MPI_UNSIGNED_CHAR, &outData,
12, MPI_UNSIGNED_CHAR, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
// process data
for (int i = 0; i < 4; i++) { outData[i] = outData[i] + 1; }
MPI_Barrier(MPI_COMM_WORLD);
// gather processed data
MPI_Gather(&outData, 12, MPI_UNSIGNED_CHAR, &inData,
12, MPI_UNSIGNED_CHAR, 0, MPI_COMM_WORLD);
//print processed data from root
if (rank == 0) {
for (int i = 0; i < 12; i++) {
printf("\n%d", inData[i]);
}
MPI_Finalize();
}
return 0;
}
虽然你的主要错误是使用12
而不是4
,但让我们一步一步来做。
// int size = 3; // number of processes/nodes
int size;
...
MPI_Comm_size(MPI_COMM_WORLD, &size); // initialize MPI
assert(size == 3);
把size
设置为3
是没有意义的。 MPI_Comm_size
将使用实际的进程数覆盖此值。此数字取决于您运行MPI应用程序的方式(例如mpirun -np 3
)。
//unsigned char outData[12]; // buffer for receiving data
unsigned char outData[4];
我们有12个元素和3个进程,每个进程4个元素。所以,4个元素足以让outData
。
outData[i] = 0;
inData[i] = 0;
将这些缓冲区置零是没有意义的,它们将被覆盖。
// scatter the data to the processes
// I am not clear about the numbers sent in and out
MPI_Scatter(&testData, 4 /*12*/, MPI_UNSIGNED_CHAR, &outData,
4 /*12*/, MPI_UNSIGNED_CHAR, 0, MPI_COMM_WORLD);
每个进程有4个元素,因此数字应为4,而不是12。
MPI_Barrier(MPI_COMM_WORLD);
你这里不需要障碍。
MPI_Gather(&outData, 4 /*12*/, MPI_UNSIGNED_CHAR, &inData,
4 /*12*/, MPI_UNSIGNED_CHAR, 0, MPI_COMM_WORLD);
同样的故事,4
而不是12
。
MPI_Finalize();
这应该由所有进程调用。