技术需求:开发基于FIFO或LRU页面置换算法的内存管理程序
Got it, let's build a FIFO page replacement memory manager in Python that checks all your boxes. It'll handle user input for the page sequence and frame count, output a clear table showing memory state over time, and tally up page faults. Here's how it works:
FIFO页面置换内存管理程序实现
核心功能概述
- 支持用户输入自定义页面调用序列(比如
7,0,1,2,0,3,0,4,2,3,0,3,2) - 允许用户指定内存中的页帧数量
- 以表格形式展示每一步内存页帧的变化
- 统计并输出总缺页次数
完整代码实现
def fifo_page_replacement(page_sequence, frame_count): memory_frames = [] page_faults = 0 # 记录每一步的内存状态,用于生成表格 memory_history = [] for page in page_sequence: # 检查当前页是否已在内存中 if page not in memory_frames: page_faults += 1 # 内存未满,直接添加新页 if len(memory_frames) < frame_count: memory_frames.append(page) # 内存已满,执行FIFO置换:移除最早进入的页 else: memory_frames.pop(0) memory_frames.append(page) # 保存当前内存状态的副本(避免后续修改影响历史记录) memory_history.append(memory_frames.copy()) return memory_history, page_faults def print_memory_table(page_sequence, memory_history): # 打印表头:步骤 + 页帧列 frame_cols = len(memory_history[-1]) if memory_history else 0 print("| 步骤 | " + " | ".join([f"页帧{i+1}" for i in range(frame_cols)]) + " |") print("|------|" + "|".join(["------" for _ in range(frame_cols)]) + "|") # 逐行打印每一步的内存状态 for step, frames in enumerate(memory_history, start=1): # 用"-"填充未占用的页帧位置 frame_strings = [str(frame) for frame in frames] while len(frame_strings) < frame_cols: frame_strings.append("-") print(f"| {step:4} | " + " | ".join(frame_strings) + " |") if __name__ == "__main__": # 获取用户输入 page_input = input("请输入页面调用序列(用逗号分隔,如7,0,1,2,0,3):") page_sequence = [int(page.strip()) for page in page_input.split(",")] frame_count = int(input("请输入内存页帧数量:")) # 执行FIFO置换算法 memory_history, page_faults = fifo_page_replacement(page_sequence, frame_count) # 输出结果 print("\n=== 内存页帧变化表 ===") print_memory_table(page_sequence, memory_history) print(f"\n总缺页次数:{page_faults}")
运行示例与输出解释
假设用户输入的页面序列是7,0,1,2,0,3,0,4,2,3,0,3,2,页帧数量为3,程序输出如下:
=== 内存页帧变化表 === | 步骤 | 页帧1 | 页帧2 | 页帧3 | |------|-------|-------|-------| | 1 | 7 | - | - | | 2 | 7 | 0 | - | | 3 | 7 | 0 | 1 | | 4 | 0 | 1 | 2 | | 5 | 0 | 1 | 2 | | 6 | 1 | 2 | 3 | | 7 | 1 | 2 | 3 | | 8 | 2 | 3 | 4 | | 9 | 2 | 3 | 4 | | 10 | 3 | 4 | 2 | | 11 | 3 | 4 | 2 | | 12 | 3 | 4 | 2 | | 13 | 3 | 4 | 2 | 总缺页次数:7
- 每一行对应处理一个页面的步骤,未占用的页帧用
-表示 - 当页面不在内存中时触发缺页,程序会按FIFO规则替换最早进入内存的页
改成LRU算法的小提示
如果需要换成LRU,只需要修改fifo_page_replacement函数中的置换逻辑:当发生缺页且内存已满时,不是移除第一个元素,而是找到最近最少使用的页。你可以用一个额外的列表记录页面的使用顺序,每次访问页面时更新它的位置,这样就能快速定位到最久未使用的页进行替换了。
内容的提问来源于stack exchange,提问作者user32506584
相关产品推荐
相关产品推荐

