Skip to content

Instantly share code, notes, and snippets.

@wkdalsgh192
Last active May 27, 2021 17:20
Show Gist options
  • Save wkdalsgh192/7785137055a5b74b49b2ea58a7c5eec9 to your computer and use it in GitHub Desktop.
Save wkdalsgh192/7785137055a5b74b49b2ea58a7c5eec9 to your computer and use it in GitHub Desktop.
public class OS_Critical_Section_Solution {
public static void main(String[] args) {
boolean[] flag = new boolean[2]; // flag[0] -> Process A, flag[1] -> Process B
// Strict Alternation
int cnt = 0;
while(true) {
flag[0] = true;
while (flag[1]==true);
System.out.println("V");
flag[0] = false;
}
// Decker's Algorithm
// test 1 : Process A gets priority. No stuff for Process B.-> V would be printed continuously.
boolean turn = false; // turn is false for giving A priority.
// test 2 : Process A gets priority. Process B gets some stuffs to do -> V not be printed.
flag[1] = true;
// test 3 : B is prior to A but gets nothing to proceed -> V would be printed continuously.
flag[1] = false;
turn = true;
while (true) {
flag[0] = true;
while (flag[1] == true) {
if (turn == true) {
flag[0] = false;
while(turn == true);
flag[0] = true;
}
};
System.out.println("V");
flag[0] = false;
turn = true; // B gets priority.
}
// Peterson's Algorithm
while (true) {
flag[0] = true;
turn = true;
while (flag[1] && turn); // if B wants to get access in the current critical section and it is prior to all others, Process A could not get in.
System.out.println("V");
flag[0] = false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment