Last active
July 26, 2020 04:06
-
-
Save youngkaneda/e5fbe49a02da6f3ff61fed9735159a4c to your computer and use it in GitHub Desktop.
Bakery algorithm for mutual exclusion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pid goes from 0 to THREAD_POOL_SIZE - 1 | |
public class Bakery { | |
private static int THREAD_POOL_SIZE = 10; | |
private volatile static boolean[] guests = new boolean[THREAD_POOL_SIZE]; | |
private volatile static int[] tickets = new int[THREAD_POOL_SIZE]; | |
public void lock(int pid) { | |
guests[pid] = true; | |
synchronized (tickets) { | |
OptionalInt max = Arrays.stream(tickets).max(); | |
int ticket = 1; | |
if (max.isPresent()) { | |
ticket += max.getAsInt(); | |
} | |
tickets[pid] = ticket; | |
} | |
guests[pid] = false; | |
// | |
for(int i = 0; i < THREAD_POOL_SIZE; i++) { | |
while(guests[i]) { | |
/*wait*/ | |
} | |
while(tickets[i] != 0 && (tickets[i] < tickets[pid])) { | |
/*wait*/ | |
} | |
break; | |
}; | |
} | |
public void unlock(int pid) { | |
tickets[pid] = 0; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment