c - 使用 MPI_Scatter 和 MPI_Gather 实现 Master-Worker-Model
问题描述
我为图像处理过滤器编写了一个 MPI 程序。该程序的主要目标是使用并行计算将给定的过滤器应用于图像文件。
MPI 程序运行良好,没有任何问题。
现在我想为我的 MPI 程序使用 Master-Worker-Model。经过一番研究,我发现 MPI_Scatter 和 MPI_Gather 是我需要的命令。
但我不太明白它们是如何工作的。这是我第一次尝试编写代码:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char** argv)
{
// Filters
MPI_Init(&argc, &argv);
if(parent == MPI_COMM_NULL)
{
MPI_Scatter(); // What are the parameters?
// Master reads in the image file and distribute it to the workers.
MPI_File_open();
MPI_File_read();
MPI_File_close();
}
else
{
// After receiving data from the master, worker processes begin their job.
/* Normally here would be the entire logic of this program.*/
/* For simplicity I just skip it for readability.*/
/* The calculcation is exclusively up to the workers.*/
}
// After finishing, the results will be sent back to the master.
MPI_Gather(); // What are the parameters?
MPI_Finalize();
return 0;
}
它不会运行,因为它只是第一个原型。我想知道的是我是否理解了Master-Worker-Model的概念。
对代码的一些反馈会有所帮助。
提前致谢。
解决方案
这是一个示例程序,展示了如何执行分散/聚集操作。请注意,在您的情况下,由于主任务不做任何工作,因此内部通信器是最合适的(即使内部通信器上的集体操作的语义并不总是很直观),因此您不需要MPI_Intercomm_merge()
.
#include <stdio.h>
#include <stdbool.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
MPI_Comm parent, intercomm;
const int slaves = 2;
bool master;
int data[slaves];
int mydata;
int i, rank, root;
MPI_Init(&argc, &argv);
MPI_Comm_get_parent(&parent);
master = parent == MPI_COMM_NULL;
if (master) {
int errcodes[slaves];
/* spawn the slaves */
MPI_Comm_spawn(argv[0], MPI_ARGV_NULL, slaves, MPI_INFO_NULL, 0, MPI_COMM_WORLD, &intercomm, errcodes);
/* prepare data to be scattered to the slaves */
for (i=0; i<slaves; i++) {
data[i] = i;
}
/* here we assume there is only one master */
root = MPI_ROOT;
} else {
intercomm = parent;
root = 0;
}
/* scatter data from master to slaves */
MPI_Scatter(data, 1, MPI_INT, &my-data, 1, MPI_INT, root, intercomm);
if (!master) {
/* slaves do their work */
mydata = mydata + 1;
}
/* gather data from slaves to master */
MPI_Gather(&mydata, 1, MPI_INT, data, 1, MPI_INT, root, intercomm);
if (master) {
int i;
for (i=0; i<slaves; i++) {
printf("Slave %d returned %d\n", i, data[i]);
}
}
MPI_Comm_disconnect(&intercomm);
MPI_Finalize();
return 0;
}
推荐阅读
- javascript - React-Redux:尝试导入错误:'./components/Score' 不包含默认导出(导入为'Score')
- python - 大家好,你建议在空的for循环之后放什么(我不知道放什么)?
- java - javax/xml/bind/JAXBException
- leaflet - 如何使用传单?
- c# - 带有浮点值的 Unity 枚举下拉列表
- apache - .htaccess 子域的端口重写
- javascript - 如何使用 Python 和 Selenium 从外部 Javascript 文件执行函数?
- html - 让视频在 iphone/mobile 上内联工作
- python-3.x - apache_beam.io.WriteToText() 文件名作为模板参数
- c++ - 大括号 {} 的 Visual Code C/C++ 格式