+/EE360P

distributed systems

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

vijaygarg1init7910ba6

master
1.2 KiB45 linesraw
1package mutex;
2import dist.*;
3public class CircToken extends MyProcess implements Lock {
4    boolean haveToken;
5    boolean wantCS = false;
6    final int leader = 0;
7    public CircToken(MsgHandler initComm) {
8        super(initComm);
9        haveToken = (myId == leader);
10       // if (haveToken) sendToken();
11    }
12    public void init(MsgHandler app) {
13    	super.init(app);
14        if (haveToken) sendToken();
15    }
16    public synchronized void requestCS() {
17        wantCS = true;
18        while (!haveToken) myWait();
19    }
20    public synchronized void releaseCS() {
21        wantCS = false;
22        sendToken();
23    }
24    public synchronized boolean getHaveToken(){
25    	return haveToken;
26    }
27    void sendToken() {
28        if (haveToken && !wantCS) {
29            int next = (myId + 1) % N;
30            Util.println("Process " + myId + "has sent the token");
31            sendMsg(next, "token");
32            haveToken = false;
33        }
34    }
35    public synchronized void handleMsg(Msg m, int src, String tag) {
36        if (tag.equals("token")) {
37            haveToken = true;
38            if (!wantCS) {
39                Util.mySleep(1000);
40                sendToken();
41            }
42            notifyAll();
43        }
44    }
45}