对于数组{ 24 48 27 1 5 30 40 27 31 36 29 45 45 43 10 15 50 35 40 47 }
index 0- 3 ---> processor 0,
index 4- 7 ---> processor 1,
index 8-11 ---> processor 2,
index 12-15 ---> processor 3,
index 16-19 ---> processor 4,
并将总和返回给主总和。
我如何对其进行编码以便可以轻松完成???
import java.util.Random;
import mpi.*;
public class Aznin {
public static void main(String args[]) throws Exception {
Random randomNumbers = new Random();
MPI.Init(args);
int my_rank = MPI.COMM_WORLD.Rank();
int size = MPI.COMM_WORLD.Size();
MPI.COMM_WORLD.Barrier();
int[] n = new int[100];
int[] my_sum = new int[1];
int blockNum, start, end;
int finalSum = 0;
// master initialize random integers and stores them
if (my_rank == 0) {
System.out.println("");
//for 20 values produced by Random number function; but you can declare an array of 20 values; other option can read values from the file--- OK Dear Students :)
//how many valus you want to distribute e.g. 20
for (int i = 0; i < 20; i++) {
n[i] = 1 + randomNumbers.nextInt(50);
System.out.printf("%d| ", n[i]);
}
System.out.printf("\n");
}
//Broadcast n from master processor to all available processors
MPI.COMM_WORLD.Bcast(n, 0, 20, MPI.INT, 0);
// Each processor calculates the result
my_sum[0] = 0;
blockNum = 20/size; // calculates number of data blocks--- using how many CPUs i.e. Size
start = my_rank * blockNum; // calculates for starting index for particular processor
end = start + blockNum; // calculates for ending index for particular processor
//Keep in mind; your approach can vary from my approach; you can create lists at run time as well --OK
for (int i = start; i < end; i++) {
my_sum[0] = my_sum[0] + n[i];
}
System.out.println("Result from processor " +my_rank+ " = " +my_sum[0]);
if (my_rank == 0) { // master processor waits for result from workers
finalSum = my_sum[0];
//master processor recieves result from all available worker prosessors
for (int wproc = 1; wproc < size; wproc++) {
MPI.COMM_WORLD.Recv(my_sum, 0, 1, MPI.INT, MPI.ANY_SOURCE,99);
finalSum = finalSum + my_sum[0];
}
}
else { // worker processors
// send result to master processor
MPI.COMM_WORLD.Send(my_sum, 0, 1, MPI.INT, 0, 99);
}
// master processor prints final result
if (my_rank == 0) {
System.out.println("Result = " + finalSum);
}
MPI.Finalize();
}
}