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