package be.ac.vub.ir.mpi; import mpi.MPI; class MPIWavefront { public static void main(String[] args) { /* * this solution assigns a row of the matrix to each process */ int[] matrix; // matrix stored at process 0 int[] row; // each process keeps its row int[] receiveBuffer; // to receive a value from ``row - 1'' int[] sendBuffer; // to send a value to ``row + 1'' MPI.Init(args); int rank = MPI.COMM_WORLD.Rank(); int size = MPI.COMM_WORLD.Size(); // initialize data structures receiveBuffer = new int[1]; sendBuffer = new int[1]; row = new int[size]; if (rank == 0) { matrix = new int[size * size]; for (int i = 0; i < size * size; ++i) { matrix[i] = 0; } matrix[0] = 1; receiveBuffer[0] = 0; // process 0 never receives!!! } else { matrix = null; } // distribute the rows of the matrix to the appropriate processes MPI.COMM_WORLD.Scatter(matrix, rank * size, size, MPI.INT, row, 0, size, MPI.INT, 0); for (int col = 0; col < size; ++col) { if (rank > 0) { MPI.COMM_WORLD.Recv(receiveBuffer, 0, 1, MPI.INT, rank - 1, 0); } int leftValue = col == 0 ? 0 : row[col - 1]; row[col] = row[col] + leftValue + receiveBuffer[0]; sendBuffer[0] = row[col]; if (rank + 1 < size) { MPI.COMM_WORLD.Send(sendBuffer, 0, 1, MPI.INT, rank + 1, 0); } } // retrieve the rows from the processes into the matrix MPI.COMM_WORLD.Gather(row, 0, size, MPI.INT, matrix, rank * size, size, MPI.INT, 0); // display the result if (rank == 0) { for (int y = 0; y < size; ++y) { for (int x = 0; x < size; ++x) { System.out.print(matrix[size * y + x] + " "); } System.out.println(); } } MPI.Finalize(); } }