Created
December 7, 2024 01:37
-
-
Save jdtech3/7df27f210f47df9256ebd2df41c5e6aa to your computer and use it in GitHub Desktop.
Simulator for clock page replacement algorithm (created for ECE344: Operating Systems)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Page: | |
def __init__(self): | |
self.r = 0 | |
self.p = None | |
def __str__(self): | |
str(self.p) | |
def inc_clk(cur: int, max: int) -> int: | |
return cur + 1 if cur < max else 0 | |
def sim(mem_size: int, accesses: list[int]) -> list[tuple[list, bool]]: | |
pages = [Page() for _ in range(mem_size)] | |
results = [] | |
clk = 0 | |
pf = 0 | |
for access in accesses: | |
found = False | |
for page in pages: | |
if page.p == access: | |
page.r = 1 | |
found = True | |
if not found: | |
pf += 1 | |
while pages[clk].r != 0: | |
pages[clk].r = 0 | |
clk = inc_clk(clk, mem_size-1) | |
pages[clk].p = access | |
pages[clk].r = 1 | |
clk = inc_clk(clk, mem_size-1) | |
results.append(([p.p for p in pages], not found)) | |
print("\n-----------------------------------------------------------\n") | |
print_clk(pages, clk) | |
print_results(accesses, results) | |
return results | |
def print_clk(pages: list[Page], clk_ptr: int): | |
print("Page: ", end="") | |
for p in pages: | |
print(f"{p.p if p.p is not None else '-'} ", end="") | |
print("") | |
print("Ref: ", end="") | |
for p in pages: | |
print(f"{p.r} ", end="") | |
print("") | |
print(" ", end="") | |
print(f"{' '*clk_ptr}↑") | |
def print_results(access_order: list[int], results: list[tuple[list, bool]]): | |
print("\n" + "+---"*len(access_order) + "+") | |
print("| ", end="") | |
for a in access_order: | |
print(a, end=" | ") | |
print("\n" + "+---"*len(access_order) + "+") | |
for i in range(len(results[0][0])): | |
print("| ", end="") | |
for r in results: | |
print(r[0][i] if r[0][i] is not None else "-", end=" | ") | |
print("\n", end="") | |
print("+---"*len(access_order) + "+") | |
print("| ", end="") | |
for r in results: | |
print("F" if r[1] else " ", end=" | ") | |
print("\n" + "+---"*len(access_order) + "+") | |
print("") | |
if __name__ == "__main__": | |
num_pages = int(input("Number of physical pages (int > 0): ")) | |
access_order: list[int] = [int(a) for a in input("Access order (space sep int): ").split()] | |
results = sim( | |
num_pages, | |
access_order | |
) | |
# print_results(access_order, results) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment