Operating System With Python
Operating System With Python
def diamond(n):
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * (2 * i - 1))
for i in range(n - 1, 0, -1):
print(' ' * (n - i) + '*' * (2 * i - 1))
diamond(5)
2. Shortest Job First Algorithm
print("Shortest Job First (Non-Preemptive) programming!".center(105, "~"), "\n")
# Processes
P = ['p1', 'p2', 'p3', 'p4']
p = P.copy()
# Arrival Times
AT = [0, 1, 2, 3]
at = AT.copy()
# Burst Times
BT = [8, 4, 9, 5]
bt = BT.copy()
GC = [] # Gantt chart
for i in range(len(P)):
miv = bt.index(min(bt)) # Find index of the minimum burst time
if i == 0:
miv = at.index(min(at)) # Find index of the minimum arrival time initially
GC.append([at[miv], p[miv], bt[miv]])
else:
GC.append([GC[i - 1][2], p[miv], GC[i - 1][2] + bt[miv]])
at.pop(miv)
p.pop(miv)
bt.pop(miv)
for i in range(len(P)):
index = P.index(GC[i][1])
CT[index] = GC[i][2]
TAT[index] = CT[index] - AT[index]
WT[index] = TAT[index] - BT[index]
# Calculate averages
avg_TAT = sum(TAT) / len(P)
avg_WT = sum(WT) / len(P)
print(f"Average Turn Around Time: {avg_TAT}")
print(f"Average Waiting Time: {avg_WT}")
3. First Come First Served Algorithm.
d = {}
# Calculating Exit Time (ET), Turnaround Time (TAT), and Waiting Time (WT)
ET = []
TAT = []
WT = []
for i in range(len(d)):
if i == 0:
ET.append(d[i][1][0] + d[i][1][1]) # Exit time for first process
else:
ET.append(max(d[i][1][0], ET[i - 1]) + d[i][1][1])
# Keep traversing processes in round robin manner until all are done
while True:
done = True
# Time quantum
quantum = 4
5.Priority Scheduling
findWaitingTime(processes, n, wt)
findTurnAroundTime(processes, n, wt, tat)
for i in proc:
print(i[0], end=" ")
print() # Print newline for better formatting
findavgTime(proc, n)
if __name__ == "__main__":
# Process IDs, Burst time, and Priority
proc = [
[1, 10, 3],
[2, 1, 1],
[3, 2, 3],
[4, 1, 4],
[5, 5, 2]
]
n=5
priorityScheduling(proc, n)
class ReaderWriterProblem:
def __init__(self):
self.mutex = threading.Semaphore(1) # Semaphore for mutual exclusion
self.wrt = threading.Semaphore(1) # Semaphore for controlling write access
self.r_c = 0 # Number of current readers
def reader(self):
while True:
self.mutex.acquire()
self.r_c += 1
if self.r_c == 1:
self.wrt.acquire() # First reader acquires write lock
self.mutex.release()
self.mutex.acquire()
self.r_c -= 1
if self.r_c == 0:
self.wrt.release() # Last reader releases write lock
self.mutex.release()
time.sleep(3)
def writer(self):
while True:
self.wrt.acquire()
print("Writing data .......")
print("-" * 20)
self.wrt.release()
time.sleep(3)
def main(self):
t1 = threading.Thread(target=self.reader)
t2 = threading.Thread(target=self.writer)
t3 = threading.Thread(target=self.reader)
t4 = threading.Thread(target=self.reader)
t5 = threading.Thread(target=self.reader)
t6 = threading.Thread(target=self.writer)
t1.start()
t2.start()
t3.start()
t4.start()
t5.start()
t6.start()
if __name__ == "__main__":
rw = ReaderWriterProblem()
rw.main()
7. To implement Banker’s algorithm for Deadlock avoidance.
Program for page replacement algorithms:
P = 5 # Number of processes
R = 3 # Number of resources
finish = [0] * P
safeSeq = []
work = avail[:]
count = 0
while count < P:
found = False
for p in range(P):
if finish[p] == 0:
# Check if the current process can be executed
for j in range(R):
if need[p][j] > work[j]:
break
else:
# If all resources for current process can be allocated
for k in range(R):
work[k] += allot[p][k]
safeSeq.append(p)
finish[p] = 1
found = True
count += 1
if not found:
print("System is not in a safe state")
return False
if __name__ == "__main__":
processes = [0, 1, 2, 3, 4]
avail = [3, 3, 2]
maxm = [
[7, 5, 3],
[3, 2, 2],
[9, 0, 2],
[2, 2, 2],
[4, 3, 3]
]
allot = [
[0, 1, 0],
[2, 0, 0],
[3, 0, 2],
[2, 1, 1],
[0, 0, 2]
]
for i in range(n):
if len(s) < capacity:
if pages[i] not in s:
s.add(pages[i])
page_faults += 1
indexes.put(pages[i])
else:
if pages[i] not in s:
val = indexes.queue[0]
indexes.get()
s.remove(val)
s.add(pages[i])
indexes.put(pages[i])
page_faults += 1
return page_faults
if __name__ == "__main__":
pages = [3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4]
n = len(pages)
capacity = 3
print("Total page fault count:", pageFaults(pages, n, capacity))
9. Least Recently Used Algorithm.
# Python3 program for LRU page replacement algorithm
# Check length of the pages list. If less than page size, append ref_page
if len(pages) < page_size:
pages.append(ref_page)
else:
# If full, remove the least recently used page (first element) and append ref_page
pages.pop(0)
pages.append(ref_page)
if __name__ == "__main__":
# Given page size and reference string
page_size = 3
reference_string = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 1, 2, 0]
10. To implement first fit, best fit and worst fit algorithm for memory management.
def FirstFit(block_size, blocks, process_size, processes):
allocate = [-1] * processes
occupied = [False] * blocks
for i in range(processes):
for j in range(blocks):
if not occupied[j] and (block_size[j] >= process_size[i]):
allocate[i] = j
occupied[j] = True
break
FirstFit(block_size, m, process_size, n)
# Pick each process and find suitable blocks according to its size and assign to it
for i in range(n):
# Find the best fit block for current process
bestIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if bestIdx == -1 or blockSize[bestIdx] > blockSize[j]:
bestIdx = j
bestFit(blockSize, m, processSize, n)
# Pick each process and find suitable blocks according to its size and assign to it
for i in range(n):
# Find the worst fit block for the current process
wstIdx = -1
for j in range(m):
if blockSize[j] >= processSize[i]:
if wstIdx == -1 or blockSize[wstIdx] < blockSize[j]:
wstIdx = j
# Driver code
if __name__ == '__main__':
blockSize = [100, 500, 200, 300, 600]
processSize = [212, 417, 112, 426]
m = len(blockSize)
n = len(processSize)
worstFit(blockSize, m, processSize, n)
def receiver(conn):
"""
Function to print the messages received from the other
end of the pipe
"""
while True:
msg = conn.recv()
if msg == "END":
break
print("Received the message: {}".format(msg))
if __name__ == "__main__":
# Messages to be sent
msgs = ["hello", "hey", "hru?", "END"]
# Creating a pipe
parent_conn, child_conn = multiprocessing.Pipe()
# Running processes
p1.start()
p2.start()