+/EE360P

distributed systems

git clone https://git.julia.blue/+/EE360P

vijaygarg1init5384742

master
1.6 KiB58 linesraw
1package mutex;
2import dist.*; import clocks.*; import java.util.*;
3public class LamportMutex extends MyProcess implements Lock {
4	LamportClock c;
5	int numAcks;
6	Queue<Timestamp> q; // request queue
7	public LamportMutex(Linker initComm) {
8		super(initComm);
9		c = new LamportClock();
10		q = new PriorityQueue<Timestamp>(n, 	
11				new Comparator<Timestamp>() {
12			public int compare(Timestamp a, Timestamp b) {
13				return Timestamp.compare(a, b);
14			}
15		});
16		numAcks = 0;
17	}
18	public synchronized void requestCS() {
19		c.tick();
20		q.add(new Timestamp(c.getValue(), myId));
21		sendMsg(neighbors, "request", c.getValue());
22		numAcks = 0;
23		while ((q.peek().pid != myId) || (numAcks < n-1))
24			myWait();
25	}
26	public synchronized void releaseCS() {
27		q.remove();
28		sendMsg(neighbors, "release", c.getValue());
29	}
30	public synchronized void handleMsg(Msg m, int src, String tag) {
31		int timeStamp = m.getMessageInt();
32		c.receiveAction(src, timeStamp);
33		if (tag.equals("request")) {
34			q.add(new Timestamp(timeStamp, src));
35			sendMsg(src, "ack",c.getValue());
36		} else if (tag.equals("release")) {
37
38			Iterator<Timestamp> it =  q.iterator();			    
39			while (it.hasNext()){
40				if (it.next().getPid() == src) it.remove();
41			}
42		} else if (tag.equals("ack"))
43			numAcks++;
44		notifyAll();
45	}
46	public static void main(String args[]) throws Exception {
47		Linker comm = new Linker(args);
48		Lock lock = new LamportMutex(comm);
49		lock.init(null);
50		for (int i = 0; i < 5; i++) {
51			lock.requestCS();
52			System.out.println(comm.getMyId() + " is in CS ******");
53			Util.mySleep(2000);
54			lock.releaseCS();
55			System.out.println(comm.getMyId() + " is not in CS");
56		}
57	}
58}