+/EE360P

distributed systems

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

vijaygarg1init5384742

master
1.1 KiB43 linesraw
1package mutex;
2import dist.*;
3import clocks.*;
4import java.util.*;
5public class RAMutex extends dist.MyProcess implements Lock {  
6	int myts;
7	LamportClock c = new LamportClock();
8	LinkedList<Integer> pendingQ = new LinkedList<Integer>();
9	int numOkay = 0;
10	public RAMutex(MsgHandler initComm) {
11		super(initComm);
12		myts = Integer.MAX_VALUE;
13	}
14	public synchronized void requestCS() {
15		c.tick();
16		myts = c.getValue();
17		sendMsg(neighbors,"request", myts);
18		numOkay = 0;
19		while (numOkay < n-1)
20			myWait(); 
21	}
22	public synchronized void releaseCS() {
23		myts = Integer.MAX_VALUE;
24		while (!pendingQ.isEmpty()) 
25			sendMsg(pendingQ.remove(), "okay", c.getValue());
26	}
27	boolean okayCS() {
28		if(myts == Integer.MAX_VALUE || numOkay <n-1) return false;
29		return true;
30	}
31	public synchronized void handleMsg(Msg m, int src, String tag) {
32		int timeStamp = m.getMessageInt();
33		c.receiveAction(src, timeStamp);
34		if (tag.equals("request")) {
35			if ((timeStamp < myts) || ((timeStamp == myts) && (src < myId)))
36				sendMsg(src, "okay", c.getValue());
37			else
38				pendingQ.add(src);
39		} else if (tag.equals("okay")) 
40			numOkay++;
41		notifyAll();
42	}
43}