#!/usr/bin/env python3 """ 先来先服务调度算法 (FCFS) First Come First Served 支持 IO 模拟 """ from typing import List, Dict, Tuple from collections import deque import heapq from base import ( Process, ProcessScheduler, generate_random_processes, print_processes ) class FCFSScheduler(ProcessScheduler): """先来先服务调度 (First Come First Served) 支持 IO 模拟: - 进程执行一个 CPU burst 后进入 IO 等待 - IO 等待期间 CPU 可以调度其他就绪进程 - IO 完成时进程回到就绪队列 """ def schedule(self) -> Dict: """FCFS 调度算法 (支持IO模拟)""" all_processes = list(self.processes) for p in all_processes: self.init_process(p, p.arrival_time) # 事件队列: (时间, 事件类型, 唯一ID, 进程) events = [] for p in all_processes: heapq.heappush(events, (p.arrival_time, 'arrival', id(p), p)) ready_queue = deque() # 就绪队列 (按到达顺序) completed = [] current_time = 0 last_processed_time = 0 while len(completed) < len(all_processes): # 1. 处理所有当前时刻的事件 while events and events[0][0] <= current_time: event_time, event_type, uid, p = heapq.heappop(events) if event_type == 'arrival': p.status = self.STATUS_READY ready_queue.append(p) elif event_type == 'io_complete': if p.status == self.STATUS_IO_WAIT: p.status = self.STATUS_READY ready_queue.append(p) # 2. 如果就绪队列为空,推进时间到下一个事件 if not ready_queue: if events: current_time = events[0][0] continue else: break # 3. FCFS: 选择队首进程 current_process = ready_queue.popleft() if current_process.start_time == -1: current_process.start_time = current_time current_process.status = self.STATUS_RUNNING # 4. 执行 CPU burst if current_process.current_cpu_idx < len(current_process.cpu_bursts): cpu_burst = current_process.cpu_bursts[current_process.current_cpu_idx] self.gantt_chart.append((current_time, current_process.pid, 'CPU', cpu_burst)) current_time += cpu_burst current_process.remaining_cpu_time -= cpu_burst current_process.current_cpu_idx += 1 # 5. 检查是否有 IO burst io_idx = current_process.current_cpu_idx - 1 if io_idx < len(current_process.io_bursts): # 进入 IO 等待,添加 IO 完成事件 io_time = current_process.io_bursts[io_idx] current_process.status = self.STATUS_IO_WAIT io_complete_time = current_time + io_time heapq.heappush(events, (io_complete_time, 'io_complete', id(current_process), current_process)) else: # 进程完成 current_process.status = self.STATUS_TERMINATED current_process.completion_time = current_time self.calculate_metrics(current_process, current_time) completed.append(current_process) else: # 进程完成 current_process.status = self.STATUS_TERMINATED current_process.completion_time = current_time self.calculate_metrics(current_process, current_time) completed.append(current_process) self.results = completed return self.print_results("FCFS (先来先服务)") if __name__ == "__main__": processes = generate_random_processes(n=5, seed=42, io_probability=0.5, io_first_prob=0.3) print_processes(processes, "测试数据") scheduler = FCFSScheduler(processes) scheduler.schedule()