Parallel Programming WS 2014/2015 - File Main.java
import java.util.Iterator; public class Main { static final int N = 7; // number of nodes in example graph static final int INITIATOR = 0; // index of initiator node static int result = 0; // stores the resulting sum of numbers public static void main (String[] args) { // build the example net shown on PPJ-73 Node[] nodes = new Node[N]; for (int i = 0; i < N; i++) nodes[i] = new Node(i, i + 3); Node.connect(nodes[0], nodes[1]); Node.connect(nodes[0], nodes[5]); Node.connect(nodes[1], nodes[2]); Node.connect(nodes[2], nodes[3]); Node.connect(nodes[4], nodes[2]); Node.connect(nodes[4], nodes[6]); Node.connect(nodes[5], nodes[4]); Node.connect(nodes[5], nodes[6]); // create a thread for each node Thread[] probers = new Thread[N]; for (int i = 0; i < N; i++) probers[i] = new Prober(nodes[i]); System.out.println("Starting prober threads..."); for (int i = 0; i < N; i++) probers[i].start(); try { for (int i = 0; i < N; i++) probers[i].join(); } catch (InterruptedException ie) { /* ignore */ } System.out.println("The answer is: " + result); } static class Prober extends Thread { private Node myNode; Prober (Node node) { myNode = node; } public void run () { if (isInitiator()) runInitiator(); else runNormalNode(); } private void runNormalNode () { // as outlined on PPJ-74 // ... } private void runInitiator () { // trigger probe and collect final result // send a probe to all neighbours Iterator nbs = myNode.getNeighbours(); while (nbs.hasNext()) { Node nb = (Node) nbs.next(); Message probe = Message.createProbe(myNode); nb.getInputChannel().send(probe); } int n = myNode.getNumberOfNeighbours(); int outstandingMsgs = n; // number of dummies and echoes to expect: // all neighbours will answer int sum = myNode.getValue(); // partial sum of values starts with our own value while (outstandingMsgs > 0) { Message msg = myNode.getInputChannel().receive(); switch(msg.getKind()) { case Message.PROBE: // initiator gives all probes a dummy message response Message dummy = Message.createDummy(myNode); msg.getSender().getInputChannel().send(dummy); break; case Message.ECHO: sum += msg.getValue(); // consider value in partial sum /* fall through */ case Message.DUMMY: outstandingMsgs -= 1; break; } } result = sum; // store final sum in variable of enclosing class } boolean isInitiator () { return myNode.getNodeID() == INITIATOR; } } }
Generiert mit Camelot | Probleme mit Camelot? | Geändert am: 02.02.2015