0% found this document useful (0 votes)
9 views23 pages

Basic I/O Programming

Uploaded by

swethasureshin.s
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)
9 views23 pages

Basic I/O Programming

Uploaded by

swethasureshin.s
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/ 23

1. Basic I/O programming.

from multiprocessing import Process


import os

def f(name):
print(f'process: {os.getpid()}, parent: {os.getppid()}, hello {name}')

if __name__ == "__main__":
print(f'main process: {os.getpid()}')
p = Process(target=f, args=('bob',))
p.start()
p.join()
print(f'Child Process ID: {p.pid})
OUTPUT

main process: 19388


Child Process ID: 16960
2.Shortest Job First Algorithm.

def sjf(jobs):
# Sort jobs by burst time
jobs.sort(key=lambda x: x[1])

# Initialize current time and completed jobs


time = 0
completed = []

# Process jobs in order of shortest burst time


for job in jobs:
time += job[1]
completed.append((job[0], time))

return completed

# Example usage
jobs = [("Job1", 3), ("Job2", 1), ("Job3", 2), ("Job4", 4)]
result = sjf(jobs)
print("Job\tCompletion Time")
for job in result:
print(f"{job[0]}\t{job[1]}")
OUTPUT

Job Completion Time


Job2 1
Job3 3
Job1 6
Job4 10
3.First Come First Served Algorithm

def fcfs(jobs):
# Initialize current time and completed jobs
time = 0
completed = []

# Process jobs in order of arrival


for job in jobs:
time += job[1]
completed.append((job[0], time))

return completed

# Example usage
jobs = [("Job1", 3), ("Job2", 1), ("Job3", 2), ("Job4", 4)]
result = fcfs(jobs)
print("Job\tCompletion Time")
for job in result:
print(f"{job[0]}\t{job[1]}")
OUTPUT

Job Completion Time


Job1 3
Job2 4
Job3 6
Job4 10
4.Round Robin and Priority Scheduling Algorithm

def rr_priority(jobs, quantum):


jobs.sort(key=lambda x: x[2])
time = 0
completed = []
temp = []
for job in jobs:
temp.append(list(job))
jobs = temp
while jobs:
job = jobs.pop(0)
burst_time = min(job[1], quantum)
time += burst_time
completed.append((job[0], time))
job[1] -= burst_time
if job[1] > 0:
jobs.append(job)
return completed

jobs = [("Job1", 3, 2), ("Job2", 1, 3), ("Job3", 2, 1), ("Job4", 4, 4)]


quantum = 2
result = rr_priority(jobs, quantum)
print(result)
OUTPUT

[('Job3', 2), ('Job1', 4), ('Job2', 5), ('Job4', 7), ('Job1', 8), ('Job4', 10)]
5.To implement reader/writer problem using semaphore

import threading

resource = threading.Semaphore(1)
read_count = 0
read_ready = threading.Semaphore(1)
def reader():
read_ready.acquire()
global read_count
read_count += 1
if read_count == 1:
resource.acquire()
read_ready.release()
print("Reader is reading")
read_ready.acquire()
read_count -= 1
if read_count == 0:
resource.release()
read_ready.release()

def writer():
resource.acquire()
print("Writer is writing")
resource.release()

t1 = threading.Thread(target=reader)
t2 = threading.Thread(target=writer)
t1.start()
t2.start()
t1.join()
t2.join()
OUTPUT

Reader is reading
Writer is writing
6. Banker’s algorithm for Deadlock avoidance Program for
page replacement algorithm

def bankers_algorithm (need, max, allocation):


available = [3, 3, 2]
work = available.copy()
safe_state = True
for i in range(len(need)):
if need[i] > work:
safe_state = False
break
work -= allocation[i]
return safe_state

def fifo(pages, frame_size):


frames = []
page_faults = 0
for page in pages:
if page not in frames:
if len(frames) == frame_size:
frames.pop(0)
frames.append(page)
page_faults += 1
return page_faults

# Banker's algorithm inputs


need = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [0, 3, 3]]
max = [[3, 3, 2], [2, 2, 2], [10, 2, 1], [1, 1, 1], [0, 0, 2]]
allocation = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]]

# FIFO page replacement algorithm inputs


pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
frame_size = 3

# Run both algorithms


print("Banker's Algorithm:")
print("Safe state:", bankers_algorithm(need, max, allocation))
print("\nFIFO Page Replacement Algorithm:")
print("Page faults:", fifo(pages, frame_size))
OUTPUT

Banker's Algorithm:
Safe state: False

FIFO Page Replacement Algorithm:


Page faults: 10
7.First In First Out Algorithm

def fifo(pages, frame_size):


frames = []
page_faults = 0
for page in pages:
if page not in frames:
if len(frames) == frame_size:
frames.pop(0)
frames.append(page)
page_faults += 1
return page_faults

pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
frame_size = 3
print(fifo(pages, frame_size))
OUTPUT

10
8.Least Recently Used Algorithm.

from collections import OrderedDict

def lru(pages, frame_size):


frames = OrderedDict()
page_faults = 0
for page in pages:
if page not in frames:
if len(frames) == frame_size:
frames.popitem(last=False)
frames[page] = None
page_faults += 1
else:
frames.move_to_end(page)
return page_faults

pages = [7, 0, 1, 2, 0, 3, 0, 4, 2, 3, 0, 3, 2]
frame_size = 3
print(lru(pages, frame_size)) # Output: 10
OUTPUT

9
9. First fit, Best fit and Worst fit algorithm for memory
management.

def first_fit(memory, process_sizes):


allocated = [False] * len(memory)
for process_size in process_sizes:
for i in range(len(memory)):
if not allocated[i] and memory[i] >= process_size:
allocated[i] = True
memory[i] -= process_size
break
return allocated

def best_fit(memory, process_sizes):


allocated = [False] * len(memory)
for process_size in process_sizes:
min_diff = float('inf')
min_index = -1
for i in range(len(memory)):
if not allocated[i] and memory[i] >= process_size:
diff = memory[i] - process_size
if diff < min_diff:
min_diff = diff
min_index = i
if min_index != -1:
allocated[min_index] = True
memory[min_index] -= process_size
return allocated

def worst_fit(memory, process_sizes):


allocated = [False] * len(memory)
for process_size in process_sizes:
max_diff = -float('inf')
max_index = -1
for i in range(len(memory)):
if not allocated[i] and memory[i] >= process_size:
diff = memory[i] - process_size
if diff > max_diff:
max_diff = diff
max_index = i
if max_index != -1:
allocated[max_index] = True
memory[max_index] -= process_size
return allocated

memory = [10, 20, 30, 40, 50]


process_sizes = [5, 10, 15, 20]
print(first_fit(memory[:], process_sizes))
print(best_fit(memory[:], process_sizes))
print(worst_fit(memory[:], process_sizes))
OUTPUT

[True, True, True, True, False]


[True, True, True, True, False]
[False, True, True, True, True]
10. Inter-process Communication

import multiprocessing

def worker(conn):
conn.send("Hello from worker!")

if __name__ == "__main__":
parent_conn, child_conn = multiprocessing.Pipe()
p = multiprocessing.Process(target=worker, args=(child_conn,))
p.start()
print(parent_conn.recv())
p.join()
OUTPUT

Hello from worker!

You might also like