写一个使用优先数调度算法完成进程的调度和使用时间片轮转算法完成进程的调度的代码
时间: 2024-05-05 21:21:44 浏览: 86
优先数调度算法:
```python
class Process:
def __init__(self, name, priority, burst_time):
self.name = name
self.priority = priority
self.burst_time = burst_time
def __repr__(self):
return self.name
def run(self):
self.burst_time -= 1
def is_completed(self):
return self.burst_time == 0
class PriorityScheduler:
def __init__(self, processes):
self.processes = processes
self.current_process = None
def schedule(self):
if not self.current_process:
self.current_process = self.get_highest_priority_process()
elif self.current_process.is_completed():
self.processes.remove(self.current_process)
self.current_process = self.get_highest_priority_process()
self.current_process.run()
def get_highest_priority_process(self):
return max(self.processes, key=lambda p: p.priority)
# Example usage
processes = [
Process('P1', 2, 5),
Process('P2', 1, 3),
Process('P3', 2, 2),
Process('P4', 3, 4),
]
scheduler = PriorityScheduler(processes)
for i in range(15):
if scheduler.current_process:
print(f'Time {i}: {scheduler.current_process}')
scheduler.schedule()
```
时间片轮转算法:
```python
class Process:
def __init__(self, name, burst_time):
self.name = name
self.burst_time = burst_time
def __repr__(self):
return self.name
def run(self):
self.burst_time -= 1
def is_completed(self):
return self.burst_time == 0
class RoundRobinScheduler:
def __init__(self, processes, time_slice):
self.processes = processes
self.time_slice = time_slice
self.current_process = None
self.remaining_time = 0
def schedule(self):
if not self.current_process:
self.current_process = self.get_next_process()
self.current_process.run()
self.remaining_time -= 1
if self.remaining_time == 0:
self.processes.append(self.current_process)
self.current_process = None
def get_next_process(self):
if not self.processes:
return None
process = self.processes.pop(0)
self.remaining_time = min(self.time_slice, process.burst_time)
return process
# Example usage
processes = [
Process('P1', 5),
Process('P2', 3),
Process('P3', 2),
Process('P4', 4),
]
scheduler = RoundRobinScheduler(processes, time_slice=2)
for i in range(15):
if scheduler.current_process:
print(f'Time {i}: {scheduler.current_process}')
scheduler.schedule()
```
阅读全文