-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRoundRobin_v2.java
More file actions
54 lines (45 loc) · 1.84 KB
/
RoundRobin_v2.java
File metadata and controls
54 lines (45 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import mpi.*;
import java.nio.*;
import java.util.Random;
public class RoundRobin_v2 {
public static void main(String[] args) throws MPIException {
MPI.Init(args);
int size = MPI.COMM_WORLD.getSize();
int rank = MPI.COMM_WORLD.getRank();
if (size < 2) {
System.out.println("Enter at least 2 processes to have 1 Master and 1 worker");
MPI.Finalize();
System.exit(1);
}
Random random = new Random();
int bufferSize = 100;
IntBuffer buffer = MPI.newIntBuffer(bufferSize);
if (rank == 0) {
// Master node
int initialNumber = random.nextInt(100);
buffer.put(0, initialNumber);
MPI.COMM_WORLD.send(buffer, 1, MPI.INT, 1, 0);
System.out.println("Master sent initial number: " + initialNumber);
// Receive the final message
buffer.clear();
MPI.COMM_WORLD.recv(buffer, bufferSize, MPI.INT, size - 1, 0);
System.out.print("Master received final numbers: ");
for (int i = 0; i < size; i++) {
System.out.print(buffer.get(i) + " ");
}
System.out.println();
} else {
// Worker nodes
int sourceRank = rank - 1;
int destinationRank = (rank + 1) % size;
MPI.COMM_WORLD.recv(buffer, bufferSize, MPI.INT, sourceRank, 0);
int receivedNumber = buffer.get(rank - 1);
System.out.println("Worker " + rank + " received number: " + receivedNumber);
int newNumber = random.nextInt(100);
buffer.put(rank, newNumber);
MPI.COMM_WORLD.send(buffer, bufferSize, MPI.INT, destinationRank, 0);
System.out.println("Worker " + rank + " added number: " + newNumber);
}
MPI.Finalize();
}
}