编写一个采用先来先服务,最短作业优先,响应比高者优先的调度算法
时间: 2023-06-13 19:03:52 浏览: 131
以下是一个简单的调度算法的实现,其中包括先来先服务(FCFS)、最短作业优先(SJF)和响应比高者优先(HRRN):
```python
class Process:
def __init__(self, pid, arrival_time, burst_time):
self.pid = pid
self.arrival_time = arrival_time
self.burst_time = burst_time
self.start_time = 0
self.end_time = 0
self.wait_time = 0
self.turnaround_time = 0
self.response_ratio = 0
def fcfs(processes):
current_time = 0
for p in processes:
if p.arrival_time > current_time:
current_time = p.arrival_time
p.start_time = current_time
p.end_time = p.start_time + p.burst_time
p.turnaround_time = p.end_time - p.arrival_time
p.wait_time = p.turnaround_time - p.burst_time
current_time = p.end_time
return processes
def sjf(processes):
processes.sort(key=lambda x: x.burst_time)
current_time = 0
for p in processes:
if p.arrival_time > current_time:
current_time = p.arrival_time
p.start_time = current_time
p.end_time = p.start_time + p.burst_time
p.turnaround_time = p.end_time - p.arrival_time
p.wait_time = p.turnaround_time - p.burst_time
current_time = p.end_time
return processes
def hrrn(processes):
current_time = 0
for p in processes:
if p.arrival_time > current_time:
current_time = p.arrival_time
p.response_ratio = (current_time - p.arrival_time + p.burst_time) / p.burst_time
processes.sort(key=lambda x: x.response_ratio, reverse=True)
for p in processes:
p.start_time = current_time
p.end_time = p.start_time + p.burst_time
p.turnaround_time = p.end_time - p.arrival_time
p.wait_time = p.turnaround_time - p.burst_time
current_time = p.end_time
return processes
```
这里我们定义了一个 `Process` 类,包括进程ID、到达时间、执行时间、开始时间、结束时间、等待时间、周转时间和响应比等属性。`fcfs()`、`sjf()` 和 `hrrn()` 函数分别实现了先来先服务、最短作业优先和响应比高者优先算法。这些函数都返回一个进程列表,其中每个进程都更新了它的属性。
阅读全文