num = []
print("Enter 3 numbers:")
for i in range(3):
n = int(input())
num.append(n)
for i in range(3):
print(num[i])
def sjf_scheduling(n, burst_times):
processes = list(range(1, n + 1))
for i in range(n):
pos = i
for j in range(i + 1, n):
if burst_times[j] < burst_times[pos]:
pos = j
burst_times[i], burst_times[pos] = burst_times[pos], burst_times[i]
processes[i], processes[pos] = processes[pos], processes[i]
waiting_time = [0] * n
total_wt = 0
for i in range(1, n):
waiting_time[i] = sum(burst_times[:i])
total_wt += waiting_time[i]
avg_wt = total_wt / n
turnaround_time = [burst_times[i] + waiting_time[i] for i in range(n)]
total_tat = sum(turnaround_time)
avg_tat = total_tat / n
print("\nProcess\t Burst Time\t Waiting Time\t Turnaround Time")
for i in range(n):
print(f"P[{processes[i]}]\t {burst_times[i]}\t\t {waiting_time[i]}\t\t {turnaround_time[i]}")
print(f"\nAverage Waiting Time: {avg_wt:.2f}")
print(f"Average Turnaround Time: {avg_tat:.2f}")
if __name__ == "__main__":
n = int(input("Enter number of processes: "))
burst_times = []
print("Enter burst times:")
for i in range(n):
bt = int(input(f" P[{i+1}]: "))
burst_times.append(bt)
sjf_scheduling(n, burst_times)
n = int(input("Enter Total No. of Processes: "))
bt = []
wt = [0] * n
tat = [0] * n
print("Enter Process Burst Time:")
for i in range(n):
bt.append(int(input(f"P[{i + 1}]: ")))
wt[0] = 0
for i in range(1, n):
wt[i] = 0
for j in range(i):
wt[i] += bt[j]
awt = 0
avtat = 0
print("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
tat[i] = bt[i] + wt[i]
awt += wt[i]
avtat += tat[i]
print(f"P[{i + 1}]\t\t{bt[i]}\t\t{wt[i]}\t\t{tat[i]}")
awt /= n
avtat /= n
print(f"\nAverage Waiting Time: {awt:.2f}")
print(f"Average Turnaround Time: {avtat:.2f}")
n = int(input("Enter Total No. of Processes: "))
processes = []
wt = [0] * n
tat = [0] * n
print("Enter burst time and priority")
for i in range(n):
print(f"P[{i + 1}]")
bt_val = int(input("Bursttime:"))
pr_val = int(input("Priority:"))
processes.append([i + 1, bt_val, pr_val])
processes.sort(key=lambda x: x[2])
bt = [x[1] for x in processes]
p_ids = [x[0] for x in processes]
wt[0] = 0
for i in range(1, n):
wt[i] = 0
for j in range(i):
wt[i] += bt[j]
awt = 0
avtat = 0
print("\nProcess\tBursttime\tWaitingtime\tTurnaroundtime")
for i in range(n):
tat[i] = bt[i] + wt[i]
awt += wt[i]
avtat += tat[i]
print(f"P[{p_ids[i]}]\t\t{bt[i]}\t\t{wt[i]}\t\t{tat[i]}")
awt /= n
avtat /= n
print(f"\nAverage waiting time:{awt:.0f}")
print(f"Average turnaround time:{avtat:.0f}")
def round_robin_scheduling():
n = int(input("Enter the total number of processes: "))
bt = []
ct = []
wt = [0] * n
tat = [0] * n
for i in range(n):
burst = int(input(f"Enter the burst time for process {i+1}: "))
bt.append(burst)
ct.append(burst)
t = int(input("Enter the size of time slice: "))
temp = 0
while True:
done = True
for i in range(n):
if bt[i] > 0:
done = False
if bt[i] <= t:
temp += bt[i]
tat[i] = temp
bt[i] = 0
else:
bt[i] -= t
temp += t
if done:
break
awt = 0
att = 0
for i in range(n):
wt[i] = tat[i] - ct[i]
att += tat[i]
awt += wt[i]
att /= n
awt /= n
print(f"\nAverage Turnaround Time: {att}")
print(f"Average Waiting Time: {awt}")
print("\nProcess\tBurst Time\tWaiting Time\tTurnaround Time")
for i in range(n):
print(f"P[{i+1}]\t\t{ct[i]}\t\t{wt[i]}\t\t{tat[i]}")
round_robin_scheduling()
wrt = 1
mutex = 1
rc = 0
def signal():
global wrt, mutex
wrt = 1
mutex = 1
def write():
global wrt, mutex, rc
if wrt == 1 and mutex == 1:
print("user are writing")
wrt = 0
mutex = 0
elif rc > 0:
t = input("Someone is reading. Do you want to stop? (y/n): ")
if t.lower() == 'y':
rc = 0
signal()
else:
t = input("Someone is writing. Do you want to stop? (y/n): ")
if t.lower() == 'y':
signal()
def read():
global wrt, mutex, rc
wrt = 0
if mutex == 1:
rc += 1
print(f"user are Reading")
else:
print("Someone is writing")
def main():
global wrt, mutex, rc
wrt = 1
mutex = 1
rc = 0
while True:
print("\nselect the option:")
print("1.Write")
print("2.Read")
print("3.Exit")
s = int(input())
if s == 1:
write()
elif s == 2:
read()
elif s == 3:
break
else:
print("Invalid choice. Try again.")
if __name__ == "__main__":
main()
def bankers_algorithm():
n = int(input("Enter the number of processes: "))
m = int(input("Enter the number of resources: "))
alloc = []
maxm = []
print("\nEnter the allocation matrix:")
for i in range(n):
row = list(map(int, input().split()))
alloc.append(row)
print("\nEnter the max matrix:")
for i in range(n):
row = list(map(int, input().split()))
maxm.append(row)
print("\nEnter the available resources:")
avail = list(map(int, input().split()))
need = [[maxm[i][j] - alloc[i][j] for j in range(m)] for i in range(n)]
print("\nNeed matrix is:")
for i in range(n):
print(*need[i])
work = avail[:]
finish = [0] * n
safe_sequence = []
while len(safe_sequence) < n:
allocated = False
for i in range(n):
if finish[i] == 0:
if all(need[i][j] <= work[j] for j in range(m)):
for j in range(m):
work[j] += alloc[i][j]
safe_sequence.append(i)
finish[i] = 1
allocated = True
if not allocated:
print("\nSystem is not in a safe state.")
return
print("\nFollowing is the safeSequence")
for i in safe_sequence:
print(f"P{i}")
bankers_algorithm()
def fifo_page_replacement():
n = int(input("Enter the number of pages: "))
print("Enter the page reference string (space-separated):")
a = list(map(int, input().split()))
no = int(input("Enter the number of frames: "))
frame = [-1] * no
j = 0
count = 0
print("\nref string\tpage frames")
for i in range(n):
print(f"{a[i]}\t\t", end="")
avail = False
for k in range(no):
if frame[k] == a[i]:
avail = True
break
if not avail:
frame[j] = a[i]
j = (j + 1) % no
count += 1
for k in range(no):
print(frame[k], end="\t")
print()
print(f"\npage fault is:{count}")
fifo_page_replacement()
def optimal_page_replacement(pages, frames_count):
frames = []
page_faults = 0
for i in range(len(pages)):
page = pages[i]
if page in frames:
print(page, "\t", " ".join(map(str, frames)))
continue
page_faults += 1
if len(frames) < frames_count:
frames.append(page)
else:
future_use = []
for f in frames:
if f in pages[i+1:]:
future_use.append(pages[i+1:].index(f))
else:
future_use.append(float('inf'))
replace_index = future_use.index(max(future_use))
frames[replace_index] = page
print(page, "\t", " ".join(map(str, frames)))
print(f"\nThe no of page faults is {page_faults}")
if __name__ == "__main__":
n = int(input("Enter no of pages: "))
pages = list(map(int, input("Enter the reference string: ").split()))
f = int(input("Enter no of frames: "))
optimal_page_replacement(pages, f)
def first_fit(bsize, psize):
bno = len(bsize)
pno = len(psize)
flags = [0] * bno
allocation = [-1] * pno
for i in range(pno):
for j in range(bno):
if flags[j] == 0 and bsize[j] >= psize[i]:
allocation[i] = j
flags[j] = 1
break
print("\nBlock no.\tsize\t\tprocess no.\tsize")
for i in range(bno):
print(f"{i+1}\t\t{bsize[i]}\t\t", end="")
if i in allocation:
proc_idx = allocation.index(i)
print(f"{proc_idx+1}\t\t{psize[proc_idx]}")
else:
print("Not allocated")
if __name__ == "__main__":
bno = int(input("Enter no. of blocks: "))
bsize = list(map(int, input("Enter size of each block: ").split()))
pno = int(input("Enter no. of processes: "))
psize = list(map(int, input("Enter size of each process: ").split()))
first_fit(bsize, psize)
def best_fit(blocks, processes):
nb = len(blocks)
np = len(processes)
barray = [0] * nb
parray = [-1] * np
fragment = [0] * np
for i in range(np):
lowest = 9999
chosen_block = -1
for j in range(nb):
if barray[j] == 0:
temp = blocks[j] - processes[i]
if temp >= 0 and temp < lowest:
chosen_block = j
lowest = temp
if chosen_block != -1:
parray[i] = chosen_block
fragment[i] = lowest
barray[chosen_block] = 1
print("\nProcess_no\tProcess_size\tBlock_no\tBlock_size\tFragment")
for i in range(np):
if parray[i] != -1:
print(f"{i+1}\t\t{processes[i]}\t\t{parray[i]+1}\t\t{blocks[parray[i]]}\t\t{fragment[i]}")
else:
print(f"{i+1}\t\t{processes[i]}\t\tNot Allocated")
if __name__ == "__main__":
nb = int(input("Enter the number of blocks: "))
blocks = list(map(int, input("Enter the size of each block: ").split()))
np = int(input("Enter the number of processes: "))
processes = list(map(int, input("Enter the size of each process: ").split()))
best_fit(blocks, processes)
def worst_fit(blocks, processes):
nBlocks = len(blocks)
nProcess = len(processes)
print("\nProcess No.\tProcess Size\tBlock no.")
for i in range(nProcess):
max_size = -1
pos = -1
for j in range(nBlocks):
if blocks[j] > max_size:
max_size = blocks[j]
pos = j
if max_size >= processes[i]:
print(f"{i+1}\t\t{processes[i]}\t\t{pos+1}")
blocks[pos] -= processes[i]
else:
print(f"{i+1}\t\t{processes[i]}\t\tNot Allocated")
if __name__ == "__main__":
nBlocks = int(input("Enter the number of blocks: "))
blocks = list(map(int, input(f"Enter the size of {nBlocks} blocks: ").split()))
nProcess = int(input("Enter the number of processes: "))
processes = list(map(int, input(f"Enter the size of {nProcess} processes: ").split()))
worst_fit(blocks, processes)
from multiprocessing import shared_memory
import time
shm_name = "PSM-6b986bba"
print(f"Shared Memory Name: {shm_name}")
mode = input("1. Sender\n2. Receiver\nEnter choice: ")
if mode == '1':
shm = shared_memory.SharedMemory(create=True, size=1024, name=shm_name)
data = input("Enter some data to write to shared memory:\n")
shm.buf[:len(data)] = data.encode()
print(f"you wrote? {data}")
print("Keep this program running until the receiver reads the data.")
input("Press Enter to exit...")
shm.close()
shm.unlink()
else:
shm = shared_memory.SharedMemory(name=shm_name)
data = bytes(shm.buf[:100]).decode().rstrip('\x00')
print(f"Data read from shared memory:\n{data}")
input("Press Enter to exit...")
shm.close()