用python编程实现进程调度算法中的:时间片轮转调度算法和优先级调度算法(抢占式)
时间: 2023-11-28 07:51:01 浏览: 310
好的,以下是时间片轮转调度算法和优先级调度算法(抢占式)的Python实现。
时间片轮转调度算法:
```python
from collections import deque
class Process:
def __init__(self, pid, burst_time):
self.pid = pid
self.burst_time = burst_time
self.remaining_time = burst_time
def execute(self, time_slice):
if self.remaining_time <= time_slice:
time_slice = self.remaining_time
self.remaining_time -= time_slice
return time_slice
def is_completed(self):
return self.remaining_time == 0
class RoundRobinScheduler:
def __init__(self, time_slice):
self.time_slice = time_slice
self.processes = deque()
def add_process(self, process):
self.processes.append(process)
def run(self):
while len(self.processes) > 0:
process = self.processes.popleft()
time_slice = process.execute(self.time_slice)
if process.is_completed():
print("Process", process.pid, "completed")
else:
self.processes.append(process)
```
优先级调度算法(抢占式):
```python
from queue import PriorityQueue
class Process:
def __init__(self, pid, burst_time, priority):
self.pid = pid
self.burst_time = burst_time
self.remaining_time = burst_time
self.priority = priority
def execute(self, time_slice):
if self.remaining_time <= time_slice:
time_slice = self.remaining_time
self.remaining_time -= time_slice
return time_slice
def is_completed(self):
return self.remaining_time == 0
def __lt__(self, other):
return self.priority < other.priority
class PriorityPreemptiveScheduler:
def __init__(self):
self.processes = PriorityQueue()
def add_process(self, process):
self.processes.put(process)
def run(self):
time = 0
while not self.processes.empty():
process = self.processes.get()
time_slice = process.execute(1)
time += time_slice
if process.is_completed():
print("Process", process.pid, "completed at time", time)
else:
self.processes.put(process)
```
以上是时间片轮转调度算法和优先级调度算法(抢占式)的Python实现,希望能够帮到你。
阅读全文