【发布时间】:2018-05-27 11:09:53
【问题描述】:
我正在尝试编写一个简单的多进程程序来查找数组中的值。
#include <mpi.h>
#include <stdio.h>
int* create_array(int num_items) {
int* tmp = new int[num_items];
for(int i = 0; i < num_items; i++)
tmp[i] = i;
return tmp;
}
int main() {
int num_items = 1000;
int item = 999;
MPI_Init(NULL, NULL);
int world_rank, world_size, num_items_per_proc;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Request* inReq;
int* array;
if(world_rank == 0) {
array = create_array(num_items);
num_items_per_proc = (num_items / world_size) + 1;
}
int* sub_array = new int[num_items_per_proc];
MPI_Scatter(array, num_items_per_proc, MPI_INT, sub_array,
num_items_per_proc, MPI_INT, 0, MPI_COMM_WORLD);
bool found = false;
MPI_Irecv(&found, 1, MPI::BOOL, MPI_ANY_SOURCE, MPI_ANY_TAG,
MPI_COMM_WORLD, inReq);
for(int i = 0; i < num_items_per_proc && !found; i++) {
if (sub_array[i] == item) {
found = true;
printf("Elemento %d trovato in posizione: %d\n", item, i);
for(int j = 0; j < world_size; j++)
if(j != world_rank)
MPI_Send(&found, 1, MPI::BOOL, j, j, MPI_COMM_WORLD);
}
}
if(world_rank == 0) delete[] array;
delete[] sub_array;
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
}
当他们中的一个人在数组的一部分中找到值时,我试图停止所有操作,但我收到了 Irecv 的分段错误。我该如何解决这个问题?
【问题讨论】:
-
num_items_per_proc看起来不正确。找到值的任务不会停止其他任务,它只是通知他们,您可以通过MPI_Allreduce()实现
标签: c++ mpi linear-search