设计一个按先来先服务,算法时间片轮转法,优先数调度算法实现处理器调度的程序。
时间: 2023-11-27 13:52:32 浏览: 37
①设计进程控制块PCB表结构(与实验一的结构相同),分别适用于优先数调度算法和循环轮转调度算法。
4星 · 用户满意度95%
以下是一个简单的处理器调度程序的实现,包括先来先服务算法、时间片轮转算法和优先数调度算法。
```python
# 先来先服务算法
def FCFS(processes):
time = 0
for p in processes:
# 等待时间 = 当前时间 - 到达时间
p["wait_time"] = time - p["arrival_time"]
# 完成时间 = 当前时间 + 执行时间
time += p["burst_time"]
p["completion_time"] = time
# 周转时间 = 完成时间 - 到达时间
p["turnaround_time"] = p["completion_time"] - p["arrival_time"]
# 平均周转时间 = 所有进程的周转时间之和 / 进程数
avg_turnaround_time = sum(p["turnaround_time"] for p in processes) / len(processes)
# 平均等待时间 = 所有进程的等待时间之和 / 进程数
avg_wait_time = sum(p["wait_time"] for p in processes) / len(processes)
return avg_turnaround_time, avg_wait_time
# 时间片轮转算法
def RR(processes, quantum):
time = 0
queue = []
for p in processes:
queue.append(p)
while queue:
p = queue.pop(0)
# 如果进程未执行完,需要将其重新添加到队列中
if p["burst_time"] > quantum:
time += quantum
p["burst_time"] -= quantum
queue.append(p)
# 如果进程执行完了,计算各种时间并将其从队列中移除
else:
time += p["burst_time"]
p["completion_time"] = time
p["turnaround_time"] = p["completion_time"] - p["arrival_time"]
p["wait_time"] = p["turnaround_time"] - p["burst_time"]
avg_turnaround_time = sum(p["turnaround_time"] for p in processes) / len(processes)
avg_wait_time = sum(p["wait_time"] for p in processes) / len(processes)
return avg_turnaround_time, avg_wait_time
# 优先数调度算法
def priority_scheduling(processes):
time = 0
queue = []
for p in processes:
queue.append(p)
# 按照进程的优先级排序
queue.sort(key=lambda x: x["priority"], reverse=True)
while queue:
p = queue.pop(0)
time += p["burst_time"]
p["completion_time"] = time
p["turnaround_time"] = p["completion_time"] - p["arrival_time"]
p["wait_time"] = p["turnaround_time"] - p["burst_time"]
avg_turnaround_time = sum(p["turnaround_time"] for p in processes) / len(processes)
avg_wait_time = sum(p["wait_time"] for p in processes) / len(processes)
return avg_turnaround_time, avg_wait_time
```
以上代码仅供参考,实际应用中需要根据具体需求进行修改和完善。
阅读全文