0% found this document useful (0 votes)
23 views6 pages

Anshu Practical 4

Uploaded by

zeelmg875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views6 pages

Anshu Practical 4

Uploaded by

zeelmg875
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Enrollment Number : 202103103510419

Practical 10
Aim: Implement Bully/Ring election algorithm.

(1) Ring election algorithm.


Code:
class Node:
def __init__(self, id):
self.id = id
self.active = True

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

def send_message(self, start_node_id):


"""Simulate message passing around the ring"""
message = start_node_id
index = (self.find_node_index(start_node_id) + 1) % self.n
traversed_nodes = []

while True:
current_node = self.nodes[index]

# Log the message transfer


if current_node.active:
print(f"Node {current_node.id} receives message: {message}")
traversed_nodes.append(current_node.id)

# Update the message to carry the highest ID


if current_node.id > message:
message = current_node.id

# Move to the next node in the ring


index = (index + 1) % self.n

# If the message comes back to the starting node, stop


if self.nodes[index].id == start_node_id:

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)


Enrollment Number : 202103103510419

break

return message, traversed_nodes

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

print(f"Node {initiator.id} starts the election")

# Pass messages around the ring


leader_id, traversed_nodes = self.send_message(initiator.id)

print(f"Leader is Node {leader_id}")


print(f"Nodes involved in the election: {traversed_nodes}")

# Set only the leader as active, others as inactive


for node in self.nodes:
if node.id == leader_id:
node.active = True
else:
node.active = False

return leader_id

def find_node_index(self, node_id):


"""Find the index of the node with the given ID"""
for i, node in enumerate(self.nodes):
if node.id == node_id:
return i
raise ValueError(f"Node with ID {node_id} not found.")

def reactivate_node(self, node_id):


"""Reactivate a node to participate in future elections"""
for node in self.nodes:
if node.id == node_id:
node.active = True
print(f"Node {node_id} has been reactivated.")
return
print(f"Node {node_id} not found.")

def deactivate_node(self, node_id):


"""Deactivate a node to simulate failure"""
for node in self.nodes:
if node.id == node_id:
node.active = False
print(f"Node {node_id} has been deactivated.")

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)


Enrollment Number : 202103103510419

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]

# Initialize the ring election system


election = RingElection(nodes)

# Run the election process


leader = election.elect_leader()

print(f"The elected leader is Node {leader}\n")

# Simulate reactivation of a node and run another election


election.reactivate_node(3)
leader = election.elect_leader()

print(f"The newly elected leader is Node {leader}\n")

# Simulate deactivation of a node and run another election


election.deactivate_node(7)
leader = election.elect_leader()

print(f"The newly elected leader is Node {leader}")


Output:

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)


Enrollment Number : 202103103510419

(2) Bully election algorithm.


Code:
import random
import time
import threading

class Process:
def __init__(self, pid):
self.pid = pid
self.is_coordinator = False
self.active = True

def start_election(self, processes):


"""Initiate the election process"""
print(f"Process {self.pid} starts an election.")
higher_ids = [p for p in processes if p.pid > self.pid and p.active]

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 receive_election(self, sender, processes):


"""Receive election message from another process"""
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):


"""Announce this process as the coordinator"""
print(f"Process {self.pid} becomes the coordinator!")
self.is_coordinator = True
for p in processes:
if p.active and p != self:
p.announce_coordinator(self)

def announce_coordinator(self, coordinator):


"""Acknowledge the new coordinator"""
print(f"Process {self.pid} acknowledges Process {coordinator.pid} as the coordinator.")

def fail(self):
"""Simulate process failure"""
self.active = False

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)


Enrollment Number : 202103103510419

print(f"Process {self.pid} has failed.")

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()

# Wait for a bit to simulate real-life time delays


time.sleep(1)

# Initiate election from a random active process


initiator = random.choice([p for p in processes if p.active])
initiator.start_election(processes)

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)]

# Simulate the election process


simulate_election(processes)

Output:

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)


Enrollment Number : 202103103510419

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

def start_election(self, processes):


print(f"Process {self.pid} starts an election.")
higher_ids = [p for p in processes if p.pid > self.pid and p.active]

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)

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!"

CGPIT/CE/SEM-7/DIV – B (BATCH -2)/Distributed Computing System (CE6004)

You might also like