/**
 * Algorithm_3.java
 *
 * This program implements strict alternation as a means of handling synchronization.
 * This solution corresponds to Algorithm 3
 *
 * @author Greg Gagne, Peter Galvin, Avi Silberschatz
 * @version 1.0 - July 15, 1999
 * @version 1.1 - March 14, 2000. Replaced volatile array with separate variables
 * 	as the volatile keyword does not extend to arrays.
 * Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz
 * Applied Operating Systems Concepts - John Wiley and Sons, Inc.
 */
 
 public class Algorithm_3 extends MutualExclusion
 {
   public Algorithm_3() {
	//flag[0] = false;
	//flag[1] = false;
	flag0 = false;
	flag1 = false;

	turn = TURN_0;
   }
  
   public void enteringCriticalSection(int t) {
		int other;

		other = 1 - t;

		//flag[t] = true;
		if (t == 0)
			flag0 = true;
		else
			flag1 = true;
		
		turn = other;

		//while ( (flag[other] == true) && (turn == other) )
		 	//Thread.yield();
		 
		if (t == 0) {
			while ( (flag1 == true) && (turn == other) )
				Thread.yield();
		}
		else {
			while ( (flag0 == true) && (turn == other) )
				Thread.yield();
		}	
   }

   public void leavingCriticalSection(int t) {
	//flag[t] = false;
		if(t == 0)
			flag0 = false;
		else
			flag1 = false;
   }

   private volatile int turn; 
   //private volatile boolean[] flag = new boolean[2];
   private volatile boolean flag0;
   private volatile boolean flag1;
}

