我刚开始使用 MPI,并且无法理解为什么我的代码无法正常工作。
#include "mpi.h"
#include <stdio.h>
#include <string.h>
int main(int argc, char* argv[]) {
int list_size = 1000
int threads;
int th_nums;
int slice;
char* the_array[list_size];
char* temp_array[list_size];
char str_to_search[10];
FILE *in = fopen("inputfile", "r");
char parse[10];
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &threads);
MPI_Comm_size(MPI_COMM_WORLD, &th_nums);
if (threads == 0) { // if master task
fgets(parse, 10, in);
slice = atoi(parse); // How many slices to cut the array into
fgets(parse, 10, in);
sscanf(parse, "%s", search); // gives us the string we want to search
int i;
for (i = 0; i < list_size; i++) {
char temp[10];
fgets(parse, 10, in);
sscanf(parse, "%s", temp);
the_array[i] = strdup(temp);
}
int index = list_size/slice; //
MPI_Bcast(&str_to_search, 10, MPI_CHAR, 0, MPI_COMM_WORLD);
}
MPI_Bcast(&str_to_search, 10, MPI_CHAR, 0, MPI_COMM_WORLD);
MPI_Scatter(the_array, index, MPI_CHAR, temp_array, index, 0, MPI_COMM_WORLD);
// Search for string occurs here
MPI_Finalize();
return 0;
}
但是,我发现当我尝试搜索时,只有主任务收到一些切片,其余的为空。所有其他任务不会收到任何内容。我尝试将 MPI_Scatter 放在 if(master task) 语句之外,但我没有运气。另外,当 list_size 增加时,我发现程序基本上卡在 MPI_Scatter 行。我做错了什么,我能做些什么来纠正这个问题?
最佳答案
你应该去查找一些关于 MPI 集合的教程。它们要求所有流程共同参与。因此,如果任何进程调用 MPI_Scatter
,则所有进程都必须调用 MPI_Scatter
。我建议您查看一些示例代码并使用它,直到您了解发生了什么。然后尝试回到您自己的代码,看看您是否能弄清楚发生了什么。
对于 MPI-3 之前的任何内容,我最喜欢的引用是 DeinoMPI 。我从未使用过该实现,但文档很棒,因为它为 MPI-2 规范中的每个函数提供了完整的示例。
关于C MPI 数组搜索帮助 (MPI_Scatter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30072992/