Untitled
unknown
plain_text
9 months ago
2.9 kB
14
Indexable
# Banker's Algorithm
def bankers_algorithm(alloc, max_need, avail):
n = len(alloc) # number of processes
m = len(avail) # number of resources
need = [[max_need[i][j] - alloc[i][j] for j in range(m)] for i in range(n)]
finish = [0] * n
safe_seq = []
work = avail[:]
while len(safe_seq) < n:
found = False
for i in range(n):
if not finish[i] and all(need[i][j] <= work[j] for j in range(m)):
for j in range(m):
work[j] += alloc[i][j]
safe_seq.append(i)
finish[i] = 1
found = True
if not found:
print("System is not in safe state.")
return
print("System is in safe state.\nSafe sequence:", ' → '.join('P'+str(i) for i in safe_seq))
# Example Input
alloc = [[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]]
max_need = [[7, 5, 3],
[3, 2, 2],
[9, 0, 2],
[2, 2, 2],
[4, 3, 3]]
avail = [3, 3, 2]
bankers_algorithm(alloc, max_need, avail)
-----------------------------------------------------------------------------------------------
# Bully Algorithm
def bully_algorithm(processes, crashed, initiator):
alive = [p for p in processes if p not in crashed]
print(f"Processes alive: {alive}")
print(f"Process {initiator} starts election...")
higher = [p for p in alive if p > initiator]
if not higher:
print(f"Process {initiator} becomes the Coordinator.")
else:
for p in higher:
print(f"Process {initiator} sends election message to {p}")
new_coordinator = max(higher)
print(f"Process {new_coordinator} becomes the Coordinator.")
# Example
processes = [1, 2, 3, 4, 5]
crashed = [5] # crashed process
initiator = 3 # who starts the election
bully_algorithm(processes, crashed, initiator)
-----------------------------------------------------------------------------------------------
# Ring Election Algorithm
def ring_algorithm(processes, initiator):
print(f"Processes in ring: {processes}")
print(f"Process {initiator} starts the election...")
index = processes.index(initiator)
msg = [initiator]
# Pass message around the ring
for i in range(1, len(processes)):
next_process = processes[(index + i) % len(processes)]
print(f"Message passed from {msg[-1]} to {next_process}")
msg.append(next_process)
coordinator = max(processes)
print(f"Process {coordinator} becomes the Coordinator.")
# Example
processes = [1, 2, 3, 4, 5]
initiator = 2
ring_algorithm(processes, initiator)
-----------------------------------------------------------------------------------------------
Editor is loading...
Leave a Comment