Anshu Practical 4
Anshu Practical 4
Practical 10
Aim: Implement Bully/Ring election algorithm.
def __repr__(self):
return f"Node {self.id}"
class RingElection:
def __init__(self, nodes):
self.nodes = nodes
self.n = len(nodes)
def find_active_node(self):
"""Find the first active node to initiate the election"""
for node in self.nodes:
if node.active:
return node
return None
while True:
current_node = self.nodes[index]
break
def elect_leader(self):
"""Conduct an election and determine the leader"""
initiator = self.find_active_node()
if not initiator:
print("No active nodes in the system.")
return None
return leader_id
return
print(f"Node {node_id} not found.")
if __name__ == "__main__":
# Create nodes with unique IDs
node_ids = [1, 3, 7, 2, 5]
nodes = [Node(id) for id in node_ids]
class Process:
def __init__(self, pid):
self.pid = pid
self.is_coordinator = False
self.active = True
if higher_ids:
print(f"Process {self.pid} found higher IDs: {[p.pid for p in higher_ids]}.")
for p in higher_ids:
p.receive_election(self, processes)
else:
self.become_coordinator(processes)
def fail(self):
"""Simulate process failure"""
self.active = False
def simulate_election(processes):
"""Simulate a process failure and initiate the election"""
# Randomly fail one process to start an election
failed_process = random.choice(processes)
failed_process.fail()
if __name__ == "__main__":
# Create a list of processes with unique IDs
process_count = 5
processes = [Process(pid=i) for i in range(1, process_count + 1)]
Output:
Practical 9
Aim: Implement clock synchronization algorithm using a counter.
Code:
import random
import time
import threading
class Process:
def __init__(self, pid):
self.pid = pid
self.is_coordinator = False
self.active = True
if higher_ids:
else:
self.become_coordinator(processes)
def receive_election(self, sender):
print(f"Process {self.pid} received an election message from Process {sender.pid}.")
if self.active:
print(f"Process {self.pid} is responding to the election.")
self.start_election(processes)
def become_coordinator(self, processes):
print(f"Process {self.pid} becomes the coordinator!"