问题描述
#include <iostream>
#include "mpi.h"
using namespace std;
int main()
{
int data[10] = { 21,45,32,16,2,105,98,76,69,9 };
int size,rank;
int temp[10] = { 0 };
MPI_Init(NULL,NULL);
MPI_Comm_rank(MPI_COMM_WORLD,&rank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Status status;
int elem_per_process = 10 / size;
if (rank == 0) {
// Sending partial arrays to all processes except the last one
int i = 0;
int start_index = 0;
for (i = 1; i < size - 1; i++) {
start_index = i * elem_per_process;
MPI_Send(&data[start_index],elem_per_process,MPI_INT,i,MPI_COMM_WORLD);
}
// Sending all the remaining elements to the last process
int elem_rem = 10 - (i * elem_per_process);
if (elem_rem)
MPI_Send(&data[i * elem_per_process],elem_rem,MPI_COMM_WORLD);
// Calculating max of partial array sent to Process 0 by itself
int max = data[0],ind = 0;
for (int j = 0; j < elem_per_process; j++) {
if (data[j] >= max) {
max = data[j];
ind = j;
}
}
cout << "Maximum element of the partial array sent to Process " << rank << " is " << max << " at index " << ind << endl;
// Calculating max of the array from the max received from the partial arrays
int result[2];
for (int i = 1; i < size; i++) {
MPI_Recv(&result,MPI_COMM_WORLD,&status);
if (result[0] >= max) {
max = result[0];
ind = result[1];
}
}
cout << "Maximum element of the entire array is: " << max << " at index " << ind << endl;
}
else {
// Receiving partial arrays from Process 0
MPI_Recv(&temp,10,&status);
// Calculating max of partial array sent by Process 0
int max = temp[0],ind = 0;
for (int j = 0; j < 10; j++) {
if (temp[j] >= max) {
max = temp[j];
ind = j;
}
}
cout << "Maximum element of the partial array sent to Process " << rank << " is " << max << " at index " << ind << endl;
int res[] = { max,ind };
// Sending max element to Process 0
MPI_Send(&res,MPI_COMM_WORLD);
}
MPI_Finalize();
return 0;
}
这是我试过的。
这里,等级 0 进程是主进程,所有其他进程都是从进程。主进程在从进程和它自己之间平均分配数组,任何剩余的元素也保留在主进程中。
每个进程计算最大元素(在这种情况下也是它的索引)并将其发送到主进程。主节点在接收到所有最大元素后,计算其中的最大值并打印出最终的最大值。
我的代码的问题是在所有部分数组中,索引都是从 0 开始的。 This 是我从 8 个进程中得到的输出。
如何打印数组元素的实际索引?
我知道可以通过对此代码进行一些更改来完成,但我无法弄清楚。帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)