Skip to content

Instantly share code, notes, and snippets.

@thien
Created May 6, 2018 10:53
Show Gist options
  • Save thien/19489207b25d0acc0851ef147c990497 to your computer and use it in GitHub Desktop.
Save thien/19489207b25d0acc0851ef147c990497 to your computer and use it in GitHub Desktop.
Variable Speeds Distributed Leader Selection (Async Rings) Algorithm
class VariableSpeeds:
def __init__(self,id):
self.id = id
self.elected = False
# initially, min_i = id_i
self.min = self.id
self.received = 0
def receive(self,r, m):
# upon receiving <m> from the right
if m is not None:
self.received = r
if m < self.min:
self.elected = False
self.min = m
print(self.id,"- min is now", m)
if m == self.id:
self.elected = True
print(self.id, "is self elected.")
#else:
# print(self.id,"eh", end="")
def send(self, r):
shouldbeRoundsAgo = (2 ** self.min) -1
if shouldbeRoundsAgo == self.min:
print(self.id, "sending min:", self.min)
return self.min
if __name__ == "__main__":
numberOfCpus = 10
cpus = [VariableSpeeds(i) for i in range(numberOfCpus)]
#print([i.id for i in cpus])
for i in range(0,10):
print("Round", i)
# generate messages to send if it was received rounds ago.
messages = [j.send(round) for j in cpus]
messages = messages + [messages.pop(0)]
for m in range(len(messages)):
cpus[m].receive(round, messages[m])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment