python实现进程调度算法完整代码1、 优先级进程调度算法 2、 时间片轮转进程调度算法
时间: 2024-06-21 10:02:04 浏览: 106
1、优先级进程调度算法的Python实现代码:
```python
class Process:
def __init__(self, pid, priority):
self.pid = pid
self.priority = priority
def priority_scheduling(processes):
# 按照优先级从高到低排序
processes.sort(key=lambda x: x.priority, reverse=True)
# 执行进程
for process in processes:
print("正在执行进程:", process.pid)
# 测试代码
if __name__ == '__main__':
# 创建进程列表
processes = [Process(1, 5), Process(2, 3), Process(3, 8), Process(4, 1), Process(5, 6)]
# 进行进程调度
priority_scheduling(processes)
```
2、时间片轮转进程调度算法的Python实现代码:
```python
class Process:
def __init__(self, pid, burst_time):
self.pid = pid
self.burst_time = burst_time
def round_robin_scheduling(processes, time_quantum):
# 创建等待队列
waiting_queue = []
# 将所有进程加入等待队列
for process in processes:
waiting_queue.append(process)
# 执行进程,直到所有进程执行完毕
while len(waiting_queue) > 0:
# 取出等待队列中的第一个进程
process = waiting_queue.pop(0)
# 判断剩余时间是否小于时间片
if process.burst_time <= time_quantum:
print("正在执行进程:", process.pid)
# 执行完毕,从进程列表中删除该进程
processes.remove(process)
else:
print("正在执行进程:", process.pid)
# 将剩余时间加入等待队列尾部
process.burst_time -= time_quantum
waiting_queue.append(process)
# 调整等待队列顺序,将当前进程放到队列末尾
waiting_queue.append(waiting_queue.pop(0))
# 测试代码
if __name__ == '__main__':
# 创建进程列表
processes = [Process(1, 10), Process(2, 5), Process(3, 8), Process(4, 3), Process(5, 7)]
# 进行进程调度
round_robin_scheduling(processes, 3)
```
阅读全文