我有一个程序可以执行以下操作:读取数组的大小,读取数组的每个元素,然后读取要在该数组中找到的数字。该程序必须为每个进程拆分搜索。我的问题是我不知道如何使所有从属进程都等待主机完成读取过程。这是到目前为止我得到的:
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <cstdlib>
#include "mpi.h"
using namespace std;
void searchForElementInArray(int left, int right, int myArray[], int number);
void readArrayAndNumber(int myArray[], int &arraySize, int &number);
int main(int argc, char *argv[])
{
int LIMIT = 100;
int numberOfProcesses;
int processRank;
int error;
int length;
int myArray[1010];
int arraySize;
int number;
error = MPI_Init(&argc, &argv);
if (error != MPI_SUCCESS) {
cout << "Error starting MPI program. Terminating.\n";
MPI_Abort(MPI_COMM_WORLD, error);
}
// get the number of processes
MPI_Comm_size(MPI_COMM_WORLD, &numberOfProcesses);
MPI_Bcast(&arraySize, 1, MPI_INT, 0, MPI_COMM_WORLD);
// Length of each interval
length = arraySize / numberOfProcesses;
//get the process rank
MPI_Comm_rank(MPI_COMM_WORLD, &processRank);
if (!processRank) { // Master
readArrayAndNumber(myArray, arraySize, number);
MPI_Send(&myArray, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Send(&arraySize, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Send(&number, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);
MPI_Barrier(MPI_COMM_WORLD);
}
else { // Slave
if (processRank != numberOfProcesses - 1) {
MPI_Recv(&myArray, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&arraySize, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
searchForElementInArray(length * processRank, length * processRank + length, myArray, 66);
MPI_Barrier(MPI_COMM_WORLD);
}
else {
MPI_Recv(&myArray, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&arraySize, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
MPI_Recv(&number, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
searchForElementInArray(length * processRank, arraySize, myArray, 66);
MPI_Barrier(MPI_COMM_WORLD);
}
}
MPI_Finalize();
_getch();
return 0;
}
void searchForElementInArray(int left, int right, int myArray[], int number) {
int flag = 0;
cout << "Searched positions: ";
for (int i = left; i < right; i++) {
cout << i << " ";
if (myArray[i] == number) {
cout << endl << "Found on position " << i;
flag = 1;
break;
}
}
if (flag == 0) {
cout << endl << "Not found";
}
int processRank;
MPI_Comm_rank(MPI_COMM_WORLD, &processRank);
cout << " by Process: " << processRank << endl << endl;
}
void readArrayAndNumber(int myArray[], int &arraySize, int &number) {
cin >> arraySize;
for (int i = 0; i < arraySize; i++) {
cin >> myArray[i];
}
cin >> number;
}