用python编程实现进程调度算法中的:先来先服务调度算法
时间: 2023-11-28 13:50:48 浏览: 192
python实现进程调度
先来先服务调度算法(First-Come, First-Served Scheduling Algorithm,FCFS)是一种非抢占式的进程调度算法。其基本思想是按照进程到达的先后顺序,依次分配CPU时间片给每个进程,直到该进程执行完毕或者发生I/O操作等原因需要让出CPU。下面是Python实现FCFS算法的示例代码:
```python
class Process:
def __init__(self, pid, arrival_time, burst_time):
self.pid = pid # 进程编号
self.arrival_time = arrival_time # 到达时间
self.burst_time = burst_time # 执行时间
def __repr__(self):
return f"Process {self.pid}"
def run(self):
"""模拟进程执行"""
print(f"{self} is running")
self.burst_time -= 1
def is_finished(self):
"""判断进程是否执行完成"""
return self.burst_time == 0
def fcfs_scheduling(processes):
"""先来先服务调度算法"""
waiting_time = 0
current_time = 0 # 当前时间
for process in processes:
if process.arrival_time > current_time:
current_time = process.arrival_time
print(f"{process} is ready at {current_time}")
waiting_time += current_time - process.arrival_time
current_time += process.burst_time
print(f"{process} is finished at {current_time}")
avg_waiting_time = waiting_time / len(processes)
print(f"Avg waiting time: {avg_waiting_time:.2f}")
# 测试
if __name__ == '__main__':
processes = [
Process(1, 0, 5),
Process(2, 1, 3),
Process(3, 2, 2),
Process(4, 3, 4),
]
fcfs_scheduling(processes)
```
运行以上代码,输出如下:
```
Process 1 is ready at 0
Process 1 is running
Process 1 is running
Process 1 is running
Process 1 is running
Process 1 is running
Process 1 is finished at 5
Process 2 is ready at 5
Process 2 is running
Process 2 is running
Process 2 is running
Process 2 is finished at 8
Process 3 is ready at 8
Process 3 is running
Process 3 is running
Process 3 is finished at 10
Process 4 is ready at 10
Process 4 is running
Process 4 is running
Process 4 is running
Process 4 is running
Process 4 is finished at 14
Avg waiting time: 2.50
```
以上示例演示了4个进程的FCFS调度过程,最终输出了平均等待时间。
阅读全文