Python Implementation of Eisenberg and McGuire's Algorithm
Description: This algorithm is alternative to the Bakery Algorithm, which does not use unique id numbers (at least not in the same way as the Bakery Algorithm)
It solves the Critical Section Problem for N Processes.
The common data structures are:
var flag: array [0 .. n-1] of (idle, waiting, active) ;
turn: 0 .. n-1 ;
All the elements of the flag are initially idle, the initial value of "turn" is
immaterial (between 0 and n-1).
Let's understands the algorithm through the program, read comments carefully!
Program:
import threading
class Solution():
flags = [0]
turn = 0
n = 8
def entryProtocol(self,*args):
index = self.turn
while (not((index >= self.n) and ((self.turn == args[0]) or (self.flags[self.turn] == "IDLE")))):
self.flags[args[0]] = "WAITING"
index = self.turn
while (index != args[0]):
if (self.flags[index] != "IDLE"):
index = self.turn
else:
index = (index + 1) % self.n
self.flags[args[0]] = "ACTIVE"
index = 0
while ((index < self.n) and ((index == args[0]) or (self.flags[args[0]] != "ACTIVE"))):
index+=1
self.turn = args[0]
#End of critical section
def exitProtocol(self,*args):
index = (self.turn + 1) % self.n
#find a process which is not IDLE
while (self.flags[index] == "IDLE"):
index = (index + 1) % self.n
self.turn = index
self.flags[args[0]] = "IDLE"
def main(self):
for i in range(8):
t1 = threading.Thread(target = self.entryProtocol, args = (i,))
t1.start()
t2 = threading.Thread(target = self.exitProtocol, args = (i,))
t2.start()
if __name__ == '__main__':
d = Solution()
d.main()
Comments